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
refactor(actions): word the Do next sentence once, in the actions view (#3299)
Raghav Chamadiya674f9a316e39
diff --git a/packages/cli/src/repowise/cli/commands/next_cmd.py b/packages/cli/src/repowise/cli/commands/next_cmd.pyindex 3639411b7..860b5b13d 100644--- a/packages/cli/src/repowise/cli/commands/next_cmd.py+++ b/packages/cli/src/repowise/cli/commands/next_cmd.py@@ -6,7 +6,6 @@ Reads the same stored actions the web app's "Do next" and ``get_overview``'sfrom __future__ import annotations-from datetime import datetimefrom pathlib import Pathfrom typing import Any@@ -25,12 +24,6 @@ from repowise.cli.output import (PREVIEW = 5ALL = 20-TIER_HEADING = {- "act_now": "Now",- "plan": "Worth planning",- "improve_signal": "Improve what Repowise can see",-}-_TIER_COLOUR = {"act_now": "red", "plan": "yellow", "improve_signal": "cyan"}@@ -58,59 +51,25 @@ def load_view(root: Path) -> dict[str, Any] | None:return None-def work(view: dict[str, Any], horizon: str) -> tuple[int, int]:- """``(act_now + plan, act_now)`` for *horizon*: the part that is real work."""- by_tier = view["horizons"][horizon].get("by_tier", {})- now = int(by_tier.get("act_now", 0))- return now + int(by_tier.get("plan", 0)), now--def default_horizon(view: dict[str, Any]) -> str:"""The week, unless it holds no work and the quarter does (as the UI opens)."""- if work(view, "week")[0] == 0 and work(view, "quarter")[0] > 0:- return "quarter"- return "week"---def _plural(n: int, noun: str) -> str:- return f"{n:,} {noun}{'' if n == 1 else 's'}"+ from repowise.core.analysis.actions.summary import work+ week, quarter = (work(view["horizons"][h]) for h in ("week", "quarter"))+ return "quarter" if week == 0 and quarter > 0 else "week"-def _day(iso: str | None) -> str | None:- if not iso:- return None- try:- d = datetime.fromisoformat(iso)- except ValueError:- return None- return f"{d:%b} {d.day}"+def sentence(view: dict[str, Any], horizon: str) -> str:+ """The view's own sentence; worded by core here for a view that predates it."""+ found = (view.get("summary") or {}).get(horizon)+ if found:+ return found+ from datetime import datetime-def status_sentence(view: dict[str, Any], horizon: str) -> str:- """Where things stand, in one sentence. Mirrors the web app's ``actionsStatus``.+ from repowise.core.analysis.actions.summary import summarize- It names the window because "this week" means the repository's last week- of commits, which is not always the calendar's.- """- total, now = work(view, horizon)- until = _day(view.get("anchor"))- if horizon == "week":- window = f"in the week to {until}, the last indexed commit" if until else "this week"- else:- window = "this quarter"- if total == 0:- other = "quarter" if horizon == "week" else "week"- other_total = work(view, other)[0]- if other_total == 0:- return f"Nothing stands out {window}."- if horizon == "week":- verb = "is" if other_total == 1 else "are"- tail = f"{verb} worth planning this quarter"- else:- tail = "came up this week"- return f"Nothing needs you {window}. {_plural(other_total, 'thing')} {tail}."- now_part = f", {now} of them now" if now else ""- return f"{_plural(total, 'thing')} worth doing {window}{now_part}."+ anchor = view.get("anchor")+ return summarize(view["horizons"], datetime.fromisoformat(anchor) if anchor else None)[horizon]def render_title(title: str) -> str:@@ -141,10 +100,13 @@ def _render_action(action: dict[str, Any]) -> None:def render(view: dict[str, Any], horizon: str, limit: int) -> None:from rich.markup import escape+ from repowise.core.analysis.actions import TIER_LABELS+ from repowise.core.analysis.actions.rules._text import plural+h = view["horizons"][horizon]- console.print(f"[bold]{escape(status_sentence(view, horizon))}[/bold]")+ console.print(f"[bold]{escape(sentence(view, horizon))}[/bold]")shown = h["actions"][:limit]- for tier, heading in TIER_HEADING.items():+ for tier, heading in TIER_LABELS.items():rows = [a for a in shown if a["tier"] == tier]if not rows:continue@@ -160,7 +122,7 @@ def render(view: dict[str, Any], horizon: str, limit: int) -> None:more = "" if limit >= ALL else " [bold]--all[/bold] shows up to 20."console.print(f"[dim]Showing {len(shown)} of {total}.{more}[/dim]")if h.get("hidden"):- console.print(f"[dim]{_plural(h['hidden'], 'action')} dismissed, snoozed or done.[/dim]")+ console.print(f"[dim]{plural(h['hidden'], 'action')} dismissed, snoozed or done.[/dim]")unavailable = sorted(view.get("unavailable") or {})if unavailable:console.print(diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.pyindex 8c7957fd4..7a4e24687 100644--- a/packages/cli/src/repowise/cli/commands/status_cmd.py+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py@@ -347,11 +347,11 @@ def _next_actions_lines(view: dict | None) -> list[str]:return []from rich.markup import escape- from repowise.cli.commands.next_cmd import default_horizon, render_title, status_sentence+ from repowise.cli.commands.next_cmd import default_horizon, render_title, sentence# The week's sentence names both windows when the week is quiet; the row# under it comes from whichever window ``repowise next`` would open on.- lines = [f"[bold]Next:[/bold] {escape(status_sentence(view, 'week'))}"]+ lines = [f"[bold]Next:[/bold] {escape(sentence(view, 'week'))}"]horizon = default_horizon(view)top = next((a for a in view["horizons"][horizon]["actions"] if a["tier"] in ("act_now", "plan")),diff --git a/packages/core/src/repowise/core/analysis/actions/__init__.py b/packages/core/src/repowise/core/analysis/actions/__init__.pyindex cec14a391..970b37033 100644--- a/packages/core/src/repowise/core/analysis/actions/__init__.py+++ b/packages/core/src/repowise/core/analysis/actions/__init__.py@@ -19,6 +19,7 @@ from .model import (HORIZONS,RULE_STATUSES,TARGET_KINDS,+ TIER_LABELS,Action,RuleOutcome,)@@ -33,6 +34,7 @@ __all__ = ["RULES","RULE_STATUSES","TARGET_KINDS",+ "TIER_LABELS","Action","ActionStateRecord","RepoFacts",diff --git a/packages/core/src/repowise/core/analysis/actions/engine.py b/packages/core/src/repowise/core/analysis/actions/engine.pyindex f5c759052..a1b0231ca 100644--- a/packages/core/src/repowise/core/analysis/actions/engine.py+++ b/packages/core/src/repowise/core/analysis/actions/engine.py@@ -14,6 +14,7 @@ from .context import RepoContext, build_contextfrom .facts import RepoFactsfrom .model import HORIZONS, RULE_RANK, TIER_RANK, Action, RuleOutcomefrom .rules import code, hygiene, signal+from .summary import summarizeRule = Callable[[RepoFacts, RepoContext], RuleOutcome]@@ -137,5 +138,6 @@ def compose_actions("history_too_short": ctx.history_too_short,},"horizons": horizons,+ "summary": summarize(horizons, facts.anchor),"rules": [o.as_dict() for o in outcomes],}diff --git a/packages/core/src/repowise/core/analysis/actions/model.py b/packages/core/src/repowise/core/analysis/actions/model.pyindex df8e89020..47e444e5e 100644--- a/packages/core/src/repowise/core/analysis/actions/model.py+++ b/packages/core/src/repowise/core/analysis/actions/model.py@@ -36,6 +36,13 @@ HORIZONS: tuple[str, ...] = get_args(Horizon)ActionTier = Literal["act_now", "plan", "improve_signal"]ACTION_TIERS: tuple[str, ...] = get_args(ActionTier)+#: The heading each tier is listed under, on every surface.+TIER_LABELS: dict[str, str] = {+ "act_now": "Now",+ "plan": "Worth planning",+ "improve_signal": "Improve what Repowise can see",+}+#: Where a fact came from. ``unknown`` is a fact too: "coverage unknown" is#: printed, never read as zero.FactBasis = Literal["measured", "inferred", "unknown"]diff --git a/packages/core/src/repowise/core/analysis/actions/summary.py b/packages/core/src/repowise/core/analysis/actions/summary.pynew file mode 100644index 000000000..86dbb8ca2--- /dev/null+++ b/packages/core/src/repowise/core/analysis/actions/summary.py@@ -0,0 +1,46 @@+"""The one sentence that says where things stand, per horizon.++Composed here so the CLI, the web app and every other surface print the same+words; they render ``view["summary"][horizon]`` rather than rebuilding it.+"""++from __future__ import annotations++from datetime import datetime+from typing import Any++from .rules._text import plural+++def work(horizon: dict[str, Any]) -> int:+ """``act_now`` plus ``plan``: the part of a horizon that is real work."""+ by_tier = horizon.get("by_tier", {})+ return int(by_tier.get("act_now", 0)) + int(by_tier.get("plan", 0))+++def _sentence(horizons: dict[str, Any], name: str, anchor: datetime | None) -> str:+ # The window is named because "this week" is the repository's last week of+ # commits, which is not always the calendar's.+ if name == "week":+ until = f"{anchor:%b} {anchor.day}" if anchor else None+ window = f"in the week to {until}, the last indexed commit" if until else "this week"+ else:+ window = "this quarter"+ total = work(horizons[name])+ if total == 0:+ other = work(horizons["quarter" if name == "week" else "week"])+ if other == 0:+ return f"Nothing stands out {window}."+ if name == "week":+ tail = f"{'is' if other == 1 else 'are'} worth planning this quarter"+ else:+ tail = "came up this week"+ return f"Nothing needs you {window}. {plural(other, 'thing')} {tail}."+ now = int(horizons[name].get("by_tier", {}).get("act_now", 0))+ now_part = f", {now} of them now" if now else ""+ return f"{plural(total, 'thing')} worth doing {window}{now_part}."+++def summarize(horizons: dict[str, Any], anchor: datetime | None) -> dict[str, str]:+ """``{horizon: sentence}`` over the ranked horizons ``compose_actions`` built."""+ return {name: _sentence(horizons, name, anchor) for name in horizons}diff --git a/packages/server/src/repowise/server/schemas/actions.py b/packages/server/src/repowise/server/schemas/actions.pyindex b5efc8919..d337eb193 100644--- a/packages/server/src/repowise/server/schemas/actions.py+++ b/packages/server/src/repowise/server/schemas/actions.py@@ -89,6 +89,9 @@ class ActionsResponse(BaseModel):week_start: str | Nonecontext: ActionContexthorizons: dict[Literal["week", "quarter"], ActionHorizon]+ summary: dict[Literal["week", "quarter"], str] = Field(+ description="Where things stand in each horizon, in one sentence."+ )rules: list[ActionRuleStatus]unavailable: dict[str, str]diff --git a/packages/types/src/actions.ts b/packages/types/src/actions.tsindex 72bd9bc1d..099cdb215 100644--- a/packages/types/src/actions.ts+++ b/packages/types/src/actions.ts@@ -25,6 +25,13 @@ export type ActionHorizonKey = "week" | "quarter";/** `act_now` is wrong or got worse; `plan` is worth scheduling; `improve_signal` sharpens the other two. */export type ActionTier = "act_now" | "plan" | "improve_signal";+/** The heading each tier is listed under; core's `TIER_LABELS`, pinned by the parity test. */+export const ACTION_TIER_LABELS: Record<ActionTier, string> = {+ act_now: "Now",+ plan: "Worth planning",+ improve_signal: "Improve what Repowise can see",+};+/** `unknown` is printed as a fact, never read as zero. */export type ActionFactBasis = "measured" | "inferred" | "unknown";@@ -139,6 +146,11 @@ export interface ActionsResponse {history_too_short: boolean;};horizons: Record<ActionHorizonKey, ActionHorizon>;+ /**+ * Where things stand in each horizon, in one sentence, worded by core so+ * every surface says the same thing. Absent from a server that predates it.+ */+ summary?: Record<ActionHorizonKey, string>;rules: ActionRuleReport[];/** Store name to why it could not be read. */unavailable: Record<string, string>;diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.tsindex be4885974..034c7b0a2 100644--- a/packages/types/src/generated/http.ts+++ b/packages/types/src/generated/http.ts@@ -85,6 +85,8 @@ export interface ActionsResponse {week_start: string | null;context: ActionContext;horizons: Record<string, ActionHorizon>;+ /** Where things stand in each horizon, in one sentence. */+ summary: Record<string, string>;rules: ActionRuleStatus[];unavailable: Record<string, string>;}diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsxindex 047b467a7..939ce68a2 100644--- a/packages/ui/__tests__/overview/next-actions.test.tsx+++ b/packages/ui/__tests__/overview/next-actions.test.tsx@@ -2,7 +2,7 @@ import { describe, expect, it, vi } from "vitest";import { fireEvent, render, screen, waitFor, within } from "@testing-library/react";import type { ActionsResponse, NextAction } from "@repowise-dev/types/actions";-import { NextActions, actionsStatus } from "../../src/overview/next-actions.js";+import { NextActions } from "../../src/overview/next-actions.js";import { actionHref } from "../../src/overview/action-href.js";function action(overrides: Partial<NextAction> = {}): NextAction {@@ -112,6 +112,31 @@ describe("NextActions", () => {expect(onSetState.mock.calls[0]?.[0].fingerprint).toBe("fp1");});+ it("still says everything is answered once the re-read view drops the row", async () => {+ const onSetState = vi.fn().mockResolvedValue(undefined);+ const before = response([], [action()]);+ const { rerender } = render(+ <NextActions data={before} hrefFor={() => null} onSetState={onSetState} />,+ );+ const chip = () => screen.getByRole("radio", { name: /This quarter/ });+ expect(chip()).toHaveTextContent("1");+ fireEvent.click(screen.getByRole("button", { name: /More for Raise test coverage/ }));+ fireEvent.click(await screen.findByText("Dismiss"));+ // Until the re-read lands, the count stays with the view, as the sentence does.+ expect(chip()).toHaveTextContent("1");+ await waitFor(() => expect(onSetState).toHaveBeenCalledTimes(1));++ const after = response([], []);+ after.horizons.quarter.hidden = 1;+ rerender(<NextActions data={after} hrefFor={() => null} onSetState={onSetState} />);+ expect(screen.getByText(/You have answered everything listed here/)).toBeInTheDocument();+ expect(screen.queryByText(/none of them produced work/)).toBeNull();+ expect(chip()).toHaveTextContent("0");+ // The other time frame held nothing to answer, so it reads as empty.+ fireEvent.click(screen.getByRole("radio", { name: /This week/ }));+ expect(screen.getByText(/none of them produced work/)).toBeInTheDocument();+ });+it("brings a row back when the write fails", async () => {const onSetState = vi.fn().mockRejectedValue(new Error("nope"));render(@@ -160,21 +185,21 @@ describe("the action drawer", () => {});});-describe("actionsStatus", () => {- it("names the window by its last indexed commit and counts work only", () => {- const now = action({ tier: "act_now", horizons: ["week"] });- const signal = action({ id: "s", tier: "improve_signal", horizons: ["week"] });- const text = actionsStatus(response([now, signal], []), "week");- expect(text).toMatch(/^1 thing worth doing in the week to /);- expect(text).toMatch(/1 of them now\.$/);+describe("the status sentence", () => {+ it("renders the sentence core wrote for the open time frame", () => {+ const data = {+ ...response([], [action()]),+ summary: { week: "Core wording, week.", quarter: "Core wording, quarter." },+ };+ render(<NextActions data={data} hrefFor={() => null} />);+ expect(screen.getByText("Core wording, quarter.")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("radio", { name: /This week/ }));+ expect(screen.getByText("Core wording, week.")).toBeInTheDocument();});- it("points to the other time frame when this one is clear", () => {- expect(actionsStatus(response([], [action()]), "week")).toBe(- "Nothing needs you in the week to " +- new Date("2026-09-28T09:45:08").toLocaleDateString(undefined, { month: "short", day: "numeric" }) +- ", the last indexed commit. 1 thing is worth planning this quarter.",- );+ it("shows no sentence from a server that predates it", () => {+ render(<NextActions data={response([], [action()])} hrefFor={() => null} />);+ expect(screen.queryByText(/worth doing|Nothing/)).toBeNull();});});diff --git a/packages/ui/src/overview/action-drawer.tsx b/packages/ui/src/overview/action-drawer.tsxindex 69ba7c5cf..e2e12cc90 100644--- a/packages/ui/src/overview/action-drawer.tsx+++ b/packages/ui/src/overview/action-drawer.tsx@@ -2,11 +2,12 @@import { useCallback, useState, type ElementType, type ReactNode } from "react";import { ArrowUpRight, BellOff, Check, X } from "lucide-react";-import type {- ActionDetail,- ActionStateValue,- ActionSurface,- NextAction,+import {+ ACTION_TIER_LABELS,+ type ActionDetail,+ type ActionStateValue,+ type ActionSurface,+ type NextAction,} from "@repowise-dev/types/actions";import { AiPromptBlock } from "../health/ai-prompt-modal";@@ -17,12 +18,6 @@ import { SeverityMark } from "../health/severity-mark";import type { Severity } from "../health/tokens";import { AdaptivePanel } from "../shared/adaptive-panel";-const TIER_LABEL: Record<NextAction["tier"], string> = {- act_now: "Do now",- plan: "Worth planning",- improve_signal: "Improve what Repowise can see",-};-/** What the evidence link opens, named for the place it lands. */const EVIDENCE_LABEL: Record<ActionSurface, string> = {file: "Open the file",@@ -102,7 +97,7 @@ export function ActionDrawer({onOpenChange={(open) => {if (!open) onClose();}}- eyebrow={action ? TIER_LABEL[action.tier] : "Next action"}+ eyebrow={action ? ACTION_TIER_LABELS[action.tier] : "Next action"}title={action ? renderTitle(action.title) : "Next action"}widthClassName="md:max-w-[680px]">diff --git a/packages/ui/src/overview/index.ts b/packages/ui/src/overview/index.tsindex 5eb116aaa..dd8fcdeb6 100644--- a/packages/ui/src/overview/index.ts+++ b/packages/ui/src/overview/index.ts@@ -41,7 +41,7 @@ export type { AttentionRowItem } from "./attention-rows";export { HotspotTable } from "./hotspot-table";export { actionHref } from "./action-href";-export { NextActions, actionsStatus, renderActionTitle } from "./next-actions";+export { NextActions, renderActionTitle } from "./next-actions";export type { NextActionsProps } from "./next-actions";export { ExploreList } from "./explore-list";export type { ExploreEntry } from "./explore-list";diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsxindex 216d0868f..5a4df94f8 100644--- a/packages/ui/src/overview/next-actions.tsx+++ b/packages/ui/src/overview/next-actions.tsx@@ -3,12 +3,13 @@import { Fragment, useMemo, useState, type ElementType, type ReactNode } from "react";import { BellOff, Check, PanelRight, X } from "lucide-react";import { toast } from "sonner";-import type {- ActionHorizonKey,- ActionsResponse,- ActionStateValue,- ActionTier,- NextAction,+import {+ ACTION_TIER_LABELS,+ type ActionHorizonKey,+ type ActionsResponse,+ type ActionStateValue,+ type ActionTier,+ type NextAction,} from "@repowise-dev/types/actions";import { EFFORT_LABEL } from "../health/labels";@@ -22,19 +23,16 @@ import { OverviewSection } from "./section";/** Rows shown before "Show all"; the response carries up to 20 per horizon. */const PREVIEW = 5;-const TIER_HEADING: Record<ActionTier, string> = {- act_now: "Now",- plan: "Worth planning",- improve_signal: "Improve what Repowise can see",-};-export interface NextActionsProps {/** `null` when the server predates actions; the section then renders nothing. */data: ActionsResponse | null;hrefFor: (action: NextAction) => string | null;/** A file's own page, for the files an opened action names. */fileHref?: ((path: string) => string | null) | undefined;- /** Persist a dismissal, snooze, done, or (null) an undo. Omit to hide those verbs. */+ /**+ * Persist a dismissal, snooze, done, or (null) an undo. Omit to hide those verbs.+ * The sentence over the list is the server's, so pass fresh `data` after a write.+ */onSetState?: (action: NextAction, state: ActionStateValue | null) => Promise<void>;/** An action's agent prompt as core renders it. Omit to hide the prompt. */loadPrompt?: ActionDrawerProps["loadPrompt"];@@ -65,50 +63,6 @@ function plural(n: number, noun: string): string {return `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`;}-function formatDay(iso: string | null): string | null {- if (!iso) return null;- const d = new Date(iso);- return Number.isNaN(d.getTime())- ? null- : d.toLocaleDateString(undefined, { month: "short", day: "numeric" });-}--/**- * The one sentence that says where things stand. Counts the list as the reader- * sees it, and names the window, because "this week" means the repository's- * last week of commits, which is not always the calendar's.- */-export function actionsStatus(- data: ActionsResponse,- horizon: ActionHorizonKey,- answered: ReadonlySet<string> = new Set(),-): string {- const h = data.horizons[horizon];- const gone = (tier: ActionTier) =>- h.actions.filter((a) => a.tier === tier && answered.has(a.id)).length;- const now = (h.by_tier.act_now ?? 0) - gone("act_now");- const work = now + (h.by_tier.plan ?? 0) - gone("plan");- const until = formatDay(data.anchor);- const window =- horizon === "week"- ? until- ? `in the week to ${until}, the last indexed commit`- : "this week"- : "this quarter";- if (work === 0) {- const other = horizon === "week" ? data.horizons.quarter : data.horizons.week;- const otherWork = (other.by_tier.act_now ?? 0) + (other.by_tier.plan ?? 0);- return otherWork > 0- ? `Nothing needs you ${window}. ${plural(otherWork, "thing")} ${- horizon === "week"- ? `${otherWork === 1 ? "is" : "are"} worth planning this quarter`- : "came up this week"- }.`- : `Nothing stands out ${window}.`;- }- return `${plural(work, "thing")} worth doing ${window}${now ? `, ${now} of them now` : ""}.`;-}-export function NextActions({data,hrefFor,@@ -121,19 +75,17 @@ export function NextActions({}: NextActionsProps) {// Open on the week unless it holds no work and the quarter does: a lone// "add a coverage report" is not a reason to show an empty week first.- const work = (key: ActionHorizonKey, less: ReadonlySet<string> = new Set()) =>- data- ? (data.horizons[key].by_tier.act_now ?? 0) +- (data.horizons[key].by_tier.plan ?? 0) -- data.horizons[key].actions.filter((a) => a.tier !== "improve_signal" && less.has(a.id))- .length- : 0;+ // Counts come from `data` alone, like the sentence, so the two agree; both+ // move when the host passes the re-read view after an answer.+ const work = (key: ActionHorizonKey) =>+ data ? (data.horizons[key].by_tier.act_now ?? 0) + (data.horizons[key].by_tier.plan ?? 0) : 0;const initial: ActionHorizonKey = work("week") === 0 && work("quarter") > 0 ? "quarter" : "week";const [horizon, setHorizon] = useState<ActionHorizonKey>(initial);const [expanded, setExpanded] = useState(false);// Optimistic: a row the person answered leaves at once and comes back if the- // write fails.- const [answered, setAnswered] = useState<ReadonlySet<string>>(new Set());+ // write fails. Kept by id with the action, so "answered everything" still+ // knows its time frame once a re-read drops the row.+ const [answered, setAnswered] = useState<ReadonlyMap<string, NextAction>>(new Map());const [opened, setOpened] = useState<NextAction | null>(null);const rows = useMemo(@@ -149,10 +101,10 @@ export function NextActions({const answer = (action: NextAction, state: ActionStateValue, message: string) => {if (!onSetState) return;- setAnswered((s) => new Set(s).add(action.id));+ setAnswered((s) => new Map(s).set(action.id, action));const restore = () =>setAnswered((s) => {- const next = new Set(s);+ const next = new Map(s);next.delete(action.id);return next;});@@ -178,14 +130,14 @@ export function NextActions({return (<OverviewSectiontitle="Do next"- description={actionsStatus(data, horizon, answered)}+ description={data.summary?.[horizon] ?? ""}action={<Segmentedlabel="Time frame"value={horizon}options={[- { value: "week", label: "This week", count: String(work("week", answered)), hint: "What the last 7 days of commits changed" },- { value: "quarter", label: "This quarter", count: String(work("quarter", answered)), hint: "What the last 90 days say is worth planning" },+ { value: "week", label: "This week", count: String(work("week")), hint: "What the last 7 days of commits changed" },+ { value: "quarter", label: "This quarter", count: String(work("quarter")), hint: "What the last 90 days say is worth planning" },]}onChange={(v) => {setHorizon(v);@@ -194,7 +146,7 @@ export function NextActions({/>}>- {shown.length === 0 && answered.size > 0 && h.actions.length > 0 ? (+ {shown.length === 0 && [...answered.values()].some((a) => a.horizons.includes(horizon)) ? (<p className="py-2 text-sm text-[var(--color-text-secondary)]">You have answered everything listed here. Answers are kept until the facts change.</p>@@ -205,7 +157,7 @@ export function NextActions({{groupByTier(shown).map(([tier, items]) => (<div key={tier} className="flex flex-col"><h3 className="pb-1 pt-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)] first:pt-0">- {TIER_HEADING[tier]}+ {ACTION_TIER_LABELS[tier]}</h3><ul className="flex flex-col divide-y divide-[var(--color-border-default)]">{items.map((action) => (diff --git a/packages/web/src/components/overview/next-actions-panel.tsx b/packages/web/src/components/overview/next-actions-panel.tsxindex 947bd1a38..71dae5220 100644--- a/packages/web/src/components/overview/next-actions-panel.tsx+++ b/packages/web/src/components/overview/next-actions-panel.tsx@@ -1,19 +1,33 @@"use client";import Link from "next/link";-import { useCallback } from "react";+import { useCallback, useEffect } from "react";+import useSWR from "swr";import type { ActionsResponse, NextAction } from "@repowise-dev/types/actions";import type { AgentPromptFlavor } from "@repowise-dev/types/agent-prompts";import { NextActions } from "@repowise-dev/ui/overview/next-actions";import { actionHref } from "@repowise-dev/ui/overview";import { fileEntityPath } from "@repowise-dev/ui/shared/entity";-import { getActionPrompt, setActionState } from "@/lib/api/actions";+import { getActionPrompt, getActions, setActionState } from "@/lib/api/actions";/*** The local app's binding for "Do next": its routes and its write path. The* list itself, and every word on it, is the shared component.*/export function NextActionsPanel({ repoId, data }: { repoId: string; data: ActionsResponse }) {+ // The server-rendered view seeds the key; after an answer, revalidating it+ // re-reads the list so the sentence and counts say what is left. SWR keeps+ // only the latest response and keeps the last good view when a read fails.+ const key = `actions:${repoId}`;+ const { data: view, mutate } = useSWR(key, () => getActions(repoId), {+ fallbackData: data,+ revalidateOnMount: false,+ revalidateOnFocus: false,+ });+ // A newer server render (navigation, refresh) replaces whatever was cached.+ useEffect(() => {+ void mutate(data, { revalidate: false });+ }, [data, mutate]);const base = `/repos/${repoId}`;const loadPrompt = useCallback(async (action: NextAction, flavor: AgentPromptFlavor) =>@@ -22,7 +36,7 @@ export function NextActionsPanel({ repoId, data }: { repoId: string; data: Actio);return (<NextActions- data={data}+ data={view ?? data}loadPrompt={loadPrompt}LinkComponent={Link}hrefFor={(action) => actionHref(action, base)}@@ -32,6 +46,7 @@ export function NextActionsPanel({ repoId, data }: { repoId: string; data: Actiostate,fingerprint: action.fingerprint,});+ void mutate();}}/>);diff --git a/tests/unit/analysis/test_actions_summary.py b/tests/unit/analysis/test_actions_summary.pynew file mode 100644index 000000000..279b55e78--- /dev/null+++ b/tests/unit/analysis/test_actions_summary.py@@ -0,0 +1,54 @@+"""The Do next sentence: worded once in core and carried in the actions view."""++from __future__ import annotations++from datetime import UTC, datetime++from repowise.core.analysis.actions import RepoFacts, compose_actions+from repowise.core.analysis.actions.summary import summarize++ANCHOR = datetime(2026, 9, 28, 12, 0)+++def _h(**by_tier: int) -> dict:+ return {"actions": [], "total": sum(by_tier.values()), "hidden": 0, "by_tier": by_tier}+++def test_counts_work_and_names_the_week_by_its_last_commit() -> None:+ out = summarize({"week": _h(act_now=1, plan=2, improve_signal=4), "quarter": _h()}, ANCHOR)+ assert out["week"] == "3 things worth doing in the week to Sep 28, the last indexed commit, 1 of them now."+++def test_no_act_now_leaves_out_the_now_clause() -> None:+ out = summarize({"week": _h(), "quarter": _h(plan=2, improve_signal=1)}, ANCHOR)+ assert out["quarter"] == "2 things worth doing this quarter."+++def test_a_tz_aware_anchor_names_its_own_day() -> None:+ late = datetime(2026, 9, 28, 23, 30, tzinfo=UTC)+ out = summarize({"week": _h(plan=1), "quarter": _h(plan=1)}, late)+ assert out["week"] == "1 thing worth doing in the week to Sep 28, the last indexed commit."+++def test_a_clear_week_points_at_the_quarter() -> None:+ out = summarize({"week": _h(improve_signal=1), "quarter": _h(plan=1)}, ANCHOR)+ assert out["week"] == (+ "Nothing needs you in the week to Sep 28, the last indexed commit. "+ "1 thing is worth planning this quarter."+ )+ assert out["quarter"] == "1 thing worth doing this quarter."+++def test_a_clear_quarter_points_at_the_week_and_both_clear_says_so() -> None:+ out = summarize({"week": _h(plan=2), "quarter": _h()}, None)+ assert out["quarter"] == "Nothing needs you this quarter. 2 things came up this week."+ assert summarize({"week": _h(), "quarter": _h()}, None) == {+ "week": "Nothing stands out this week.",+ "quarter": "Nothing stands out this quarter.",+ }+++def test_the_view_carries_one_sentence_per_horizon() -> None:+ view = compose_actions(RepoFacts(anchor=ANCHOR), now=ANCHOR)+ assert view["summary"] == summarize(view["horizons"], ANCHOR)+ assert set(view["summary"]) == set(view["horizons"])diff --git a/tests/unit/cli/test_next_cmd.py b/tests/unit/cli/test_next_cmd.pyindex 77fe6b48a..8ccb93d30 100644--- a/tests/unit/cli/test_next_cmd.py+++ b/tests/unit/cli/test_next_cmd.py@@ -17,6 +17,7 @@ from click.testing import CliRunnerfrom repowise.cli.commands import next_cmd, status_cmdfrom repowise.cli.commands.next_cmd import next_command+from repowise.core.analysis.actions.summary import summarizedef _action(n: int, tier: str, title: str, **extra: Any) -> dict[str, Any]:@@ -52,12 +53,14 @@ def _horizon(actions: list[dict[str, Any]], total: int | None = None) -> dict[stdef _view(week: list[dict], quarter: list[dict], **extra: Any) -> dict[str, Any]:+ horizons = {"week": _horizon(week), "quarter": _horizon(quarter)}return {"status": "available","anchor": "2026-09-28T12:00:00","week_start": "2026-09-21T12:00:00","context": {},- "horizons": {"week": _horizon(week), "quarter": _horizon(quarter)},+ "horizons": horizons,+ "summary": summarize(horizons, datetime.datetime(2026, 9, 28, 12)),"rules": [],"unavailable": {},**extra,@@ -76,6 +79,26 @@ def _run(*args: str) -> Any:return CliRunner().invoke(next_command, [*args, "--no-workspace"], catch_exceptions=False)+def test_prints_the_sentence_the_view_carries(canned, tmp_path: Path) -> None:+ view = _view([_action(1, "plan", "Do it")], [])+ view["summary"] = {"week": "Core wording, week.", "quarter": "Core wording, quarter."}+ canned(view)++ assert _run(str(tmp_path)).output.startswith("Core wording, week.")+ assert _run(str(tmp_path), "--horizon", "quarter").output.startswith("Core wording, quarter.")+ assert status_cmd._next_actions_lines(view)[0].endswith("Core wording, week.")+++def test_a_view_without_a_summary_is_worded_by_core(canned, tmp_path: Path) -> None:+ view = _view([_action(1, "act_now", "Fix `a`")], [])+ del view["summary"]+ canned(view)++ out = _run(str(tmp_path)).output+ assert out.startswith("1 thing worth doing in the week to Sep 28, the last indexed commit, 1 of them now.")+ assert status_cmd._next_actions_lines(view)[0].endswith("1 of them now.")++def test_groups_by_tier_under_the_status_sentence(canned, tmp_path: Path) -> None:week = [_action(1, "act_now", "Rotate the key in `src/settings.py`"),diff --git a/tests/unit/server/mcp/test_overview_next_actions.py b/tests/unit/server/mcp/test_overview_next_actions.pyindex ba6993c8d..d264c894e 100644--- a/tests/unit/server/mcp/test_overview_next_actions.py+++ b/tests/unit/server/mcp/test_overview_next_actions.py@@ -84,11 +84,15 @@ def test_compact_view_keeps_three_rows_and_names_unavailable_stores():"week": {"actions": rows, "total": 9, "hidden": 0, "by_tier": {"plan": 9}},"quarter": {"actions": [], "total": 0, "hidden": 0, "by_tier": {}},},+ "summary": {"week": "9 things worth doing this week.", "quarter": "Nothing."},"unavailable": {"security": "why", "performance": "why"},}block = compact_actions_view(view)+ # The agent reads counts; the sentence stays on the human surfaces.+ assert "summary" not in block+assert [a["id"] for a in block["week"]["actions"]] == ["act_0", "act_1", "act_2"]assert block["week"]["total"] == 9assert block["week"]["actions"][0]["target"] == {"kind": "file", "path": "a0.py"}diff --git a/tests/unit/server/test_actions_route.py b/tests/unit/server/test_actions_route.pyindex 4be1f620e..4af9f351b 100644--- a/tests/unit/server/test_actions_route.py+++ b/tests/unit/server/test_actions_route.py@@ -42,6 +42,7 @@ async def test_get_returns_the_actions_shape(actions_client: AsyncClient, sessioassert resp.status_code == 200body = ActionsResponse.model_validate(resp.json())assert set(body.horizons) == {"week", "quarter"}+ assert body.summary["quarter"].endswith(", 1 of them now.")(secret,) = [a for a in body.horizons["quarter"].actions if a.rule == "live_secret"]assert secret.tier == "act_now"assert len(body.rules) == 12diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.pyindex 7bdb2fa18..7b950abc8 100644--- a/tests/unit/server/test_wire_vocabulary_parity.py+++ b/tests/unit/server/test_wire_vocabulary_parity.py@@ -85,6 +85,15 @@ def test_action_vocabularies_match_python() -> None:assert _union_members(alias, "actions.ts") == set(values), alias+def test_action_tier_labels_match_python() -> None:+ from repowise.core.analysis.actions import TIER_LABELS++ text = (_TYPES_SRC / "actions.ts").read_text(encoding="utf-8")+ match = re.search(r"export const ACTION_TIER_LABELS[^=]*= \{(.*?)\};", text, re.DOTALL)+ assert match, "ACTION_TIER_LABELS is not declared in actions.ts"+ assert dict(re.findall(r'(\w+): "([^"]+)"', match.group(1))) == TIER_LABELS++def test_fix_first_vocabularies_match_python() -> None:from repowise.core.analysis.health.fix_first import (FIX_EFFORTS,