Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(actions): lead the Overview with "Do next", built from stored evidence (#2651)

Raghav Chamadiya655f33bae954
diff --git a/docs/agent/MCP_TOOLS.md b/docs/agent/MCP_TOOLS.md
index 463a25db3..1d1d3e9c7 100644
--- a/docs/agent/MCP_TOOLS.md
+++ b/docs/agent/MCP_TOOLS.md
@@ -224,7 +224,7 @@ Architecture summary, module map, and entry points.
| `repo` | string | No | *(workspace only)* Target repo alias, or `"all"` |
| `include` | list[string] | No | Opt-in blocks, any combination of `"content"`, `"outline"`, `"tour"`, `"decisions"`, `"graph"`, `"ownership"` (see below) |
-**Returns (default):** `title`, `content_md` (the overview essay's summary section), `key_modules` (name, path, outline section), `entry_points`, `architecture` (layer names, file counts, layer order), `code_health`, `git_health`, `_meta`, and in workspace mode a `workspace` footer. The response's `more` field names the opt-in blocks.
+**Returns (default):** `title`, `content_md` (the overview essay's summary section), `key_modules` (name, path, outline section), `entry_points`, `architecture` (layer names, file counts, layer order), `code_health`, `git_health`, `next_actions` (per horizon, week and quarter: the first three stored actions as `id`, `tier`, `title`, `impact`, `done_when`, `target`, with `total` and `by_tier`; `unavailable` names stores the index predates; replaced by `next_actions_reason` when they cannot be read), `_meta`, and in workspace mode a `workspace` footer. The response's `more` field names the opt-in blocks.
**Opt-in blocks** — omitted unless named in `include`, and not computed at all when they are not:
diff --git a/docs/reference/CLI_REFERENCE.md b/docs/reference/CLI_REFERENCE.md
index 42941dc90..a68cfd4ab 100644
--- a/docs/reference/CLI_REFERENCE.md
+++ b/docs/reference/CLI_REFERENCE.md
@@ -2,7 +2,7 @@
Complete reference for all `repowise` commands. For a guided introduction, see the [Quickstart](../start/QUICKSTART.md).
-Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `doc-drift`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
+Command list (in registration order): `augment`, `init`, `delete`, `generate-claude-md`, `costs`, `update`, `generate`, `dead-code`, `doc-drift`, `health`, `risk`, `overlap`, `decision`, `coverage`, `impacted-tests`, `search`, `ask`, `context`, `symbol`, `why`, `distill`, `expand`, `saved`, `security`, `corrections`, `export`, `hook`, `agents`, `uninstall`, `status`, `next`, `doctor`, `watch`, `serve`, `mcp`, `reindex`, `restyle`, `wiki-styles`, `whats-new`, `telemetry`, `login`, `logout`, `whoami`, `workspace`. Two more ship as separate console scripts, not subcommands: `repowise-augment`, `repowise-rewrite` (both hook entry points, not meant to be run by hand).
**Do you need an LLM key?** Most commands are pure index/analysis and never call an LLM. `init` never requires a key: without one it renders the wiki from structure. It calls an LLM only when a provider is resolvable or `--prose` is passed. The exceptions: `update` (unless `--index-only` or `--no-docs`), `generate`, `restyle`, `watch` (when it regenerates a page), `health --generate-code`, and `workspace add --docs`. Everything else, `search`, `dead-code`, `doc-drift`, `health`, `risk`, `impacted-tests`, `decision`, `coverage`, `security`, `export`, `mcp`, `reindex`, `doctor`, and so on, works index-only, with no provider configured.
@@ -26,7 +26,8 @@ Grouped by what you're trying to do, not alphabetically. `PATH` and flag details
[`symbol`](#repowise-symbol-symbol_id) ·
[`why`](#repowise-why-query) ·
[shared `ask`/`context`/`symbol`/`why` options](#shared-options-ask-context-symbol-why) ·
-[`status`](#repowise-status-path)
+[`status`](#repowise-status-path) ·
+[`next`](#repowise-next-path)
**Health and risk**
[`health`](#repowise-health-path) ·
@@ -701,6 +702,23 @@ repowise status --format json # machine-readable
In workspace mode, the table includes a **Docs** column with each repo's page count and a per-repo **Docs status** block listing skip reasons (e.g. `cost gate declined`) and the exact remediation command.
+For a single repo it ends with a short **Next** block: how many things are worth doing this week (or this quarter, when the week is quiet) and the first of them. `--format json` carries the counts as `next_actions`; `repowise next` has the list.
+
+---
+
+### `repowise next [PATH]`
+
+The few things worth doing next, ranked from the index. The same stored actions the web app's overview and MCP `get_overview` (`next_actions`) read, so all three agree.
+
+```bash
+repowise next # this week, or the quarter when the week holds no work
+repowise next --horizon quarter # the 90-day window
+repowise next --all # up to 20 rows instead of 5
+repowise next --format json # the whole stored view (--json also works)
+```
+
+Rows are grouped as **Now**, **Worth planning** and **Improve what Repowise can see**, each with its impact, the facts behind it, when it counts as done, and a command when one applies. An index built before a store existed names that store and suggests `repowise update` rather than reporting it as empty.
+
---
## Analysis Commands
diff --git a/packages/api-client/package.json b/packages/api-client/package.json
index e377e1c94..766fe2d48 100644
--- a/packages/api-client/package.json
+++ b/packages/api-client/package.json
@@ -34,6 +34,7 @@
"./meta": "./src/meta.ts",
"./modules": "./src/modules.ts",
"./overview": "./src/overview.ts",
+ "./actions": "./src/actions.ts",
"./pagination": "./src/pagination.ts",
"./owners": "./src/owners.ts",
"./pages": "./src/pages.ts",
diff --git a/packages/api-client/src/actions.ts b/packages/api-client/src/actions.ts
new file mode 100644
index 000000000..2c412015d
--- /dev/null
+++ b/packages/api-client/src/actions.ts
@@ -0,0 +1,28 @@
+import type {
+ ActionsResponse,
+ ActionStateRequest,
+ ActionStateResponse,
+ WorkspaceActionsResponse,
+} from "@repowise-dev/types/actions";
+import { apiGet, apiPut } from "./client";
+
+/** Both horizons in one call, so the week and quarter lenses switch without a fetch. */
+export async function getActions(repoId: string): Promise<ActionsResponse> {
+ return apiGet<ActionsResponse>(`/api/repos/${repoId}/actions`);
+}
+
+export async function setActionState(
+ repoId: string,
+ actionId: string,
+ body: ActionStateRequest,
+): Promise<ActionStateResponse> {
+ return apiPut<ActionStateResponse>(
+ `/api/repos/${repoId}/actions/${encodeURIComponent(actionId)}/state`,
+ body,
+ );
+}
+
+/** Each workspace repository's lead actions, plus the cross-repository ones. */
+export async function getWorkspaceActions(): Promise<WorkspaceActionsResponse> {
+ return apiGet<WorkspaceActionsResponse>("/api/workspace/actions");
+}
diff --git a/packages/cli/src/repowise/cli/commands/next_cmd.py b/packages/cli/src/repowise/cli/commands/next_cmd.py
new file mode 100644
index 000000000..3639411b7
--- /dev/null
+++ b/packages/cli/src/repowise/cli/commands/next_cmd.py
@@ -0,0 +1,211 @@
+"""``repowise next`` - the short list of things worth doing, from the index.
+
+Reads the same stored actions the web app's "Do next" and ``get_overview``'s
+``next_actions`` rank, so the terminal, the agent and the UI agree.
+"""
+
+from __future__ import annotations
+
+from datetime import datetime
+from pathlib import Path
+from typing import Any
+
+import click
+
+from repowise.cli.helpers import console, repo_index_session, resolve_command_target, run_async
+from repowise.cli.output import (
+ emit_json,
+ format_option,
+ json_option,
+ notice_console,
+ resolve_format,
+)
+
+#: Rows shown by default and with ``--all``. The stored view keeps 20 a horizon.
+PREVIEW = 5
+ALL = 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"}
+
+
+async def _read_view(root: Path) -> dict[str, Any] | None:
+ """The actions view for *root*, or ``None`` when there is no index to read."""
+ from repowise.core.persistence.crud.analysis.actions import load_actions_view
+
+ async with repo_index_session(root) as opened:
+ if opened is None:
+ return None
+ session, repo_id = opened
+ return await load_actions_view(session, repo_id)
+
+
+def load_view(root: Path) -> dict[str, Any] | None:
+ """:func:`_read_view`, and ``None`` on any failure.
+
+ The loader already reports a store missing from an older index as
+ ``unavailable``; this guard is for everything else, so ``status`` can call
+ it without risking its own output.
+ """
+ try:
+ return run_async(_read_view(root))
+ except Exception:
+ 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'}"
+
+
+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 status_sentence(view: dict[str, Any], horizon: str) -> str:
+ """Where things stand, in one sentence. Mirrors the web app's ``actionsStatus``.
+
+ 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}."
+
+
+def render_title(title: str) -> str:
+ """Rich markup for action text: the backtick spans (paths, symbols) set bold cyan."""
+ from rich.markup import escape
+
+ parts = title.split("`")
+ return "".join(
+ f"[bold cyan]{escape(p)}[/bold cyan]" if i % 2 else escape(p) for i, p in enumerate(parts)
+ )
+
+
+def _render_action(action: dict[str, Any]) -> None:
+ from rich.markup import escape
+
+ console.print(f" [bold]-[/bold] {render_title(action['title'])}")
+ if action.get("impact"):
+ console.print(f" [dim]{render_title(action['impact'])}[/dim]")
+ why = [f"{w['label']}: {w['value']}" for w in action.get("why") or []]
+ if why:
+ console.print(f" {escape(' · '.join(why))}")
+ if action.get("done_when"):
+ console.print(f" [dim]Done when: {render_title(action['done_when'])}[/dim]")
+ if action.get("command"):
+ console.print(f" [green]$ {escape(action['command'])}[/green]")
+
+
+def render(view: dict[str, Any], horizon: str, limit: int) -> None:
+ from rich.markup import escape
+
+ h = view["horizons"][horizon]
+ console.print(f"[bold]{escape(status_sentence(view, horizon))}[/bold]")
+ shown = h["actions"][:limit]
+ for tier, heading in TIER_HEADING.items():
+ rows = [a for a in shown if a["tier"] == tier]
+ if not rows:
+ continue
+ colour = _TIER_COLOUR[tier]
+ console.print()
+ console.print(f"[{colour}]{heading}[/{colour}]")
+ for action in rows:
+ _render_action(action)
+
+ console.print()
+ total = h.get("total", len(h["actions"]))
+ if total > len(shown):
+ 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]")
+ unavailable = sorted(view.get("unavailable") or {})
+ if unavailable:
+ console.print(
+ f"[dim]Not in this index yet: {escape(', '.join(unavailable))}. "
+ "Run [bold]repowise update[/bold] to add them.[/dim]"
+ )
+
+
[email protected]("path", required=False, default=None)
+ "--horizon",
+ type=click.Choice(["week", "quarter"]),
+ default=None,
+ help="Window to rank. Default: the week, or the quarter when the week holds no work.",
+)
[email protected]("--all", "show_all", is_flag=True, default=False, help="Show up to 20, not 5.")
[email protected]("--repo", "repo_alias", default=None, help="In workspace mode, target one repo.")
[email protected]("--no-workspace", is_flag=True, default=False, help="Force single-repo mode.")
+@format_option(help="Output format. json prints the whole stored view.")
+@json_option(help="Alias for --format json.")
+def next_command(
+ path: str | None,
+ horizon: str | None,
+ show_all: bool,
+ repo_alias: str | None,
+ no_workspace: bool,
+ fmt: str,
+ as_json: bool,
+) -> None:
+ """Show the few things worth doing next, ranked from the index."""
+ fmt = resolve_format(fmt, as_json)
+ target = resolve_command_target(
+ path=path, no_workspace_flag=no_workspace, repo_alias=repo_alias
+ )
+ target.notice(notice_console(fmt), command="next")
+ root = target.single_repo_path().resolve()
+ view = load_view(root)
+
+ if fmt == "json":
+ emit_json(view if view is not None else {"repo": str(root), "status": "unavailable"})
+ return
+ if view is None:
+ console.print(
+ "[yellow]No readable index here. Run 'repowise init' (or 'repowise update').[/yellow]"
+ )
+ return
+ render(view, horizon or default_horizon(view), ALL if show_all else PREVIEW)
diff --git a/packages/cli/src/repowise/cli/commands/status_cmd.py b/packages/cli/src/repowise/cli/commands/status_cmd.py
index 2d451ef0f..c1b97d6e3 100644
--- a/packages/cli/src/repowise/cli/commands/status_cmd.py
+++ b/packages/cli/src/repowise/cli/commands/status_cmd.py
@@ -311,6 +311,52 @@ def _query_health_line(repo_path: Path) -> str | None:
)
+def _load_actions(repo_path: Path) -> dict | None:
+ """The stored next-actions view, or ``None``; never raises (see ``next_cmd``)."""
+ try:
+ from repowise.cli.commands.next_cmd import load_view
+
+ return load_view(repo_path)
+ except Exception:
+ return None
+
+
+def _next_actions_summary(view: dict | None) -> dict | None:
+ """Counts only, for the json mode; ``repowise next --format json`` has the rows."""
+ if view is None:
+ return None
+ return {
+ "anchor": view.get("anchor"),
+ **{
+ name: {"total": h.get("total", 0), "by_tier": h.get("by_tier", {})}
+ for name, h in view["horizons"].items()
+ },
+ "unavailable": sorted(view.get("unavailable") or {}),
+ }
+
+
+def _next_actions_lines(view: dict | None) -> list[str]:
+ """The "Next" block: where things stand and the first thing worth doing."""
+ if view is None:
+ return []
+ from rich.markup import escape
+
+ from repowise.cli.commands.next_cmd import default_horizon, render_title, status_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'))}"]
+ horizon = default_horizon(view)
+ top = next(
+ (a for a in view["horizons"][horizon]["actions"] if a["tier"] in ("act_now", "plan")),
+ None,
+ )
+ if top is not None:
+ lines.append(f" {render_title(top['title'])}")
+ lines.append(" [dim]Run [bold]repowise next[/bold] for the list.[/dim]")
+ return lines
+
+
def _format_relative_time(iso_timestamp: str | None) -> str:
"""Format an ISO 8601 timestamp as a relative time string."""
if not iso_timestamp:
@@ -593,6 +639,7 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
"page_total": sum(counts.values()),
"page_tokens": total_db_tokens,
"health": _query_health(repo_path),
+ "next_actions": _next_actions_summary(_load_actions(repo_path) if has_db else None),
"index_scope": scope,
}
)
@@ -666,3 +713,9 @@ def status_command(path: str | None, workspace: bool, no_workspace: bool, fmt: s
if health_line:
console.print()
console.print(health_line)
+
+ next_lines = _next_actions_lines(_load_actions(repo_path))
+ if next_lines:
+ console.print()
+ for line in next_lines:
+ console.print(line)
diff --git a/packages/cli/src/repowise/cli/main.py b/packages/cli/src/repowise/cli/main.py
index ff516026f..a1acee827 100644
--- a/packages/cli/src/repowise/cli/main.py
+++ b/packages/cli/src/repowise/cli/main.py
@@ -88,6 +88,7 @@ _OSS_COMMANDS: tuple[tuple[str, str], ...] = (
("agents", "agents_cmd:agents_group"),
("uninstall", "uninstall_cmd:uninstall_command"),
("status", "status_cmd:status_command"),
+ ("next", "next_cmd:next_command"),
("doctor", "doctor_cmd:doctor_command"),
("watch", "watch_cmd:watch_command"),
("serve", "serve_cmd:serve_command"),
diff --git a/packages/core/alembic/versions/0083_action_states.py b/packages/core/alembic/versions/0083_action_states.py
new file mode 100644
index 000000000..c8d8ffc65
--- /dev/null
+++ b/packages/core/alembic/versions/0083_action_states.py
@@ -0,0 +1,48 @@
+"""Action states: a person's dismiss, snooze, or done on a next action.
+
+Next actions are computed on read, so this is the only stored half. Local
+SQLite stores never run Alembic -- ``init_db``'s reconciler creates the table --
+so this migration exists for managed Postgres and is guarded for that reason.
+
+Revision ID: 0083
+Revises: 0082
+Create Date: 2026-09-29
+"""
+
+from __future__ import annotations
+
+from collections.abc import Sequence
+
+import sqlalchemy as sa
+from alembic import op
+
+# revision identifiers
+revision: str = "0083"
+down_revision: str | None = "0082"
+branch_labels: str | Sequence[str] | None = None
+depends_on: str | Sequence[str] | None = None
+
+
+def upgrade() -> None:
+ if sa.inspect(op.get_bind()).has_table("action_states"):
+ return
+ op.create_table(
+ "action_states",
+ sa.Column("id", sa.String(32), primary_key=True),
+ sa.Column(
+ "repository_id",
+ sa.String(32),
+ sa.ForeignKey("repositories.id", ondelete="CASCADE"),
+ nullable=False,
+ ),
+ sa.Column("action_id", sa.String(32), nullable=False),
+ sa.Column("state", sa.String(16), nullable=False),
+ sa.Column("fingerprint", sa.String(32), nullable=False, server_default=""),
+ sa.Column("until", sa.DateTime(timezone=True), nullable=True),
+ sa.Column("updated_at", sa.DateTime(timezone=True), nullable=False),
+ sa.UniqueConstraint("repository_id", "action_id", name="uq_action_states"),
+ )
+
+
+def downgrade() -> None:
+ op.drop_table("action_states")
diff --git a/packages/core/src/repowise/core/analysis/actions/__init__.py b/packages/core/src/repowise/core/analysis/actions/__init__.py
new file mode 100644
index 000000000..34259fde7
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/__init__.py
@@ -0,0 +1,40 @@
+"""Next actions: stored evidence turned into a short list of things to do.
+
+The fold is pure (``engine.compose_actions`` over ``facts.RepoFacts``); the
+loader that reads the stores lives in
+``repowise.core.persistence.crud.analysis.actions``.
+"""
+
+from __future__ import annotations
+
+from .engine import RULES, ActionStateRecord, compose_actions
+from .facts import RepoFacts
+from .model import (
+ ACTION_RULES,
+ ACTION_STATES,
+ ACTION_SURFACES,
+ ACTION_TIERS,
+ FACT_BASES,
+ HORIZONS,
+ RULE_STATUSES,
+ TARGET_KINDS,
+ Action,
+ RuleOutcome,
+)
+
+__all__ = [
+ "ACTION_RULES",
+ "ACTION_STATES",
+ "ACTION_SURFACES",
+ "ACTION_TIERS",
+ "FACT_BASES",
+ "HORIZONS",
+ "RULES",
+ "RULE_STATUSES",
+ "TARGET_KINDS",
+ "Action",
+ "ActionStateRecord",
+ "RepoFacts",
+ "RuleOutcome",
+ "compose_actions",
+]
diff --git a/packages/core/src/repowise/core/analysis/actions/context.py b/packages/core/src/repowise/core/analysis/actions/context.py
new file mode 100644
index 000000000..2cff5e430
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/context.py
@@ -0,0 +1,84 @@
+"""Facts about the repository that decide which rules apply to it.
+
+The same rule set runs on a single-author side project and a forty-person
+monorepo. What changes is which rules can say anything true: ownership rules
+need more than one active author, test rules need to know whether coverage was
+measured, and "busy" means a different commit count in each.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+from datetime import UTC, datetime, timedelta
+
+from .facts import RepoFacts
+
+WEEK = timedelta(days=7)
+
+#: Below this many active authors in 90 days, ownership is the shape of the
+#: repository, not a risk in it.
+TEAM_MIN_AUTHORS = 3
+
+#: A file is busy when it clears both: a floor so a quiet repository does not
+#: call two commits "hot", and the repository's own 90th percentile so a busy
+#: one does not call every file hot.
+BUSY_FLOOR = 5
+BUSY_PERCENTILE = 0.9
+
+#: The same two-sided bar for bug-fix commits: at least three, and the
+#: repository's 95th percentile among files that had any, so "fixes keep
+#: landing" names the few files that stand out rather than every file touched
+#: by a fix.
+FIX_FLOOR = 3
+FIX_PERCENTILE = 0.95
+
+
+@dataclass(frozen=True, slots=True)
+class RepoContext:
+ anchor: datetime | None
+ week_start: datetime | None
+ production_files: int
+ active_authors_90d: int
+ busy_threshold: int
+ fix_threshold: int
+ fix_commits_90d: int
+
+ @property
+ def is_team(self) -> bool:
+ return self.active_authors_90d >= TEAM_MIN_AUTHORS
+
+ def in_week(self, when: datetime | None) -> bool:
+ if when is None or self.week_start is None:
+ return False
+ return _naive(when) >= _naive(self.week_start)
+
+
+def _naive(value: datetime) -> datetime:
+ # SQLite hands back naive datetimes and Postgres aware ones; compare in UTC
+ # wall time either way.
+ return value.astimezone(UTC).replace(tzinfo=None) if value.tzinfo else value
+
+
+def _percentile(values: list[int], q: float) -> int:
+ if not values:
+ return 0
+ ordered = sorted(values)
+ return ordered[min(len(ordered) - 1, int(len(ordered) * q))]
+
+
+def build_context(facts: RepoFacts) -> RepoContext:
+ production = [f for f in facts.files.values() if not f.is_test]
+ busy = _percentile([f.commits_90d for f in production if f.commits_90d > 0], BUSY_PERCENTILE)
+ fixes = _percentile(
+ [f.fix_commits_90d for f in production if f.fix_commits_90d > 0], FIX_PERCENTILE
+ )
+ anchor = facts.anchor
+ return RepoContext(
+ anchor=anchor,
+ week_start=(anchor - WEEK) if anchor else None,
+ production_files=len(production),
+ active_authors_90d=facts.active_authors_90d,
+ busy_threshold=max(BUSY_FLOOR, busy),
+ fix_threshold=max(FIX_FLOOR, fixes),
+ fix_commits_90d=facts.fix_commits_90d,
+ )
diff --git a/packages/core/src/repowise/core/analysis/actions/engine.py b/packages/core/src/repowise/core/analysis/actions/engine.py
new file mode 100644
index 000000000..1fc58e406
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/engine.py
@@ -0,0 +1,131 @@
+"""Run every rule, merge overlaps, apply user state, rank per horizon.
+
+Pure: facts and states in, a JSON-ready view out.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+from .context import RepoContext, build_context
+from .facts import RepoFacts
+from .model import HORIZONS, RULE_RANK, TIER_RANK, Action, RuleOutcome
+from .rules import code, hygiene, signal
+
+Rule = Callable[[RepoFacts, RepoContext], RuleOutcome]
+
+RULES: tuple[Rule, ...] = (
+ hygiene.live_secret,
+ code.fresh_regressions,
+ code.fragile_file,
+ code.fix_concentration,
+ code.hot_path_perf,
+ hygiene.stale_decision,
+ hygiene.knowledge_loss,
+ hygiene.broken_doc_refs,
+ hygiene.dead_code_batch,
+ signal.coverage_missing,
+ signal.coverage_stale,
+ signal.decisions_unreviewed,
+)
+
+#: Stored per horizon. The page shows fewer; the rest stay one click away and
+#: the total is always the full count.
+KEEP_PER_HORIZON = 20
+
+#: In the head of each tier, no rule takes more than this many places before
+#: every other rule with something to say has had one.
+PER_RULE_HEAD = 2
+
+
+@dataclass(frozen=True, slots=True)
+class ActionStateRecord:
+ state: str
+ fingerprint: str
+ until: datetime | None = None
+
+
+def _hidden(action: Action, record: ActionStateRecord | None, now: datetime) -> bool:
+ if record is None:
+ return False
+ if record.state == "snoozed":
+ return record.until is not None and _naive(record.until) > _naive(now)
+ # Dismissed and done both hold only while the facts are the ones the person
+ # saw. A dismissed "raise coverage" returns when ten more fixes land.
+ return record.fingerprint == action.fingerprint
+
+
+def _naive(value: datetime) -> datetime:
+ return value.astimezone(UTC).replace(tzinfo=None) if value.tzinfo else value
+
+
+def _order(actions: list[Action]) -> list[Action]:
+ ranked = sorted(
+ actions,
+ key=lambda a: (TIER_RANK[a.tier], RULE_RANK[a.rule], -a.weight, a.action_id),
+ )
+ out: list[Action] = []
+ for tier in sorted({a.tier for a in ranked}, key=TIER_RANK.__getitem__):
+ in_tier = [a for a in ranked if a.tier == tier]
+ head: list[Action] = []
+ rest: list[Action] = []
+ taken: dict[str, int] = {}
+ for a in in_tier:
+ if taken.get(a.rule, 0) < PER_RULE_HEAD:
+ head.append(a)
+ taken[a.rule] = taken.get(a.rule, 0) + 1
+ else:
+ rest.append(a)
+ out.extend(head + rest)
+ return out
+
+
+def compose_actions(
+ facts: RepoFacts,
+ states: Mapping[str, ActionStateRecord] | None = None,
+ *,
+ now: datetime,
+) -> dict[str, Any]:
+ ctx = build_context(facts)
+ outcomes = [rule(facts, ctx) for rule in RULES]
+ actions = [a for o in outcomes for a in o.actions]
+
+ states = states or {}
+ horizons: dict[str, Any] = {}
+ for horizon in HORIZONS:
+ pool = [a for a in actions if horizon in a.horizons]
+ # A folder action speaks for the fragile files inside it, in the time
+ # frame it appears in; listing both there tells one story twice. The
+ # week's regression roll-up names files too, but only as a starting
+ # point, so it absorbs nothing.
+ absorbed = {p for a in pool if a.rule == "fix_concentration" for p in a.includes}
+ pool = [a for a in pool if not (a.rule == "fragile_file" and a.target_path in absorbed)]
+ visible = [a for a in pool if not _hidden(a, states.get(a.action_id), now)]
+ ordered = _order(visible)
+ by_tier: dict[str, int] = {}
+ for a in ordered:
+ by_tier[a.tier] = by_tier.get(a.tier, 0) + 1
+ horizons[horizon] = {
+ "actions": [a.as_dict() for a in ordered[:KEEP_PER_HORIZON]],
+ "total": len(ordered),
+ "hidden": len(pool) - len(visible),
+ "by_tier": by_tier,
+ }
+
+ return {
+ "status": "available",
+ "anchor": facts.anchor.isoformat() if facts.anchor else None,
+ "week_start": ctx.week_start.isoformat() if ctx.week_start else None,
+ "context": {
+ "production_files": ctx.production_files,
+ "active_authors_90d": ctx.active_authors_90d,
+ "fix_commits_90d": ctx.fix_commits_90d,
+ "busy_threshold": ctx.busy_threshold,
+ "coverage": facts.coverage.status,
+ },
+ "horizons": horizons,
+ "rules": [o.as_dict() for o in outcomes],
+ }
diff --git a/packages/core/src/repowise/core/analysis/actions/facts.py b/packages/core/src/repowise/core/analysis/actions/facts.py
new file mode 100644
index 000000000..6cc49c981
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/facts.py
@@ -0,0 +1,155 @@
+"""The inputs the action rules read, as plain frozen records.
+
+A loader fills these from the stores; rules only read them. Every store is
+optional: a store the loader could not read is named in
+:attr:`RepoFacts.unavailable` with a reason, and a rule that needs it reports
+itself as not evaluated rather than as clear.
+"""
+
+from __future__ import annotations
+
+from collections.abc import Mapping
+from dataclasses import dataclass, field
+from datetime import datetime
+from typing import Literal
+
+CoverageStatus = Literal["measured", "stale", "unknown"]
+
+
+@dataclass(frozen=True, slots=True)
+class LeadFinding:
+ """A file's strongest code-shape finding: the thing an edit can fix."""
+
+ biomarker: str
+ severity: str
+ function: str | None
+ line: int | None
+ reason: str
+
+
+@dataclass(frozen=True, slots=True)
+class FileFacts:
+ path: str
+ is_test: bool
+ score: float | None
+ max_ccn: int | None
+ nloc: int | None
+ line_coverage_pct: float | None
+ commits_90d: int
+ last_commit_at: datetime | None
+ bug_magnet: bool
+ fix_commits_90d: int
+ bus_factor: int | None
+ owner_key: str | None
+ owner_name: str | None
+ owner_pct: float | None
+ dependents: int | None
+ lead: LeadFinding | None = None
+
+
+@dataclass(frozen=True, slots=True)
+class RecentFinding:
+ """A finding a commit in the recent window introduced or made worse."""
+
+ sha: str
+ subject: str
+ committed_at: datetime | None
+ file_path: str
+ symbol: str | None
+ biomarker: str
+ severity: str
+ change_kind: str
+ line: int | None
+ reason: str = ""
+
+
+@dataclass(frozen=True, slots=True)
+class PerfFacts:
+ opportunity_id: str
+ biomarker: str
+ boundary: str | None
+ file_path: str
+ symbol: str | None
+ call_sites: int
+ files: int
+ actionability: str
+ exposure: str | None
+ loop_magnitude: str | None
+ effort: str | None
+
+
+@dataclass(frozen=True, slots=True)
+class SecretFacts:
+ file_path: str
+ kind: str
+ line: int | None
+ snippet: str
+
+
+@dataclass(frozen=True, slots=True)
+class DriftFacts:
+ document: str
+ kind: str
+ target: str
+ #: The link as the document wrote it; ``target`` is normalised against the
+ #: document's own path, which turns a site-root `/#install` into a
+ #: same-file anchor that was never meant.
+ raw: str
+ line: int | None
+ reason: str
+ confidence: float
+ #: The target path appears in this repository's own history or tree, so the
+ #: document is describing something that was here. See ``rules.docs``.
+ target_known: bool
+
+
+@dataclass(frozen=True, slots=True)
+class DeadFacts:
+ finding_id: str
+ file_path: str
+ symbol: str | None
+ lines: int
+
+
+@dataclass(frozen=True, slots=True)
+class DecisionFacts:
+ id: str
+ title: str
+
+
+@dataclass(frozen=True, slots=True)
+class CoverageState:
+ status: CoverageStatus
+ ingested_at: datetime | None = None
+ files_measured: int = 0
+ #: The report's paths did not all map to this repository's files, so a
+ #: file without a row may be covered and simply unmatched.
+ partial: bool = False
+
+
+@dataclass(frozen=True, slots=True)
+class RepoFacts:
+ """Everything the rules may read about one repository."""
+
+ #: The newest commit the index holds. Windows are measured back from here,
+ #: not from the wall clock, so a quiet or archived repository still reads
+ #: in terms of its own last week of work.
+ anchor: datetime | None
+ files: Mapping[str, FileFacts] = field(default_factory=dict)
+ #: Distinct bug-fix commit shas in the last 90 days, per file.
+ fix_shas_by_file: Mapping[str, frozenset[str]] = field(default_factory=dict)
+ fix_commits_90d: int = 0
+ recent_findings: tuple[RecentFinding, ...] = ()
+ perf: tuple[PerfFacts, ...] = ()
+ secrets: tuple[SecretFacts, ...] = ()
+ drift: tuple[DriftFacts, ...] = ()
+ dead: tuple[DeadFacts, ...] = ()
+ stale_decisions: tuple[DecisionFacts, ...] = ()
+ proposed_decisions: int = 0
+ accepted_decisions: int = 0
+ #: Last commit per author identity key, for "their main author has gone quiet".
+ author_last_commit: Mapping[str, datetime] = field(default_factory=dict)
+ active_authors_90d: int = 0
+ coverage: CoverageState = CoverageState("unknown")
+ #: Store name -> why it could not be read.
+ unavailable: Mapping[str, str] = field(default_factory=dict)
diff --git a/packages/core/src/repowise/core/analysis/actions/model.py b/packages/core/src/repowise/core/analysis/actions/model.py
new file mode 100644
index 000000000..5aa0187bf
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/model.py
@@ -0,0 +1,222 @@
+"""What an action is, and the closed vocabularies it is written in.
+
+Mirrored by ``packages/types/src/actions.ts``; ``test_wire_vocabulary_parity``
+fails when the two disagree.
+"""
+
+from __future__ import annotations
+
+import hashlib
+from dataclasses import dataclass
+from typing import Any, Literal, get_args
+
+ActionRule = Literal[
+ "live_secret",
+ "fresh_regressions",
+ "fragile_file",
+ "fix_concentration",
+ "hot_path_perf",
+ "stale_decision",
+ "knowledge_loss",
+ "broken_doc_refs",
+ "dead_code_batch",
+ "coverage_missing",
+ "coverage_stale",
+ "decisions_unreviewed",
+]
+ACTION_RULES: tuple[str, ...] = get_args(ActionRule)
+
+Horizon = Literal["week", "quarter"]
+HORIZONS: tuple[str, ...] = get_args(Horizon)
+
+#: ``act_now`` is something wrong that got worse or is live; ``plan`` is work
+#: worth scheduling; ``improve_signal`` makes the other two more accurate.
+ActionTier = Literal["act_now", "plan", "improve_signal"]
+ACTION_TIERS: tuple[str, ...] = get_args(ActionTier)
+
+#: Where a fact came from. ``unknown`` is a fact too: "coverage unknown" is
+#: printed, never read as zero.
+FactBasis = Literal["measured", "inferred", "unknown"]
+FACT_BASES: tuple[str, ...] = get_args(FactBasis)
+
+ActionSurface = Literal[
+ "file",
+ "findings",
+ "performance",
+ "security",
+ "doc_drift",
+ "dead_code",
+ "decisions",
+ "commits",
+ "coverage",
+]
+ACTION_SURFACES: tuple[str, ...] = get_args(ActionSurface)
+
+TargetKind = Literal["file", "symbol", "folder", "document", "decision", "repo"]
+TARGET_KINDS: tuple[str, ...] = get_args(TargetKind)
+
+Effort = Literal["S", "M", "L"]
+
+RuleStatus = Literal["evaluated", "not_applicable", "unavailable"]
+RULE_STATUSES: tuple[str, ...] = get_args(RuleStatus)
+
+ActionStateValue = Literal["dismissed", "snoozed", "done"]
+ACTION_STATES: tuple[str, ...] = get_args(ActionStateValue)
+
+TIER_RANK: dict[str, int] = {"act_now": 0, "plan": 1, "improve_signal": 2}
+
+#: Tie-break between rules inside one tier: a claim that code is wrong or got
+#: worse outranks a claim that it is costly, which outranks tidiness.
+RULE_RANK: dict[str, int] = {rule: i for i, rule in enumerate(ACTION_RULES)}
+
+
+@dataclass(frozen=True, slots=True)
+class WhyFact:
+ label: str
+ value: str
+ basis: FactBasis = "measured"
+
+ def as_dict(self) -> dict[str, str]:
+ return {"label": self.label, "value": self.value, "basis": self.basis}
+
+
+@dataclass(frozen=True, slots=True)
+class ActionDetail:
+ """One piece of evidence behind an action: a finding, a site, a reference.
+
+ What an agent needs to start without re-deriving the list: where, what,
+ and why. ``ref`` is the commit or stored id that produced it.
+ """
+
+ path: str
+ line: int | None = None
+ symbol: str | None = None
+ marker: str | None = None
+ severity: str | None = None
+ reason: str = ""
+ ref: str | None = None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "path": self.path,
+ "line": self.line,
+ "symbol": self.symbol,
+ "marker": self.marker,
+ "severity": self.severity,
+ "reason": self.reason,
+ "ref": self.ref,
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class ActionCommand:
+ """A way to see more: the MCP call an agent makes, the CLI line a person runs."""
+
+ purpose: str
+ mcp: str | None = None
+ cli: str | None = None
+
+ def as_dict(self) -> dict[str, Any]:
+ return {"purpose": self.purpose, "mcp": self.mcp, "cli": self.cli}
+
+
+#: Evidence rows carried per action. The total says how many there were.
+DETAILS_CAP = 40
+
+
+@dataclass(frozen=True, slots=True)
+class Action:
+ rule: ActionRule
+ tier: ActionTier
+ horizons: tuple[Horizon, ...]
+ severity: str
+ #: Verb first. Paths and symbols are wrapped in backticks, which every
+ #: renderer sets in mono: "Raise test coverage on `a/b.py` from 62%".
+ title: str
+ impact: str
+ why: tuple[WhyFact, ...]
+ target_kind: TargetKind
+ target_path: str
+ surface: ActionSurface
+ effort: Effort
+ confidence: Literal["high", "medium"]
+ done_when: str
+ #: Rule-local ordering weight, comparable only within its rule.
+ weight: float = 0.0
+ target_symbol: str | None = None
+ #: What makes this action the same action next time, when the target alone
+ #: does not: two performance opportunities can share a symbol, and a
+ #: fragile file's lead function can change without the file's story
+ #: changing. Defaults to ``target_path:target_symbol``.
+ identity: str | None = None
+ evidence_ids: tuple[str, ...] = ()
+ evidence_total: int = 0
+ #: Files a folder-level action absorbed, so their own rows do not repeat.
+ includes: tuple[str, ...] = ()
+ command: str | None = None
+ #: The biomarker behind the action, when one names it; renderers label it
+ #: through their own glossary.
+ marker: str | None = None
+ #: Changes when the facts behind the action change materially. A dismissal
+ #: records it, and a dismissed action returns when it no longer matches.
+ fingerprint: str = ""
+ details: tuple[ActionDetail, ...] = ()
+ details_total: int = 0
+ commands: tuple[ActionCommand, ...] = ()
+
+ @property
+ def action_id(self) -> str:
+ identity = self.identity or f"{self.target_path}:{self.target_symbol or ''}"
+ key = f"{self.rule}:{identity}"
+ return "act_" + hashlib.sha1(key.encode("utf-8")).hexdigest()[:16]
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.action_id,
+ "rule": self.rule,
+ "tier": self.tier,
+ "horizons": list(self.horizons),
+ "severity": self.severity,
+ "title": self.title,
+ "impact": self.impact,
+ "why": [w.as_dict() for w in self.why],
+ "target": {
+ "kind": self.target_kind,
+ "path": self.target_path,
+ "symbol": self.target_symbol,
+ },
+ "surface": self.surface,
+ "effort": self.effort,
+ "confidence": self.confidence,
+ "done_when": self.done_when,
+ "command": self.command,
+ "marker": self.marker,
+ "evidence_ids": list(self.evidence_ids),
+ "evidence_total": self.evidence_total,
+ "includes": list(self.includes),
+ "fingerprint": self.fingerprint,
+ "details": [d.as_dict() for d in self.details[:DETAILS_CAP]],
+ "details_total": max(self.details_total, len(self.details)),
+ "commands": [c.as_dict() for c in self.commands],
+ }
+
+
+@dataclass(frozen=True, slots=True)
+class RuleOutcome:
+ rule: ActionRule
+ status: RuleStatus
+ reason: str = ""
+ actions: tuple[Action, ...] = ()
+
+ def as_dict(self) -> dict[str, Any]:
+ return {
+ "rule": self.rule,
+ "status": self.status,
+ "reason": self.reason,
+ "emitted": len(self.actions),
+ }
+
+
+def fingerprint(*parts: object) -> str:
+ raw = "|".join(str(p) for p in parts)
+ return hashlib.sha1(raw.encode("utf-8")).hexdigest()[:12]
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/__init__.py b/packages/core/src/repowise/core/analysis/actions/rules/__init__.py
new file mode 100644
index 000000000..dc7865e23
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/rules/__init__.py
@@ -0,0 +1 @@
+"""Action rules, one function per rule, grouped by what they read."""
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/_text.py b/packages/core/src/repowise/core/analysis/actions/rules/_text.py
new file mode 100644
index 000000000..b6d689057
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/rules/_text.py
@@ -0,0 +1,21 @@
+"""Small copy helpers shared by the rules."""
+
+from __future__ import annotations
+
+
+def code(text: str) -> str:
+ """Mark a path or symbol for a mono renderer."""
+ return f"`{text}`"
+
+
+def plural(n: int, noun: str) -> str:
+ return f"{n:,} {noun}" if n == 1 else f"{n:,} {noun}s"
+
+
+def humanize(token: str) -> str:
+ return token.replace("_", " ")
+
+
+def py_list(items: list[str]) -> str:
+ """A list literal for an MCP call line: ``["a.py", "b.py"]``."""
+ return "[" + ", ".join(f'"{i}"' for i in items) + "]"
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/code.py b/packages/core/src/repowise/core/analysis/actions/rules/code.py
new file mode 100644
index 000000000..e142ce9f4
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/rules/code.py
@@ -0,0 +1,535 @@
+"""Rules about the code itself: what got worse, what keeps breaking, what is slow."""
+
+from __future__ import annotations
+
+import posixpath
+from collections import defaultdict
+from datetime import datetime
+
+from ..context import RepoContext
+from ..facts import FileFacts, RepoFacts
+from ..model import Action, ActionCommand, ActionDetail, RuleOutcome, WhyFact, fingerprint
+from ._text import code, humanize, plural, py_list
+
+#: Files that tell the week's story as well as the quarter's: busy fragile
+#: files someone touched this week, strongest first.
+FRAGILE_WEEK_ROWS = 5
+
+#: Line coverage at or above this reads as "the tests exist"; below it, adding
+#: tests is the action.
+COVERED_PCT = 80.0
+
+#: ``fix_concentration`` needs enough fixes that a share means something, a
+#: share worth a sentence, and lift: the folder's share of fixes over its share
+#: of files. Lift is what separates `update_cmd/` (9% of fixes in 0.3% of the
+#: files) from `packages/cli/` (29% of fixes in 7% of the files): both are
+#: true, only one is an area someone can take on.
+CONCENTRATION_MIN_FIXES = 20
+CONCENTRATION_MIN_SHARE = 0.08
+CONCENTRATION_MIN_LIFT = 4.0
+CONCENTRATION_MIN_REPEAT_FILES = 3
+CONCENTRATION_MAX_ACTIONS = 2
+
+
+#: Up to this many files, each gets its own action; beyond it, one action
+#: carries the week and names the worst files. A heavy week of feature work can
+#: add findings to seventy files, and seventy rows is not a to-do list.
+REGRESSION_FILE_ROWS = 3
+
+
+def fresh_regressions(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ """Serious findings the last week of commits added and nobody has fixed yet.
+
+ The loader keeps only findings the commit demonstrably wrote (added lines,
+ a new file, or a changed symbol), still open, in production code, and not
+ history markers: "you made this worse" has to be true of the diff.
+ """
+ rule = "fresh_regressions"
+ if "commit_health" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["commit_health"])
+ if ctx.anchor is None:
+ return RuleOutcome(rule, "not_applicable", "No commit history in the index.")
+ by_file: dict[str, list] = defaultdict(list)
+ for f in facts.recent_findings:
+ by_file[f.file_path].append(f)
+ if not by_file:
+ return RuleOutcome(rule, "evaluated")
+
+ def weight(found: list) -> float:
+ return sum(f.severity == "critical" for f in found) * 10.0 + len(found)
+
+ ranked = sorted(by_file.items(), key=lambda kv: (-weight(kv[1]), kv[0]))
+ if len(ranked) > REGRESSION_FILE_ROWS:
+ return RuleOutcome(rule, "evaluated", "", (_regression_rollup(ranked),))
+ return RuleOutcome(
+ rule,
+ "evaluated",
+ "",
+ tuple(_regression_file(path, found, ctx, weight(found)) for path, found in ranked),
+ )
+
+
+def _regression_file(path: str, found: list, ctx: RepoContext, weight: float) -> Action:
+ symbols = sorted({f.symbol for f in found if f.symbol})
+ critical = sum(f.severity == "critical" for f in found)
+ commits = {f.sha: f for f in found}
+ lead = max(found, key=lambda f: (f.severity == "critical", f.line or 0))
+ if len(symbols) == 1:
+ title = f"Simplify {code(symbols[0])} in {code(path)} while the change is fresh"
+ elif symbols:
+ title = f"Tidy {plural(len(symbols), 'function')} you changed in {code(path)} this week"
+ else:
+ title = f"Tidy what this week's changes left in {code(path)}"
+ latest = max(commits.values(), key=lambda f: f.committed_at or ctx.anchor)
+ return Action(
+ rule="fresh_regressions",
+ tier="act_now",
+ horizons=("week",),
+ severity="critical" if critical else "high",
+ title=title,
+ impact=(
+ f"{plural(len(commits), 'commit')} in the last 7 days added or worsened "
+ f"{plural(len(found), 'critical or high finding')} here, still open. "
+ "Fixing now costs less than after the next change."
+ ),
+ why=(
+ WhyFact("serious findings", str(len(found))),
+ WhyFact("critical", str(critical)),
+ WhyFact("latest commit", latest.subject[:72] or latest.sha[:7]),
+ ),
+ target_kind="symbol" if len(symbols) == 1 else "file",
+ target_path=path,
+ target_symbol=symbols[0] if len(symbols) == 1 else None,
+ surface="findings",
+ effort="S" if len(symbols) <= 2 else "M",
+ confidence="high",
+ done_when="The findings close on the next update.",
+ marker=lead.biomarker,
+ weight=weight,
+ evidence_ids=tuple(sorted(commits)),
+ evidence_total=len(found),
+ fingerprint=fingerprint(len(found), critical),
+ details=_regression_details(found),
+ commands=_regression_commands([path], latest.sha),
+ )
+
+
+def _regression_details(found: list) -> tuple[ActionDetail, ...]:
+ ordered = sorted(found, key=lambda f: (f.severity != "critical", f.file_path, f.line or 0))
+ return tuple(
+ ActionDetail(
+ path=f.file_path,
+ line=f.line,
+ symbol=f.symbol,
+ marker=f.biomarker,
+ severity=f.severity,
+ reason=f.reason,
+ ref=f.sha,
+ )
+ for f in ordered
+ )
+
+
+def _regression_commands(paths: list[str], sha: str) -> tuple[ActionCommand, ...]:
+ first = paths[0]
+ return (
+ ActionCommand(
+ "Every open finding in these files, with its line and reason",
+ mcp=f'get_health(targets={py_list(paths[:10])}, include=["biomarkers"])',
+ cli=f"repowise health --file {first}",
+ ),
+ ActionCommand(
+ "The commit that last made the first file worse, and what it put at risk",
+ mcp=f'get_change_risk(revspec="{sha}")',
+ cli=f"git show {sha[:12]} -- {first}",
+ ),
+ ActionCommand(
+ "A file's structure and callers before editing it",
+ mcp=f'get_context(targets=["{first}"], include=["skeleton", "callers"])',
+ cli=f"repowise context {first}",
+ ),
+ )
+
+
+def _regression_rollup(ranked: list[tuple[str, list]]) -> Action:
+ found = [f for _, fs in ranked for f in fs]
+ critical = sum(f.severity == "critical" for f in found)
+ commits = {f.sha for f in found}
+ worst_path, worst = ranked[0]
+ worst_critical = sum(f.severity == "critical" for f in worst)
+ return Action(
+ rule="fresh_regressions",
+ tier="act_now",
+ horizons=("week",),
+ severity="critical" if critical else "high",
+ title=(
+ f"Clean up what this week's commits left: {plural(len(found), 'serious finding')} "
+ f"in {len(ranked):,} files"
+ ),
+ impact=(
+ f"{plural(len(commits), 'commit')} in the last 7 days added or worsened them, and they are "
+ f"still open. Start with {code(worst_path)}"
+ + (f", which has {worst_critical} critical." if worst_critical else ".")
+ ),
+ why=(
+ WhyFact("serious findings", str(len(found))),
+ WhyFact("critical", str(critical)),
+ WhyFact("files", str(len(ranked))),
+ ),
+ target_kind="repo",
+ target_path="",
+ surface="commits",
+ effort="L" if len(ranked) > 10 else "M",
+ confidence="high",
+ done_when="The findings close on the next update.",
+ weight=float(critical * 10 + len(found)),
+ evidence_ids=tuple(sorted(commits)),
+ evidence_total=len(found),
+ includes=tuple(path for path, _ in ranked[:10]),
+ fingerprint=fingerprint(len(found) // 10, critical // 5),
+ # Evidence in the order the files are ranked, so it starts where the
+ # impact line says to start; the commit to inspect is the latest one
+ # that touched that same file.
+ details=tuple(d for _, fs in ranked for d in _regression_details(fs)),
+ details_total=len(found),
+ commands=_regression_commands(
+ [path for path, _ in ranked],
+ max(worst, key=lambda f: f.committed_at or datetime.min).sha,
+ ),
+ )
+
+
+def _coverage_fact(f: FileFacts, facts: RepoFacts) -> WhyFact:
+ if f.line_coverage_pct is not None:
+ basis = "measured"
+ value = f"{f.line_coverage_pct:.0f}%"
+ if facts.coverage.status == "stale":
+ value += " (older report)"
+ return WhyFact("line coverage", value, basis)
+ if facts.coverage.status == "unknown":
+ return WhyFact("line coverage", "Unknown, no report", "unknown")
+ if facts.coverage.partial:
+ return WhyFact("line coverage", "Unknown, the report only partly mapped", "unknown")
+ return WhyFact("line coverage", "Unknown, not in the report", "unknown")
+
+
+def _is_fragile(f: FileFacts, ctx: RepoContext) -> bool:
+ return (
+ not f.is_test
+ and f.bug_magnet
+ and f.commits_90d >= ctx.busy_threshold
+ and f.fix_commits_90d >= ctx.fix_threshold
+ # A file with no branching is declarations: types, constants, a
+ # re-export barrel. Tests are not what it needs, and "add tests around
+ # types.ts" is the kind of advice that teaches a reader to skip the list.
+ and (f.max_ccn is None or f.max_ccn > 1)
+ )
+
+
+def fragile_file(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ """Busy files where bug fixes keep landing, with the next step their tests allow."""
+ rule = "fragile_file"
+ if "files" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["files"])
+ if ctx.fix_commits_90d == 0:
+ return RuleOutcome(rule, "not_applicable", "No bug-fix commits in the last 90 days.")
+ fragile = sorted(
+ (f for f in facts.files.values() if _is_fragile(f, ctx)),
+ key=lambda f: -(f.fix_commits_90d * f.commits_90d),
+ )
+ touched = [f for f in fragile if ctx.in_week(f.last_commit_at)]
+ week_rows = {f.path for f in touched[:FRAGILE_WEEK_ROWS]}
+ actions = []
+ for f in fragile:
+ cov = f.line_coverage_pct
+ if cov is None:
+ title = f"Add tests around {code(f.path)} before its next change"
+ done = "A coverage report includes it at 80% or more."
+ variant = "unknown"
+ elif cov < COVERED_PCT:
+ title = f"Raise test coverage on {code(f.path)} from {cov:.0f}%"
+ done = "Line coverage on this file reaches 80%."
+ variant = "raise"
+ elif f.lead is not None:
+ where = code(f.lead.function) + " in " if f.lead.function else ""
+ title = f"Simplify {where}{code(f.path)}: it is tested, and fixes keep landing"
+ done = "Its lead finding closes and bug-fix commits slow down."
+ variant = "simplify"
+ else:
+ continue
+ why = [
+ WhyFact("commits in 90 days", str(f.commits_90d)),
+ WhyFact("bug-fix commits", str(f.fix_commits_90d)),
+ _coverage_fact(f, facts),
+ ]
+ impact = (
+ f"Changed {f.commits_90d} times in 90 days, and {f.fix_commits_90d} "
+ "of those commits were bug fixes."
+ )
+ if f.dependents and f.dependents >= 5:
+ why.append(WhyFact("files that import it", str(f.dependents)))
+ impact += f" {f.dependents} files import it."
+ actions.append(
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("week", "quarter") if f.path in week_rows else ("quarter",),
+ severity="high" if f.fix_commits_90d >= 10 else "medium",
+ title=title,
+ impact=impact,
+ why=tuple(why),
+ target_kind="file",
+ target_path=f.path,
+ target_symbol=f.lead.function if variant == "simplify" and f.lead else None,
+ identity=f.path,
+ surface="file",
+ effort="M" if (f.nloc or 0) < 600 else "L",
+ confidence="high" if variant != "unknown" else "medium",
+ done_when=done,
+ marker=f.lead.biomarker if f.lead else None,
+ weight=float(f.fix_commits_90d * f.commits_90d),
+ fingerprint=fingerprint(variant, f.fix_commits_90d // 5),
+ details=(
+ (
+ ActionDetail(
+ path=f.path,
+ line=f.lead.line,
+ symbol=f.lead.function,
+ marker=f.lead.biomarker,
+ severity=f.lead.severity,
+ reason=f.lead.reason,
+ ),
+ )
+ if f.lead
+ else ()
+ ),
+ commands=(
+ ActionCommand(
+ "Its bug-fix history, co-change partners and test gaps",
+ mcp=f'get_risk(targets=["{f.path}"])',
+ cli=f"repowise risk -t {f.path}",
+ ),
+ ActionCommand(
+ "Every open finding in the file",
+ mcp=f'get_health(targets=["{f.path}"], include=["biomarkers"])',
+ cli=f"repowise health --file {f.path}",
+ ),
+ ),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+def fix_concentration(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ """One folder that takes a disproportionate share of the bug fixes.
+
+ Told as an area of work rather than a list of files, because that is how a
+ lead plans it. The deepest folder that still clears the share wins, so the
+ answer is `update_cmd/`, not `packages/`.
+ """
+ rule = "fix_concentration"
+ if "files" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["files"])
+ total = ctx.fix_commits_90d
+ if total < CONCENTRATION_MIN_FIXES:
+ return RuleOutcome(
+ rule,
+ "not_applicable",
+ f"{plural(total, 'bug-fix commit')} in 90 days; a share needs "
+ f"at least {CONCENTRATION_MIN_FIXES}.",
+ )
+ production = {p: f for p, f in facts.files.items() if not f.is_test}
+ files_per_folder: dict[str, int] = defaultdict(int)
+ for path in production:
+ for folder in _ancestors(path):
+ files_per_folder[folder] += 1
+ shas_per_folder: dict[str, set[str]] = defaultdict(set)
+ fixed_files: dict[str, list[str]] = defaultdict(list)
+ for path, shas in facts.fix_shas_by_file.items():
+ f = production.get(path)
+ if f is None:
+ continue
+ for folder in _ancestors(path):
+ shas_per_folder[folder] |= shas
+ if f.fix_commits_90d >= 3:
+ fixed_files[folder].append(path)
+ n_prod = len(production)
+
+ def lift(folder: str) -> float:
+ return (len(shas_per_folder[folder]) / total) / (files_per_folder[folder] / n_prod)
+
+ candidates = [
+ folder
+ for folder, shas in shas_per_folder.items()
+ if len(shas) / total >= CONCENTRATION_MIN_SHARE
+ and len(fixed_files[folder]) >= CONCENTRATION_MIN_REPEAT_FILES
+ and lift(folder) >= CONCENTRATION_MIN_LIFT
+ ]
+ chosen: list[str] = []
+ for folder in sorted(candidates, key=lambda d: -lift(d)):
+ if any(folder.startswith(c + "/") or c.startswith(folder + "/") for c in chosen):
+ continue
+ chosen.append(folder)
+ actions = []
+ for folder in chosen[:CONCENTRATION_MAX_ACTIONS]:
+ n = len(shas_per_folder[folder])
+ share = round(100 * n / total)
+ members = sorted(
+ fixed_files[folder], key=lambda p: -production[p].fix_commits_90d
+ )
+ includes = tuple(p for p in members if _is_fragile(production[p], ctx))
+ actions.append(
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="high",
+ title=(
+ f"Stabilise {code(folder + '/')}: {share}% of the bug fixes land in "
+ f"its {plural(files_per_folder[folder], 'file')}"
+ ),
+ impact=(
+ f"{n} of the {total} bug-fix commits in the last 90 days touched "
+ f"this folder, which holds {files_per_folder[folder] / n_prod:.1%} "
+ "of the production files."
+ ),
+ why=(
+ WhyFact("share of bug-fix commits", f"{share}%"),
+ WhyFact("files with repeated fixes", str(len(members))),
+ WhyFact("most fixed", posixpath.basename(members[0])),
+ ),
+ target_kind="folder",
+ target_path=folder,
+ surface="findings",
+ effort="L",
+ confidence="medium",
+ done_when="Its share of bug-fix commits falls over the next 90 days.",
+ weight=float(n),
+ evidence_total=len(members),
+ includes=includes,
+ fingerprint=fingerprint(share // 5),
+ details=tuple(
+ ActionDetail(
+ path=p,
+ reason=(
+ f"{production[p].fix_commits_90d} bug-fix commits, "
+ f"{production[p].commits_90d} commits in 90 days"
+ ),
+ )
+ for p in members
+ ),
+ commands=(
+ ActionCommand(
+ "Bug-fix history and co-change partners for the most fixed files",
+ mcp=f"get_risk(targets={py_list(members[:5])})",
+ cli="repowise risk " + " ".join(f"-t {p}" for p in members[:5]),
+ ),
+ ActionCommand(
+ "Why the folder is shaped this way",
+ mcp=f'get_why(targets=["{folder}/"])',
+ cli=f"repowise why {folder}/",
+ ),
+ ),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+def _ancestors(path: str) -> list[str]:
+ parts = path.split("/")[:-1]
+ return ["/".join(parts[: i + 1]) for i in range(len(parts))]
+
+
+_BOUNDARY_NOUN = {
+ "db": "database",
+ "filesystem": "file system",
+ "network": "network",
+ "subprocess": "subprocess",
+}
+
+
+def hot_path_perf(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ """Repeated I/O an entry point can reach, whose cost grows with the data.
+
+ Strict on purpose: on the repowise index 4 of 491 production opportunities
+ clear it. The rest stay on the Performance tab as an inventory.
+ """
+ rule = "hot_path_perf"
+ if "performance" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["performance"])
+ actions = []
+ for p in facts.perf:
+ if p.actionability not in ("plan_ready", "advisory"):
+ continue
+ if p.exposure != "entry_reachable":
+ continue
+ if p.loop_magnitude != "grows_with_data" and p.call_sites < 3:
+ continue
+ where = code(p.symbol.rsplit("::", 1)[-1] if p.symbol else p.file_path)
+ noun = _BOUNDARY_NOUN.get(p.boundary or "")
+ if noun and p.call_sites > 1:
+ title = f"Batch the {noun} calls loops make through {where}"
+ elif noun:
+ title = f"Move the {noun} call in {where} out of its loop"
+ else:
+ title = f"Fix the {humanize(p.biomarker)} in {where}"
+ actions.append(
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="medium",
+ title=title,
+ impact=(
+ f"{plural(p.call_sites, 'loop')} across {plural(p.files, 'file')} "
+ f"{'reaches' if p.call_sites == 1 else 'reach'} it from code an entry "
+ "point calls, once per item."
+ ),
+ why=(
+ WhyFact("file", posixpath.basename(p.file_path)),
+ WhyFact("call sites", str(p.call_sites)),
+ WhyFact("reachable from an entry point", "Yes", "inferred"),
+ WhyFact(
+ "cost",
+ "Grows with the data"
+ if p.loop_magnitude == "grows_with_data"
+ else "Repeated per call site",
+ "inferred",
+ ),
+ ),
+ target_kind="symbol" if p.symbol else "file",
+ target_path=p.file_path,
+ target_symbol=p.symbol,
+ identity=p.opportunity_id,
+ surface="performance",
+ effort=_effort(p.effort),
+ confidence="high" if p.actionability == "plan_ready" else "medium",
+ done_when="The opportunity closes on the next update.",
+ marker=p.biomarker,
+ weight=float(p.call_sites),
+ evidence_ids=(p.opportunity_id,),
+ evidence_total=p.call_sites,
+ commands=(
+ ActionCommand(
+ "Every call site, the fix strategy and the tests to run",
+ mcp=f'get_health(opportunity_id="{p.opportunity_id}")',
+ cli=f"repowise health --file {p.file_path}",
+ ),
+ ActionCommand(
+ "The function's body and its callers",
+ mcp=f'get_symbol("{p.symbol or p.file_path}", depth=1)',
+ cli=f"repowise symbol {p.symbol or p.file_path}",
+ ),
+ ),
+ fingerprint=fingerprint(p.call_sites, p.actionability),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+def _effort(bucket: str | None) -> str:
+ if bucket == "S":
+ return "S"
+ if bucket in ("L", "XL"):
+ return "L"
+ return "M"
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
new file mode 100644
index 000000000..daf5f0d78
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/rules/hygiene.py
@@ -0,0 +1,384 @@
+"""Rules about what surrounds the code: credentials, documents, decisions, people."""
+
+from __future__ import annotations
+
+import re
+from collections import defaultdict
+from datetime import timedelta
+
+from repowise.core.support_paths import DOC_EXTENSIONS
+
+from ..context import RepoContext
+from ..facts import RepoFacts
+from ..model import Action, ActionCommand, ActionDetail, RuleOutcome, WhyFact, fingerprint
+from ._text import code, plural
+
+# ---------------------------------------------------------------------------
+# Secrets
+# ---------------------------------------------------------------------------
+
+#: Only credential kinds. Pattern kinds (``os_system``, ``pickle_loads``, ...)
+#: are code smells with a high false-positive rate on this scanner today and
+#: stay on the Security tab until its precision work lands.
+SECRET_KINDS = {
+ "hardcoded_secret": "hard-coded secret",
+ "hardcoded_password": "hard-coded password",
+}
+PUBLIC_ENV_KIND = "public_env_secret"
+
+_COMMENT_PREFIXES = ("#", "//", "*", "/*", ">>>", "--", '"', "'")
+
+
+#: Values nobody would ship: the elided or templated examples in docstrings
+#: and READMEs (`api_key="sk-..."`, `"your-key-here"`). A masked real secret
+#: reads `sk-a****`, which none of these match.
+_PLACEHOLDER_MARKERS = ("...", "…", "<", "your", "xxx", "example", "placeholder", "dummy", "fake", "changeme")
+_QUOTED = re.compile(r"""["']([^"']*)["']""")
+
+
+def _looks_like_code(path: str, snippet: str) -> bool:
+ lowered = path.lower()
+ if lowered.endswith(tuple(DOC_EXTENSIONS)) or lowered.startswith("docs/") or "/docs/" in lowered:
+ return False
+ # Comments, docstrings and quoted examples: the scanner matches text, and a
+ # sentence about passwords is not a password.
+ if snippet.lstrip().startswith(_COMMENT_PREFIXES):
+ return False
+ values = _QUOTED.findall(snippet)
+ if any(marker in v.lower() for v in values for marker in _PLACEHOLDER_MARKERS):
+ return False
+ # A credential is long and not a plain word: `api_key="ollama"` is the
+ # dummy value a local server's client requires, not a secret.
+ return not values or any(_credential_shaped(v) for v in values)
+
+
+def _credential_shaped(value: str) -> bool:
+ return len(value) >= 8 and not value.isalpha()
+
+
+def live_secret(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "live_secret"
+ if "security" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["security"])
+ by_file: dict[str, list] = defaultdict(list)
+ for s in facts.secrets:
+ if (s.kind in SECRET_KINDS or s.kind == PUBLIC_ENV_KIND) and _looks_like_code(
+ s.file_path, s.snippet
+ ):
+ by_file[s.file_path].append(s)
+ actions = []
+ for path, found in by_file.items():
+ public = all(s.kind == PUBLIC_ENV_KIND for s in found)
+ lines = sorted({s.line for s in found if s.line})
+ where = (
+ f"line {lines[0]}"
+ if len(lines) == 1
+ else plural(len(lines), "line")
+ if lines
+ else "Unknown line"
+ )
+ if public:
+ title = f"Keep the secret out of a public environment variable in {code(path)}"
+ impact = (
+ "A variable a web build exposes to the browser is read as a secret "
+ "here; anything it holds ships to every visitor."
+ )
+ done = "The secret is read only from a server-side variable."
+ tier, severity = "plan", "high"
+ else:
+ kind = SECRET_KINDS[next(s.kind for s in found if s.kind in SECRET_KINDS)]
+ title = f"Rotate the {kind} in {code(path)}"
+ impact = "A credential sits in the working tree; anyone who can read the repository can use it."
+ done = "Rotate the credential with its provider, then remove it from the file."
+ tier, severity = "act_now", "critical"
+ actions.append(
+ Action(
+ rule=rule,
+ tier=tier,
+ horizons=("week", "quarter"),
+ severity=severity,
+ title=title,
+ impact=impact,
+ why=(WhyFact("where", where), WhyFact("in", "Working tree")),
+ target_kind="file",
+ target_path=path,
+ surface="security",
+ effort="S",
+ # Until the scanner's precision work lands, a secret match is
+ # worth a look rather than a certainty.
+ confidence="medium",
+ done_when=done,
+ evidence_total=len(found),
+ fingerprint=fingerprint(len(found)),
+ details=tuple(
+ ActionDetail(path=s.file_path, line=s.line, marker=s.kind, reason=s.snippet)
+ for s in found
+ ),
+ commands=(
+ ActionCommand(
+ "Where the value is read and who calls it",
+ mcp=f'get_context(targets=["{path}"], include=["callers"])',
+ cli=f"repowise context {path}",
+ ),
+ ),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+# ---------------------------------------------------------------------------
+# Documentation
+# ---------------------------------------------------------------------------
+
+DRIFT_MIN_CONFIDENCE = 0.8
+
+
+def _trusted_drift(d) -> bool:
+ if d.confidence < DRIFT_MIN_CONFIDENCE:
+ return False
+ if d.kind == "path":
+ # A document can name paths from another repository or an example that
+ # never existed. Trust the claim when the path was part of this one.
+ return d.target_known
+ if d.kind == "anchor":
+ # `/#install` is a site-root link on a web page, not an anchor in this
+ # file tree.
+ return not d.raw.startswith(("/", "http:", "https:"))
+ return False
+
+
+def broken_doc_refs(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "broken_doc_refs"
+ if "doc_drift" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["doc_drift"])
+ by_doc: dict[str, list] = defaultdict(list)
+ for d in facts.drift:
+ if _trusted_drift(d):
+ by_doc[d.document].append(d)
+ actions = []
+ for doc, found in by_doc.items():
+ targets = sorted({d.target for d in found})
+ actions.append(
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="low",
+ title=f"Fix {plural(len(targets), 'broken reference')} in {code(doc)}",
+ impact=(
+ "The document points readers and agents at "
+ f"{'a path' if len(targets) == 1 else 'paths'} this repository "
+ "no longer has."
+ ),
+ why=(
+ WhyFact("broken references", str(len(targets))),
+ WhyFact("first", targets[0]),
+ ),
+ target_kind="document",
+ target_path=doc,
+ surface="doc_drift",
+ effort="S",
+ confidence="high",
+ done_when="The references resolve on the next update.",
+ weight=float(len(targets)),
+ evidence_total=len(found),
+ fingerprint=fingerprint(len(targets)),
+ details=tuple(
+ ActionDetail(path=doc, line=d.line, marker=d.kind, reason=d.reason, ref=d.target)
+ for d in found
+ ),
+ commands=(
+ ActionCommand(
+ "Every broken reference, with a likely replacement where one is known",
+ mcp=f'get_context(targets=["{doc}"], include=["doc_drift"])',
+ cli="repowise doc-drift",
+ ),
+ ),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+# ---------------------------------------------------------------------------
+# Dead code
+# ---------------------------------------------------------------------------
+
+DEAD_MIN_SYMBOLS = 3
+DEAD_MIN_LINES = 30
+
+#: Code nothing imports on purpose: tutorials, samples, and scripts run by
+#: hand. FastAPI's `docs_src/` alone is 137 "unreachable" files.
+_STANDALONE_DIRS = ("docs/", "docs_src/", "examples/", "example/", "samples/", "scripts/")
+
+
+def _standalone(path: str) -> bool:
+ lowered = path.lower()
+ return lowered.startswith(_STANDALONE_DIRS) or any(
+ f"/{d}" in lowered for d in _STANDALONE_DIRS
+ )
+
+
+def dead_code_batch(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "dead_code_batch"
+ if "dead_code" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["dead_code"])
+ found = [d for d in facts.dead if not _standalone(d.file_path)]
+ lines = sum(d.lines for d in found)
+ if len(found) < DEAD_MIN_SYMBOLS and lines < DEAD_MIN_LINES:
+ return RuleOutcome(
+ rule,
+ "evaluated",
+ f"{plural(len(found), 'safe-to-delete symbol')}; below the batch floor.",
+ )
+ files = {d.file_path for d in found}
+ action = Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="low",
+ title=(
+ f"Delete {len(found):,} unused "
+ f"{'symbol or file' if len(found) == 1 else 'symbols and files'} ({lines:,} lines)"
+ ),
+ impact=(
+ f"Nothing in the graph reaches them, across {plural(len(files), 'file')}; "
+ "every reader and agent pays to skip them."
+ ),
+ why=(
+ WhyFact("symbols", str(len(found))),
+ WhyFact("lines", f"{lines:,}"),
+ WhyFact("safe to delete", "Yes", "inferred"),
+ ),
+ target_kind="repo",
+ target_path="",
+ surface="dead_code",
+ effort="S" if lines < 300 else "M",
+ confidence="high",
+ done_when="The dead-code list is empty after the next update.",
+ weight=float(lines),
+ evidence_ids=tuple(d.finding_id for d in found[:50]),
+ evidence_total=len(found),
+ details=tuple(
+ ActionDetail(
+ path=d.file_path,
+ symbol=d.symbol,
+ reason=f"{d.lines} lines, nothing reaches it",
+ ref=d.finding_id,
+ )
+ for d in sorted(found, key=lambda d: -d.lines)
+ ),
+ details_total=len(found),
+ commands=(
+ ActionCommand(
+ "The deletion-ready list with the evidence for each",
+ mcp="get_dead_code(safe_only=True)",
+ cli="repowise dead-code --safe-only",
+ ),
+ ),
+ fingerprint=fingerprint(len(found) // 5),
+ )
+ return RuleOutcome(rule, "evaluated", "", (action,))
+
+
+# ---------------------------------------------------------------------------
+# Decisions
+# ---------------------------------------------------------------------------
+
+
+def stale_decision(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "stale_decision"
+ if "decisions" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["decisions"])
+ if facts.accepted_decisions == 0:
+ return RuleOutcome(rule, "not_applicable", "No accepted decisions to drift.")
+ actions = [
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="medium",
+ title=f"Update the decision “{d.title}”: the code it governs has moved on",
+ impact="Agents and reviewers still follow it, so they are steered by a rule the code no longer keeps.",
+ why=(WhyFact("status", "Accepted, drifting"),),
+ target_kind="decision",
+ target_path=d.id,
+ surface="decisions",
+ effort="S",
+ confidence="medium",
+ done_when="The decision is re-accepted, amended or superseded.",
+ commands=(
+ ActionCommand(
+ "The decision, the code it governs, and how it drifted",
+ mcp=f'get_why(id="{d.id}")',
+ cli="repowise decision health",
+ ),
+ ),
+ weight=float(len(facts.stale_decisions) - i),
+ fingerprint=fingerprint(d.id),
+ )
+ for i, d in enumerate(facts.stale_decisions)
+ ]
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
+
+
+# ---------------------------------------------------------------------------
+# People
+# ---------------------------------------------------------------------------
+
+#: An owner quiet this long is treated as gone for planning purposes.
+OWNER_QUIET = timedelta(days=60)
+
+
+def knowledge_loss(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "knowledge_loss"
+ if "files" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["files"])
+ if not ctx.is_team:
+ return RuleOutcome(
+ rule,
+ "not_applicable",
+ f"{plural(ctx.active_authors_90d, 'active author')} in 90 days; "
+ "single ownership is the repository's shape, not a risk in it.",
+ )
+ if ctx.anchor is None:
+ return RuleOutcome(rule, "not_applicable", "No commit history in the index.")
+ actions = []
+ for f in facts.files.values():
+ if f.is_test or f.owner_key is None or (f.owner_pct or 0) < 0.8:
+ continue
+ if f.commits_90d < ctx.busy_threshold or (f.bus_factor or 1) > 1:
+ continue
+ last = facts.author_last_commit.get(f.owner_key)
+ if last is None:
+ continue
+ quiet = ctx.anchor.replace(tzinfo=None) - last.replace(tzinfo=None)
+ if quiet < OWNER_QUIET:
+ continue
+ actions.append(
+ Action(
+ rule=rule,
+ tier="plan",
+ horizons=("quarter",),
+ severity="medium",
+ title=f"Share what {f.owner_name or 'its main author'} knew about {code(f.path)}",
+ impact=(
+ f"{round((f.owner_pct or 0) * 100)}% of its history is theirs, they have not "
+ f"committed in {quiet.days} days, and it still changes "
+ f"{f.commits_90d} times a quarter."
+ ),
+ why=(
+ WhyFact("main author's share", f"{round((f.owner_pct or 0) * 100)}%"),
+ WhyFact("days since their last commit", str(quiet.days)),
+ WhyFact("commits in 90 days", str(f.commits_90d)),
+ ),
+ target_kind="file",
+ target_path=f.path,
+ surface="file",
+ effort="M",
+ confidence="medium",
+ done_when="A second person has reviewed or changed it.",
+ weight=float(f.commits_90d),
+ fingerprint=fingerprint(f.owner_key),
+ )
+ )
+ return RuleOutcome(rule, "evaluated", "", tuple(actions))
diff --git a/packages/core/src/repowise/core/analysis/actions/rules/signal.py b/packages/core/src/repowise/core/analysis/actions/rules/signal.py
new file mode 100644
index 000000000..909ba8b11
--- /dev/null
+++ b/packages/core/src/repowise/core/analysis/actions/rules/signal.py
@@ -0,0 +1,113 @@
+"""Rules that make the other rules more accurate.
+
+Kept in their own tier so they never outrank work: they tell the reader what
+Repowise cannot see yet, and what one command would change.
+"""
+
+from __future__ import annotations
+
+from datetime import timedelta
+
+from ..context import RepoContext
+from ..facts import RepoFacts
+from ..model import Action, RuleOutcome, WhyFact, fingerprint
+from ._text import plural
+
+#: Below this many production files, a coverage report is not worth asking for.
+COVERAGE_MIN_FILES = 20
+COVERAGE_STALE_AFTER = timedelta(days=14)
+DECISIONS_REVIEW_MIN = 5
+
+
+def coverage_missing(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "coverage_missing"
+ if "coverage" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["coverage"])
+ if facts.coverage.status != "unknown":
+ return RuleOutcome(rule, "evaluated", "A coverage report is ingested.")
+ if ctx.production_files < COVERAGE_MIN_FILES:
+ return RuleOutcome(rule, "not_applicable", "Too few files for coverage to change the list.")
+ action = Action(
+ rule=rule,
+ tier="improve_signal",
+ horizons=("week", "quarter"),
+ severity="low",
+ title="Add a test coverage report",
+ impact=(
+ "Without one, Repowise cannot tell tested code from untested code, so "
+ "every test-related action says “unknown”."
+ ),
+ why=(WhyFact("line coverage", "Unknown, no report", "unknown"),),
+ target_kind="repo",
+ target_path="",
+ surface="coverage",
+ effort="S",
+ confidence="high",
+ done_when="A coverage report is ingested.",
+ command="repowise coverage add <report>",
+ fingerprint=fingerprint("none"),
+ )
+ return RuleOutcome(rule, "evaluated", "", (action,))
+
+
+def coverage_stale(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "coverage_stale"
+ cov = facts.coverage
+ if cov.status != "stale" or cov.ingested_at is None or ctx.anchor is None:
+ return RuleOutcome(rule, "evaluated", "Coverage is current or absent.")
+ age = ctx.anchor.replace(tzinfo=None) - cov.ingested_at.replace(tzinfo=None)
+ if age < COVERAGE_STALE_AFTER:
+ return RuleOutcome(rule, "evaluated", "Coverage is recent enough.")
+ action = Action(
+ rule=rule,
+ tier="improve_signal",
+ horizons=("week", "quarter"),
+ severity="low",
+ title="Refresh the test coverage report",
+ impact=(
+ f"It was measured {age.days} days before the latest commit, so "
+ "coverage figures on changed files may be out of date."
+ ),
+ why=(
+ WhyFact("report age", f"{age.days} days"),
+ WhyFact("files measured", str(cov.files_measured)),
+ ),
+ target_kind="repo",
+ target_path="",
+ surface="coverage",
+ effort="S",
+ confidence="high",
+ done_when="A report from the current commit is ingested.",
+ command="repowise coverage add <report>",
+ fingerprint=fingerprint(age.days // 14),
+ )
+ return RuleOutcome(rule, "evaluated", "", (action,))
+
+
+def decisions_unreviewed(facts: RepoFacts, ctx: RepoContext) -> RuleOutcome:
+ rule = "decisions_unreviewed"
+ if "decisions" in facts.unavailable:
+ return RuleOutcome(rule, "unavailable", facts.unavailable["decisions"])
+ n = facts.proposed_decisions
+ if facts.accepted_decisions > 0 or n < DECISIONS_REVIEW_MIN:
+ return RuleOutcome(rule, "evaluated", "Decisions are reviewed, or too few are proposed.")
+ action = Action(
+ rule=rule,
+ tier="improve_signal",
+ horizons=("quarter",),
+ severity="low",
+ title=f"Review the {plural(n, 'proposed decision')}",
+ impact=(
+ "None is accepted yet, so nothing can drift from one and agents get no "
+ "enforced guidance from them."
+ ),
+ why=(WhyFact("proposed", str(n)), WhyFact("accepted", "0")),
+ target_kind="repo",
+ target_path="",
+ surface="decisions",
+ effort="M",
+ confidence="high",
+ done_when="The decisions that hold are accepted.",
+ fingerprint=fingerprint(n // 25),
+ )
+ return RuleOutcome(rule, "evaluated", "", (action,))
diff --git a/packages/core/src/repowise/core/analysis/health/models.py b/packages/core/src/repowise/core/analysis/health/models.py
index a60561775..4a25848b6 100644
--- a/packages/core/src/repowise/core/analysis/health/models.py
+++ b/packages/core/src/repowise/core/analysis/health/models.py
@@ -59,8 +59,9 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:
``coverage_gradient``.
"""
from .biomarkers.registry import continuous_biomarkers
+ from .governance import GOVERNANCE_BIOMARKERS
from .rows import field as row_field
- from .scoring import is_advisory
+ from .scoring import HISTORY_CATEGORY, biomarker_category, is_advisory
if not findings:
return None
@@ -72,6 +73,19 @@ def primary_finding(findings: Sequence[Any]) -> Any | None:
]
if not candidates:
return None
+ # A history marker is measured from git, so it names a file's context, not
+ # something an edit changes. When the file also carries a code-shape
+ # finding, that one leads: the Findings list put `change_entropy` at the
+ # head of four of its top five rows and asked an agent to fix it.
+ # Governance markers share the category but are work: writing or updating
+ # a decision clears them, so they stay eligible to lead.
+ shaped = [
+ item
+ for item in candidates
+ if biomarker_category(row_field(item, "biomarker_type")) != HISTORY_CATEGORY
+ or row_field(item, "biomarker_type") in GOVERNANCE_BIOMARKERS
+ ]
+ candidates = shaped or candidates
continuous = continuous_biomarkers()
discrete = [
item for item in candidates if row_field(item, "biomarker_type") not in continuous
diff --git a/packages/core/src/repowise/core/persistence/crud/analysis/actions.py b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
new file mode 100644
index 000000000..45be747d1
--- /dev/null
+++ b/packages/core/src/repowise/core/persistence/crud/analysis/actions.py
@@ -0,0 +1,612 @@
+"""Read the stores into :class:`RepoFacts`, and keep the per-person action state.
+
+Every store is read in its own savepoint and may fail on its own: an index
+built before a detector shipped, or an older schema, costs that store's rules
+(reported as unavailable, with the reason) rather than the whole list.
+"""
+
+from __future__ import annotations
+
+import json
+import logging
+from collections import defaultdict
+from collections.abc import Awaitable, Callable
+from dataclasses import replace
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+from sqlalchemy import func, select
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.analysis.actions import ActionStateRecord, RepoFacts, compose_actions
+from repowise.core.analysis.actions.facts import (
+ CoverageState,
+ DeadFacts,
+ DecisionFacts,
+ DriftFacts,
+ FileFacts,
+ LeadFinding,
+ PerfFacts,
+ RecentFinding,
+ SecretFacts,
+)
+from repowise.core.analysis.actions.rules.hygiene import PUBLIC_ENV_KIND, SECRET_KINDS
+from repowise.core.analysis.health.models import primary_finding, split_by_origin
+from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
+from repowise.core.author_identity import author_identity_key
+
+from ...models import (
+ ActionState,
+ CoverageFile,
+ CoverageIngest,
+ DeadCodeFinding,
+ DocDriftFinding,
+ FixEvent,
+ GitCommit,
+ GitCommitFile,
+ GitCommitHealthFinding,
+ GitMetadata,
+ GraphMetric,
+ HealthFileMetric,
+ HealthFinding,
+ PerformanceOpportunity,
+ SecurityFinding,
+)
+
+logger = logging.getLogger(__name__)
+
+QUARTER = timedelta(days=90)
+WEEK = timedelta(days=7)
+
+#: Attribution bases that tie a finding to lines the commit wrote. A
+#: ``file_change`` basis only says the commit touched the file, which is not
+#: enough to tell someone they made it worse.
+AUTHORED_BASES = ("added_lines", "new_file", "changed_symbol")
+
+#: Files whose lead finding is looked up: busy bug magnets only, so the lookup
+#: stays a keyed read whatever the repository's size.
+LEAD_LOOKUP_MIN_COMMITS = 5
+
+
+async def _anchor(session: AsyncSession, repo_id: str) -> tuple[datetime | None, str | None]:
+ row = (
+ await session.execute(
+ select(GitCommit.committed_at, GitCommit.sha)
+ .where(GitCommit.repository_id == repo_id, GitCommit.committed_at.is_not(None))
+ .order_by(GitCommit.committed_at.desc())
+ .limit(1)
+ )
+ ).first()
+ return (row.committed_at, row.sha) if row else (None, None)
+
+
+async def _files(session: AsyncSession, repo_id: str, since: datetime | None) -> dict[str, Any]:
+ rows = (
+ await session.execute(
+ select(
+ GitMetadata.file_path,
+ GitMetadata.commit_count_90d,
+ GitMetadata.last_commit_at,
+ GitMetadata.bug_magnet,
+ GitMetadata.bus_factor,
+ GitMetadata.primary_owner_name,
+ GitMetadata.primary_owner_email,
+ GitMetadata.primary_owner_commit_pct,
+ HealthFileMetric.is_test,
+ HealthFileMetric.score,
+ HealthFileMetric.max_ccn,
+ HealthFileMetric.nloc,
+ HealthFileMetric.line_coverage_pct,
+ )
+ .outerjoin(
+ HealthFileMetric,
+ (HealthFileMetric.repository_id == GitMetadata.repository_id)
+ & (HealthFileMetric.file_path == GitMetadata.file_path),
+ )
+ .where(GitMetadata.repository_id == repo_id)
+ )
+ ).all()
+ dependents = dict(
+ (
+ await session.execute(
+ select(GraphMetric.node_id, GraphMetric.in_degree).where(
+ GraphMetric.repository_id == repo_id
+ )
+ )
+ ).all()
+ )
+ fix_shas: dict[str, set[str]] = defaultdict(set)
+ all_fix: set[str] = set()
+ if since is not None:
+ for path, sha in (
+ await session.execute(
+ select(FixEvent.file_path, FixEvent.fix_sha).where(
+ FixEvent.repository_id == repo_id,
+ FixEvent.committed_at >= since,
+ FixEvent.shape_kind == "code_fix",
+ FixEvent.attribution != "none",
+ )
+ )
+ ).all():
+ fix_shas[path].add(sha)
+ all_fix.add(sha)
+
+ files: dict[str, FileFacts] = {}
+ for r in rows:
+ files[r.file_path] = FileFacts(
+ path=r.file_path,
+ is_test=bool(r.is_test),
+ score=r.score,
+ max_ccn=r.max_ccn,
+ nloc=r.nloc,
+ line_coverage_pct=r.line_coverage_pct,
+ commits_90d=r.commit_count_90d or 0,
+ last_commit_at=r.last_commit_at,
+ bug_magnet=bool(r.bug_magnet),
+ fix_commits_90d=len(fix_shas.get(r.file_path, ())),
+ bus_factor=r.bus_factor,
+ owner_key=(
+ author_identity_key(r.primary_owner_name, r.primary_owner_email)
+ if (r.primary_owner_name or r.primary_owner_email)
+ else None
+ ),
+ owner_name=r.primary_owner_name,
+ owner_pct=r.primary_owner_commit_pct,
+ dependents=dependents.get(r.file_path),
+ )
+
+ # Lead finding for the busy bug magnets: the code-shape finding an edit can
+ # fix. History markers are context, never the thing to do.
+ lead_paths = [
+ p
+ for p, f in files.items()
+ if f.bug_magnet
+ and not f.is_test
+ and f.commits_90d >= LEAD_LOOKUP_MIN_COMMITS
+ and f.fix_commits_90d >= 3
+ ]
+ if lead_paths:
+ findings = (
+ await session.execute(
+ select(
+ HealthFinding.file_path,
+ HealthFinding.biomarker_type,
+ HealthFinding.severity,
+ HealthFinding.function_name,
+ HealthFinding.line_start,
+ HealthFinding.reason,
+ HealthFinding.health_impact,
+ ).where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.status == "open",
+ HealthFinding.file_path.in_(lead_paths),
+ )
+ )
+ ).all()
+ by_path: dict[str, list] = defaultdict(list)
+ for f in findings:
+ by_path[f.file_path].append(f)
+ for path, found in by_path.items():
+ shape, _history = split_by_origin(found)
+ lead = primary_finding(shape)
+ if lead is not None:
+ files[path] = replace(
+ files[path],
+ lead=LeadFinding(
+ biomarker=lead.biomarker_type,
+ severity=lead.severity,
+ function=lead.function_name,
+ line=lead.line_start,
+ reason=lead.reason or "",
+ ),
+ )
+ return {
+ "files": files,
+ "fix_shas_by_file": {p: frozenset(s) for p, s in fix_shas.items()},
+ "fix_commits_90d": len(all_fix),
+ }
+
+
+async def _authors(session: AsyncSession, repo_id: str, since: datetime | None) -> dict[str, Any]:
+ last: dict[str, datetime] = {}
+ active: set[str] = set()
+ for name, email, latest in (
+ await session.execute(
+ select(
+ GitCommit.author_name,
+ GitCommit.author_email,
+ func.max(GitCommit.committed_at),
+ )
+ .where(GitCommit.repository_id == repo_id)
+ .group_by(GitCommit.author_name, GitCommit.author_email)
+ )
+ ).all():
+ if latest is None:
+ continue
+ key = author_identity_key(name, email)
+ if key not in last or latest > last[key]:
+ last[key] = latest
+ if since is not None and latest >= since:
+ active.add(key)
+ return {"author_last_commit": last, "active_authors_90d": len(active)}
+
+
+async def _recent(
+ session: AsyncSession, repo_id: str, since: datetime | None, files: dict[str, FileFacts]
+) -> dict[str, Any]:
+ if since is None:
+ return {}
+ rows = (
+ await session.execute(
+ select(GitCommitHealthFinding, GitCommit.subject, GitCommit.committed_at)
+ .join(
+ GitCommit,
+ (GitCommit.repository_id == GitCommitHealthFinding.repository_id)
+ & (GitCommit.sha == GitCommitHealthFinding.sha),
+ )
+ .where(
+ GitCommitHealthFinding.repository_id == repo_id,
+ GitCommit.committed_at >= since,
+ GitCommitHealthFinding.change_kind.in_(("introduced", "worsened")),
+ GitCommitHealthFinding.severity.in_(("critical", "high")),
+ GitCommitHealthFinding.attribution_basis.in_(AUTHORED_BASES),
+ )
+ )
+ ).all()
+ candidates = [
+ (f, subject, at)
+ for f, subject, at in rows
+ if not (files.get(f.file_path) and files[f.file_path].is_test)
+ and biomarker_category(f.biomarker_type) != HISTORY_CATEGORY
+ ]
+ if not candidates:
+ return {"recent_findings": ()}
+ paths = {f.file_path for f, _, _ in candidates}
+ open_keys = {
+ (p, b, fn)
+ for p, b, fn in (
+ await session.execute(
+ select(
+ HealthFinding.file_path,
+ HealthFinding.biomarker_type,
+ HealthFinding.function_name,
+ ).where(
+ HealthFinding.repository_id == repo_id,
+ HealthFinding.status == "open",
+ HealthFinding.file_path.in_(paths),
+ )
+ )
+ ).all()
+ }
+ recent = []
+ seen: set[tuple[str, str, str | None]] = set()
+ for f, subject, at in sorted(candidates, key=lambda r: r[2] or datetime.min, reverse=True):
+ key = (f.file_path, f.biomarker_type, f.symbol)
+ # Still open, and counted once however many commits touched it.
+ if key not in open_keys or key in seen:
+ continue
+ seen.add(key)
+ recent.append(
+ RecentFinding(
+ sha=f.sha,
+ subject=subject or "",
+ committed_at=at,
+ file_path=f.file_path,
+ symbol=f.symbol,
+ biomarker=f.biomarker_type,
+ severity=f.severity,
+ change_kind=f.change_kind,
+ line=f.line_start,
+ reason=f.reason or "",
+ )
+ )
+ return {"recent_findings": tuple(recent)}
+
+
+async def _perf(session: AsyncSession, repo_id: str) -> dict[str, Any]:
+ rows = (
+ (
+ await session.execute(
+ select(PerformanceOpportunity).where(
+ PerformanceOpportunity.repository_id == repo_id,
+ PerformanceOpportunity.status == "open",
+ PerformanceOpportunity.execution_context == "production",
+ PerformanceOpportunity.actionability_state.in_(("plan_ready", "advisory")),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ out = []
+ for r in rows:
+ try:
+ details = json.loads(r.details_json or "{}")
+ except ValueError:
+ details = {}
+ facets = details.get("facets") or {}
+ plan = details.get("plan") or {}
+ out.append(
+ PerfFacts(
+ opportunity_id=r.opportunity_id,
+ biomarker=r.biomarker_type,
+ boundary=r.boundary_kind,
+ file_path=r.file_path,
+ symbol=r.intervention_symbol,
+ call_sites=r.affected_call_sites_total or 0,
+ files=r.affected_files_total or 0,
+ actionability=r.actionability_state,
+ exposure=facets.get("exposure"),
+ loop_magnitude=facets.get("loop_magnitude"),
+ effort=plan.get("effort_bucket"),
+ )
+ )
+ return {"perf": tuple(out)}
+
+
+async def _secrets(session: AsyncSession, repo_id: str, files: dict[str, FileFacts]) -> dict:
+ rows = (
+ await session.execute(
+ select(
+ SecurityFinding.file_path,
+ SecurityFinding.kind,
+ SecurityFinding.line_number,
+ SecurityFinding.snippet,
+ ).where(
+ SecurityFinding.repository_id == repo_id,
+ SecurityFinding.commit_sha == "",
+ SecurityFinding.severity == "high",
+ SecurityFinding.kind.in_((*SECRET_KINDS, PUBLIC_ENV_KIND)),
+ )
+ )
+ ).all()
+ return {
+ "secrets": tuple(
+ SecretFacts(r.file_path, r.kind, r.line_number, r.snippet or "")
+ for r in rows
+ if not (files.get(r.file_path) and files[r.file_path].is_test)
+ and not _test_path(r.file_path)
+ )
+ }
+
+
+def _test_path(path: str) -> bool:
+ lowered = path.lower()
+ return any(
+ seg in lowered
+ for seg in ("/tests/", "/test/", "__tests__", "/fixtures/", ".test.", ".spec.", "_test.")
+ ) or lowered.startswith(("tests/", "test/"))
+
+
+async def _drift(session: AsyncSession, repo_id: str) -> dict[str, Any]:
+ rows = (
+ await session.execute(
+ select(
+ DocDriftFinding.file_path,
+ DocDriftFinding.kind,
+ DocDriftFinding.target,
+ DocDriftFinding.raw,
+ DocDriftFinding.line_number,
+ DocDriftFinding.reason,
+ DocDriftFinding.confidence,
+ ).where(DocDriftFinding.repository_id == repo_id)
+ )
+ ).all()
+ path_targets = {r.target for r in rows if r.kind == "path" and r.target}
+ known: set[str] = set()
+ if path_targets:
+ known = set(
+ (
+ await session.execute(
+ select(GitCommitFile.file_path)
+ .where(
+ GitCommitFile.repository_id == repo_id,
+ GitCommitFile.file_path.in_(path_targets),
+ )
+ .distinct()
+ )
+ )
+ .scalars()
+ .all()
+ )
+ known |= set(
+ (
+ await session.execute(
+ select(GitMetadata.original_path).where(
+ GitMetadata.repository_id == repo_id,
+ GitMetadata.original_path.in_(path_targets),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ return {
+ "drift": tuple(
+ DriftFacts(
+ document=r.file_path,
+ kind=r.kind,
+ target=r.target or "",
+ raw=r.raw or "",
+ line=r.line_number,
+ reason=r.reason or "",
+ confidence=float(r.confidence or 0.0),
+ target_known=(r.target in known),
+ )
+ for r in rows
+ )
+ }
+
+
+async def _dead(session: AsyncSession, repo_id: str, files: dict[str, FileFacts]) -> dict:
+ rows = (
+ await session.execute(
+ select(
+ DeadCodeFinding.id,
+ DeadCodeFinding.file_path,
+ DeadCodeFinding.symbol_name,
+ DeadCodeFinding.lines,
+ ).where(
+ DeadCodeFinding.repository_id == repo_id,
+ DeadCodeFinding.status == "open",
+ DeadCodeFinding.safe_to_delete.is_(True),
+ )
+ )
+ ).all()
+ return {
+ "dead": tuple(
+ DeadFacts(r.id, r.file_path, r.symbol_name, r.lines or 0)
+ for r in rows
+ if not (files.get(r.file_path) and files[r.file_path].is_test)
+ and not _test_path(r.file_path)
+ )
+ }
+
+
+async def _decisions(session: AsyncSession, repo_id: str) -> dict[str, Any]:
+ from ..decision_health import get_decision_health_summary
+
+ summary = await get_decision_health_summary(session, repo_id)
+ counts = summary.get("summary") or {}
+ return {
+ "stale_decisions": tuple(
+ DecisionFacts(d.id, d.title) for d in summary.get("stale_decisions") or []
+ ),
+ "proposed_decisions": int(counts.get("proposed") or 0),
+ "accepted_decisions": int(counts.get("active") or 0),
+ }
+
+
+async def _coverage(session: AsyncSession, repo_id: str, head_sha: str | None) -> dict:
+ count, latest_at, latest_sha = (
+ await session.execute(
+ select(
+ func.count(CoverageFile.id),
+ func.max(CoverageFile.ingested_at),
+ func.max(CoverageFile.ingested_commit_sha),
+ ).where(CoverageFile.repository_id == repo_id)
+ )
+ ).one()
+ if not count:
+ return {"coverage": CoverageState("unknown")}
+ # The ingest record is authoritative for when, at which commit, and whether
+ # the report's paths all mapped. Indexes that predate it carry the same
+ # commit on every row, because one ingest replaces them all.
+ partial = False
+ try:
+ async with session.begin_nested():
+ ingest = (
+ await session.execute(
+ select(
+ CoverageIngest.ingested_at,
+ CoverageIngest.ingested_commit_sha,
+ CoverageIngest.mapping_partial,
+ )
+ .where(CoverageIngest.repository_id == repo_id)
+ .order_by(CoverageIngest.ingested_at.desc())
+ .limit(1)
+ )
+ ).first()
+ if ingest is not None:
+ latest_at, latest_sha, partial = (
+ ingest.ingested_at,
+ ingest.ingested_commit_sha,
+ bool(ingest.mapping_partial),
+ )
+ except Exception: # an index from before ingests were recorded
+ pass
+ # Stale only when both commits are known and differ; a report without a
+ # commit cannot be called out of date.
+ status = "stale" if latest_sha and head_sha and latest_sha != head_sha else "measured"
+ return {"coverage": CoverageState(status, latest_at, int(count), partial)}
+
+
+_Reader = Callable[[], Awaitable[dict[str, Any]]]
+
+
+async def load_repo_facts(session: AsyncSession, repo_id: str) -> RepoFacts:
+ anchor, head_sha = await _anchor(session, repo_id)
+ since = (anchor - QUARTER) if anchor else None
+ week = (anchor - WEEK) if anchor else None
+ values: dict[str, Any] = {"anchor": anchor}
+ unavailable: dict[str, str] = {}
+
+ async def read(store: str, reader: _Reader) -> None:
+ try:
+ async with session.begin_nested():
+ values.update(await reader())
+ except Exception as exc: # one store must not cost the list
+ logger.warning("actions: %s unavailable: %s", store, exc)
+ unavailable[store] = "Not in this index yet; run `repowise update`."
+
+ await read("files", lambda: _files(session, repo_id, since))
+ files: dict[str, FileFacts] = values.get("files") or {}
+ await read("authors", lambda: _authors(session, repo_id, since))
+ await read("commit_health", lambda: _recent(session, repo_id, week, files))
+ await read("performance", lambda: _perf(session, repo_id))
+ await read("security", lambda: _secrets(session, repo_id, files))
+ await read("doc_drift", lambda: _drift(session, repo_id))
+ await read("dead_code", lambda: _dead(session, repo_id, files))
+ await read("decisions", lambda: _decisions(session, repo_id))
+ await read("coverage", lambda: _coverage(session, repo_id, head_sha))
+ values["unavailable"] = unavailable
+ return RepoFacts(**values)
+
+
+async def get_action_states(session: AsyncSession, repo_id: str) -> dict[str, ActionStateRecord]:
+ rows = (
+ (await session.execute(select(ActionState).where(ActionState.repository_id == repo_id)))
+ .scalars()
+ .all()
+ )
+ return {r.action_id: ActionStateRecord(r.state, r.fingerprint, r.until) for r in rows}
+
+
+async def set_action_state(
+ session: AsyncSession,
+ repo_id: str,
+ action_id: str,
+ *,
+ state: str | None,
+ fingerprint: str = "",
+ until: datetime | None = None,
+) -> None:
+ """Record, replace, or (``state=None``) clear a person's answer to one action."""
+ row = (
+ await session.execute(
+ select(ActionState).where(
+ ActionState.repository_id == repo_id, ActionState.action_id == action_id
+ )
+ )
+ ).scalar_one_or_none()
+ if state is None:
+ if row is not None:
+ await session.delete(row)
+ return
+ if row is None:
+ session.add(
+ ActionState(
+ repository_id=repo_id,
+ action_id=action_id,
+ state=state,
+ fingerprint=fingerprint,
+ until=until,
+ )
+ )
+ else:
+ row.state, row.fingerprint, row.until = state, fingerprint, until
+
+
+async def load_actions_view(
+ session: AsyncSession, repo_id: str, *, now: datetime | None = None
+) -> dict[str, Any]:
+ """The one entry point: facts, the person's answers, and the ranked view."""
+ facts = await load_repo_facts(session, repo_id)
+ try:
+ async with session.begin_nested():
+ states = await get_action_states(session, repo_id)
+ except Exception:
+ states = {}
+ view = compose_actions(facts, states, now=now or datetime.now(UTC))
+ view["unavailable"] = dict(facts.unavailable)
+ return view
diff --git a/packages/core/src/repowise/core/persistence/models.py b/packages/core/src/repowise/core/persistence/models.py
index 3542bf1a0..87dec9790 100644
--- a/packages/core/src/repowise/core/persistence/models.py
+++ b/packages/core/src/repowise/core/persistence/models.py
@@ -2270,6 +2270,35 @@ class CoverageIngest(Base):
)
+class ActionState(Base):
+ """A person's answer to one next action: dismissed, snoozed, or done.
+
+ Actions themselves are computed on read (``analysis.actions``), so this is
+ the only stored half. ``action_id`` is stable across re-index because it is
+ derived from the rule and its target. ``fingerprint`` is the one the action
+ carried when the person acted; a dismissal holds only while it still
+ matches, so an action whose facts changed materially comes back.
+ """
+
+ __tablename__ = "action_states"
+
+ id: Mapped[str] = mapped_column(String(32), primary_key=True, default=_new_uuid)
+ repository_id: Mapped[str] = mapped_column(
+ String(32), ForeignKey("repositories.id", ondelete="CASCADE"), nullable=False
+ )
+ action_id: Mapped[str] = mapped_column(String(32), nullable=False)
+ state: Mapped[str] = mapped_column(String(16), nullable=False)
+ fingerprint: Mapped[str] = mapped_column(String(32), nullable=False, default="")
+ until: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
+ updated_at: Mapped[datetime] = mapped_column(
+ DateTime(timezone=True), nullable=False, default=_now_utc, onupdate=_now_utc
+ )
+
+ __table_args__ = (
+ UniqueConstraint("repository_id", "action_id", name="uq_action_states"),
+ )
+
+
class TestCoverageEntry(Base):
"""One ``(test, source file)`` coverage fact - the test-to-code map.
diff --git a/packages/server/src/repowise/server/app.py b/packages/server/src/repowise/server/app.py
index 3f4b9ba7c..67a9c76d9 100644
--- a/packages/server/src/repowise/server/app.py
+++ b/packages/server/src/repowise/server/app.py
@@ -37,6 +37,7 @@ from repowise.core.providers.embedding.base import KeylessEmbedder
from repowise.core.providers.embedding.caching import CachingEmbedder
from repowise.server import __version__
from repowise.server.routers import (
+ actions,
blast_radius,
c4,
chat,
@@ -386,6 +387,7 @@ _ROUTERS = (
files,
external_systems,
feedback,
+ actions,
)
diff --git a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
index 7e9c6de81..da482367a 100644
--- a/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
+++ b/packages/server/src/repowise/server/mcp_server/_budget/contracts.py
@@ -268,6 +268,13 @@ _CONTRACTS: dict[str, ResponseBudgetContract] = {
# served 0 of 40 while 73% of the budget went unspent.
"outline.sections[]",
"outline",
+ # Built at three rows a horizon. The quarter trims first, since the
+ # week is the nearer ask, and the totals stay until the whole block
+ # goes.
+ "next_actions.quarter.actions[]",
+ "next_actions.week.actions[]",
+ "next_actions_reason",
+ "next_actions",
"tool_surface",
"repos[]",
"key_modules[]",
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py
new file mode 100644
index 000000000..a37549e67
--- /dev/null
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/actions.py
@@ -0,0 +1,54 @@
+"""The overview's ``next_actions`` block: the same stored actions the UI ranks."""
+
+from __future__ import annotations
+
+import logging
+from typing import Any
+
+from repowise.core.persistence.crud.analysis.actions import load_actions_view
+
+logger = logging.getLogger(__name__)
+
+#: Rows per horizon. The UI previews five; an agent orienting needs the head,
+#: and ``total`` says how much sits behind it.
+_PER_HORIZON = 3
+
+_FIELDS = ("id", "tier", "title", "impact", "done_when")
+
+
+def _compact(action: dict[str, Any]) -> dict[str, Any]:
+ row = {k: action.get(k) for k in _FIELDS}
+ row["target"] = {k: v for k, v in (action.get("target") or {}).items() if v is not None}
+ return row
+
+
+def compact_actions_view(view: dict[str, Any]) -> dict[str, Any]:
+ """The head of each horizon plus its totals, from a ``load_actions_view`` result."""
+ block: dict[str, Any] = {"anchor": view.get("anchor")}
+ for name, horizon in (view.get("horizons") or {}).items():
+ block[name] = {
+ "total": horizon.get("total", 0),
+ "by_tier": horizon.get("by_tier", {}),
+ "actions": [_compact(a) for a in horizon.get("actions", [])[:_PER_HORIZON]],
+ }
+ unavailable = sorted(view.get("unavailable") or {})
+ if unavailable:
+ block["unavailable"] = unavailable
+ return block
+
+
+async def _build_next_actions(session: Any, repository: Any) -> tuple[dict[str, Any], str | None]:
+ """``(block, None)``, or ``({}, reason)`` when the actions could not be read.
+
+ The loader already tolerates a store missing from an older index; this
+ guard is for anything else, so the overview never fails on its account.
+ The savepoint keeps a failed read from poisoning the session the rest of
+ the overview still uses.
+ """
+ try:
+ async with session.begin_nested():
+ view = await load_actions_view(session, repository.id)
+ return compact_actions_view(view), None
+ except Exception as exc:
+ logger.warning("get_overview: next actions unavailable: %s", exc)
+ return {}, f"Next actions could not be read from this index ({type(exc).__name__})."
diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
index 9e6f2eb5d..ef2da2587 100644
--- a/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
+++ b/packages/server/src/repowise/server/mcp_server/tool_overview/tool.py
@@ -20,6 +20,7 @@ from repowise.server.mcp_server._helpers import (
from repowise.server.mcp_server._meta import (
build_meta_with_full_scope as _build_meta_with_full_scope,
)
+from repowise.server.mcp_server.tool_overview.actions import _build_next_actions
from repowise.server.mcp_server.tool_overview.decisions import _build_key_decisions
from repowise.server.mcp_server.tool_overview.graph import (
_build_architecture,
@@ -56,8 +57,8 @@ async def get_overview(repo: str | None = None, include: list[str] | None = None
"""Architecture map for an unfamiliar repo — first call when you don't know your way around.
Returns the synthesised overview summary, key modules, entry points,
- architecture layers, code health, and repo-wide git health (hotspot count,
- churn trend, bus-factor distribution).
+ architecture layers, code health, repo-wide git health, and
+ ``next_actions`` (top work for the week and quarter).
Skip this on subsequent calls — once you have the map, jump straight to
``get_context`` / ``get_answer``.
@@ -120,6 +121,7 @@ async def _repo_overview(
all_git = await _load_git_rows(session, repository, exclude_spec)
architecture = await _build_architecture(session, repository)
code_health = await _build_code_health(session, repository)
+ next_actions, next_actions_reason = await _build_next_actions(session, repository)
requested = await _requested_blocks(session, repository, exclude_spec, all_git, want)
sections, outline = await _load_outline(session, repository, want, collector)
content_md, content_hint = _overview_content(overview_page, "content" in want)
@@ -128,6 +130,10 @@ async def _repo_overview(
"title": _resolve_title(overview_page, repository),
"content_md": content_md,
"code_health": code_health,
+ # The stored actions the web app's "Do next" ranks, so the agent and
+ # the UI agree on what comes first.
+ **({"next_actions": next_actions} if next_actions else {}),
+ **({"next_actions_reason": next_actions_reason} if next_actions_reason else {}),
# Names and paths only. get_context(path) carries the prose, and
# section indexes into include=["outline"].
"key_modules": [
diff --git a/packages/server/src/repowise/server/routers/actions.py b/packages/server/src/repowise/server/routers/actions.py
new file mode 100644
index 000000000..ff66944fd
--- /dev/null
+++ b/packages/server/src/repowise/server/routers/actions.py
@@ -0,0 +1,59 @@
+"""/api/repos/{repo_id}/actions: the short list of things worth doing next."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime, timedelta
+
+from fastapi import APIRouter, Depends, HTTPException, Path
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from repowise.core.persistence import crud
+from repowise.core.persistence.crud.analysis.actions import load_actions_view, set_action_state
+from repowise.server.deps import get_db_session, verify_api_key
+from repowise.server.schemas.actions import (
+ ActionsResponse,
+ ActionStateRequest,
+ ActionStateResponse,
+)
+
+router = APIRouter(tags=["actions"], dependencies=[Depends(verify_api_key)])
+
+
[email protected]("/api/repos/{repo_id}/actions", response_model=ActionsResponse)
+async def get_actions(
+ repo_id: str,
+ session: AsyncSession = Depends(get_db_session),
+) -> dict:
+ """Both horizons in one response, so switching between them costs nothing."""
+ await _require_repo(session, repo_id)
+ return await load_actions_view(session, repo_id)
+
+
+async def _require_repo(session: AsyncSession, repo_id: str) -> None:
+ if await crud.get_repository(session, repo_id) is None:
+ raise HTTPException(status_code=404, detail="Repository not found")
+
+
+ "/api/repos/{repo_id}/actions/{action_id}/state",
+ response_model=ActionStateResponse,
+)
+async def put_action_state(
+ repo_id: str,
+ body: ActionStateRequest,
+ action_id: str = Path(..., max_length=32),
+ session: AsyncSession = Depends(get_db_session),
+) -> ActionStateResponse:
+ await _require_repo(session, repo_id)
+ until = (
+ datetime.now(UTC) + timedelta(days=body.snooze_days) if body.state == "snoozed" else None
+ )
+ await set_action_state(
+ session,
+ repo_id,
+ action_id,
+ state=body.state,
+ fingerprint=body.fingerprint,
+ until=until,
+ )
+ return ActionStateResponse(action_id=action_id, state=body.state, until=until)
diff --git a/packages/server/src/repowise/server/routers/workspace.py b/packages/server/src/repowise/server/routers/workspace.py
index 4b695b67d..b45d8703c 100644
--- a/packages/server/src/repowise/server/routers/workspace.py
+++ b/packages/server/src/repowise/server/routers/workspace.py
@@ -43,6 +43,11 @@ from repowise.server.schemas import (
WorkspaceSystemGraphResponse,
WorkspaceTestImpactResponse,
)
+from repowise.server.schemas.actions import (
+ WorkspaceActionsResponse,
+ WorkspaceCrossRepoAction,
+ WorkspaceRepoActions,
+)
from repowise.server.services.module_health import read_repo_health_score
router = APIRouter(
@@ -652,6 +657,99 @@ async def get_test_impact(
return WorkspaceTestImpactResponse(**workspace_test_impact_to_dict(result))
+# ---------------------------------------------------------------------------
+# GET /api/workspace/actions
+# ---------------------------------------------------------------------------
+
+#: Per repository, per horizon: enough to say what leads, not a second copy of
+#: each repository's own list.
+WORKSPACE_ACTIONS_PER_REPO = 2
+
+
[email protected]("/actions", response_model=WorkspaceActionsResponse)
+async def get_workspace_actions(
+ request: Request,
+ ws_config=Depends(get_workspace_config),
+ enricher=Depends(get_cross_repo_enricher),
+) -> WorkspaceActionsResponse:
+ """What to do next across the workspace: each repository's lead actions,
+ plus the cross-repository ones only the workspace can see.
+
+ Each repository's list is the same fold its own Overview serves
+ (``load_actions_view``), trimmed to the work tiers, so the two pages never
+ disagree about what leads.
+ """
+ from repowise.core.persistence.crud.analysis.actions import load_actions_view
+ from repowise.core.persistence.database import get_session
+
+ _require_workspace(ws_config)
+ ws_root = getattr(request.app.state, "workspace_root", None)
+ ws_root_path = Path(ws_root) if ws_root else None
+
+ repos: list[WorkspaceRepoActions] = []
+ for r in ws_config.repos:
+ repo_id = None
+ if ws_root_path:
+ db_path = (ws_root_path / r.path).resolve() / ".repowise" / "wiki.db"
+ repo_id = _query_repo_stats(db_path).get("repo_id")
+ if not repo_id:
+ repos.append(
+ WorkspaceRepoActions(
+ alias=r.alias, repo_id=None, status="unavailable", reason="Not indexed yet."
+ )
+ )
+ continue
+ try:
+ async with get_session(resolve_session_factory(request.app.state, repo_id)) as session:
+ view = await load_actions_view(session, repo_id)
+ except Exception as exc: # one repository must not cost the page
+ _log.warning("workspace actions: %s unavailable: %s", r.alias, exc)
+ repos.append(
+ WorkspaceRepoActions(
+ alias=r.alias,
+ repo_id=repo_id,
+ status="unavailable",
+ reason="Could not read this repository's index.",
+ )
+ )
+ continue
+ horizons = {}
+ for key, h in view["horizons"].items():
+ work = [a for a in h["actions"] if a["tier"] != "improve_signal"]
+ horizons[key] = {
+ **h,
+ "actions": work[:WORKSPACE_ACTIONS_PER_REPO],
+ "total": (h["by_tier"].get("act_now", 0) + h["by_tier"].get("plan", 0)),
+ }
+ repos.append(
+ WorkspaceRepoActions(
+ alias=r.alias, repo_id=repo_id, status="available", horizons=horizons
+ )
+ )
+
+ cross_repo: list[WorkspaceCrossRepoAction] = []
+ report = enricher.get_breaking_changes() if enricher is not None else None
+ if report:
+ view = reads.breaking_changes_view(report, repo=None, severity="breaking")
+ count = int(view.get("breaking_count") or 0)
+ if count:
+ impacted = sorted(view.get("impacted_repos") or [])
+ cross_repo.append(
+ WorkspaceCrossRepoAction(
+ kind="breaking_contract",
+ title=f"Resolve {count} breaking contract change{'' if count == 1 else 's'}",
+ impact=(
+ "A provider changed a route, topic or table that another repository "
+ "consumes"
+ + (f"; {', '.join(impacted)} depend on it." if impacted else ".")
+ ),
+ count=count,
+ repos=impacted,
+ )
+ )
+ return WorkspaceActionsResponse(repos=repos, cross_repo=cross_repo)
+
+
# ---------------------------------------------------------------------------
# GET /api/workspace/breaking-changes
# ---------------------------------------------------------------------------
diff --git a/packages/server/src/repowise/server/schemas/actions.py b/packages/server/src/repowise/server/schemas/actions.py
new file mode 100644
index 000000000..a62c5d00f
--- /dev/null
+++ b/packages/server/src/repowise/server/schemas/actions.py
@@ -0,0 +1,129 @@
+"""Wire shapes for next actions. Mirrors ``packages/types/src/actions.ts``."""
+
+from __future__ import annotations
+
+from datetime import datetime
+from typing import Literal
+
+from pydantic import BaseModel, Field
+
+
+class ActionWhy(BaseModel):
+ label: str
+ value: str
+ basis: Literal["measured", "inferred", "unknown"]
+
+
+class ActionTarget(BaseModel):
+ kind: Literal["file", "symbol", "folder", "document", "decision", "repo"]
+ path: str
+ symbol: str | None = None
+
+
+class ActionDetail(BaseModel):
+ path: str
+ line: int | None = None
+ symbol: str | None = None
+ marker: str | None = None
+ severity: str | None = None
+ reason: str = ""
+ ref: str | None = None
+
+
+class ActionCommand(BaseModel):
+ purpose: str
+ mcp: str | None = None
+ cli: str | None = None
+
+
+class NextAction(BaseModel):
+ id: str
+ rule: str
+ tier: Literal["act_now", "plan", "improve_signal"]
+ horizons: list[Literal["week", "quarter"]]
+ severity: Literal["critical", "high", "medium", "low"]
+ title: str = Field(description="Verb first; paths and symbols wrapped in backticks.")
+ impact: str
+ why: list[ActionWhy]
+ target: ActionTarget
+ surface: str
+ effort: Literal["S", "M", "L"]
+ confidence: Literal["high", "medium"]
+ done_when: str
+ command: str | None = None
+ marker: str | None = None
+ evidence_ids: list[str]
+ evidence_total: int
+ includes: list[str]
+ fingerprint: str
+ details: list[ActionDetail] = Field(default_factory=list)
+ details_total: int = 0
+ commands: list[ActionCommand] = Field(default_factory=list)
+
+
+class ActionHorizon(BaseModel):
+ actions: list[NextAction]
+ total: int = Field(description="Every visible action in this horizon, not only those listed.")
+ hidden: int = Field(description="Actions the person dismissed, snoozed or marked done.")
+ by_tier: dict[str, int]
+
+
+class ActionRuleStatus(BaseModel):
+ rule: str
+ status: Literal["evaluated", "not_applicable", "unavailable"]
+ reason: str
+ emitted: int
+
+
+class ActionContext(BaseModel):
+ production_files: int
+ active_authors_90d: int
+ fix_commits_90d: int
+ busy_threshold: int
+ coverage: Literal["measured", "stale", "unknown"]
+
+
+class ActionsResponse(BaseModel):
+ status: Literal["available"]
+ anchor: str | None = Field(description="Newest indexed commit time; windows count back from it.")
+ week_start: str | None
+ context: ActionContext
+ horizons: dict[Literal["week", "quarter"], ActionHorizon]
+ rules: list[ActionRuleStatus]
+ unavailable: dict[str, str]
+
+
+class ActionStateRequest(BaseModel):
+ state: Literal["dismissed", "snoozed", "done"] | None = Field(
+ description="None clears the person's answer."
+ )
+ fingerprint: str = Field("", max_length=32)
+ snooze_days: int = Field(14, ge=1, le=365)
+
+
+class ActionStateResponse(BaseModel):
+ action_id: str
+ state: Literal["dismissed", "snoozed", "done"] | None
+ until: datetime | None = None
+
+
+class WorkspaceRepoActions(BaseModel):
+ alias: str
+ repo_id: str | None
+ status: Literal["available", "unavailable"]
+ reason: str = ""
+ #: The strongest work per horizon (act now and plan tiers only), with totals.
+ horizons: dict[Literal["week", "quarter"], ActionHorizon] = Field(default_factory=dict)
+
+
+class WorkspaceCrossRepoAction(BaseModel):
+ kind: Literal["breaking_contract"]
+ title: str
+ impact: str
+ count: int
+ repos: list[str]
+
+
+class WorkspaceActionsResponse(BaseModel):
+ repos: list[WorkspaceRepoActions]
+ cross_repo: list[WorkspaceCrossRepoAction]
diff --git a/packages/server/src/repowise/server/services/attention.py b/packages/server/src/repowise/server/services/attention.py
index af97492b8..cce0e7eb1 100644
--- a/packages/server/src/repowise/server/services/attention.py
+++ b/packages/server/src/repowise/server/services/attention.py
@@ -24,6 +24,7 @@ from repowise.core.analysis.attention import (
severity_of_file_score,
silo_source,
)
+from repowise.core.analysis.health.scoring import HISTORY_CATEGORY, biomarker_category
from repowise.core.persistence.models import (
DeadCodeFinding,
DocDriftFinding,
@@ -100,7 +101,10 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
# The biomarker to name each file by: its own heaviest one. Bounded to the
# handful of files above, so this is a keyed read rather than a scan.
paths = [r.file_path for r in rows]
+ # A history marker names only when the file has nothing an edit can fix,
+ # the same rule `primary_finding` applies everywhere else.
lead_biomarker: dict[str, str] = {}
+ history_lead: dict[str, str] = {}
for path, biomarker in (
await session.execute(
select(HealthFinding.file_path, HealthFinding.biomarker_type)
@@ -108,6 +112,11 @@ async def _health_items(session: AsyncSession, repo_id: str) -> tuple[list[dict]
.order_by(HealthFinding.health_impact.desc())
)
).all():
+ if biomarker_category(biomarker) == HISTORY_CATEGORY:
+ history_lead.setdefault(path, biomarker)
+ else:
+ lead_biomarker.setdefault(path, biomarker)
+ for path, biomarker in history_lead.items():
lead_biomarker.setdefault(path, biomarker)
items = [
diff --git a/packages/types/package.json b/packages/types/package.json
index 1e4b2ef96..760dac2ea 100644
--- a/packages/types/package.json
+++ b/packages/types/package.json
@@ -27,6 +27,7 @@
"./owners": "./src/owners.ts",
"./modules": "./src/modules.ts",
"./overview": "./src/overview.ts",
+ "./actions": "./src/actions.ts",
"./repos": "./src/repos.ts",
"./files": "./src/files.ts",
"./external-systems": "./src/external-systems.ts",
diff --git a/packages/types/src/actions.ts b/packages/types/src/actions.ts
new file mode 100644
index 000000000..a884b1b03
--- /dev/null
+++ b/packages/types/src/actions.ts
@@ -0,0 +1,173 @@
+/**
+ * Next actions: the short list of things worth doing, built from the index.
+ *
+ * Mirrors `repowise.core.analysis.actions.model` and the server's
+ * `schemas/actions.py`. `test_wire_vocabulary_parity.py` fails when the unions
+ * below and their Python twins disagree.
+ */
+
+export type ActionRule =
+ | "live_secret"
+ | "fresh_regressions"
+ | "fragile_file"
+ | "fix_concentration"
+ | "hot_path_perf"
+ | "stale_decision"
+ | "knowledge_loss"
+ | "broken_doc_refs"
+ | "dead_code_batch"
+ | "coverage_missing"
+ | "coverage_stale"
+ | "decisions_unreviewed";
+
+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";
+
+/** `unknown` is printed as a fact, never read as zero. */
+export type ActionFactBasis = "measured" | "inferred" | "unknown";
+
+export type ActionSurface =
+ | "file"
+ | "findings"
+ | "performance"
+ | "security"
+ | "doc_drift"
+ | "dead_code"
+ | "decisions"
+ | "commits"
+ | "coverage";
+
+export type ActionTargetKind = "file" | "symbol" | "folder" | "document" | "decision" | "repo";
+
+export type ActionRuleStatus = "evaluated" | "not_applicable" | "unavailable";
+
+export type ActionStateValue = "dismissed" | "snoozed" | "done";
+
+export type ActionSeverity = "critical" | "high" | "medium" | "low";
+
+export interface ActionWhy {
+ label: string;
+ value: string;
+ basis: ActionFactBasis;
+}
+
+/** One piece of evidence: a finding, a site, a reference. */
+export interface ActionDetail {
+ path: string;
+ line: number | null;
+ symbol: string | null;
+ marker: string | null;
+ severity: string | null;
+ reason: string;
+ /** The commit or stored id that produced it. */
+ ref: string | null;
+}
+
+/** A way to see more: the MCP call for an agent, the CLI line for a person. */
+export interface ActionCommand {
+ purpose: string;
+ mcp: string | null;
+ cli: string | null;
+}
+
+export interface NextAction {
+ /** Stable across re-index: derived from the rule and its target. */
+ id: string;
+ rule: ActionRule;
+ tier: ActionTier;
+ horizons: ActionHorizonKey[];
+ severity: ActionSeverity;
+ /** Verb first. Paths and symbols are wrapped in backticks for a mono renderer. */
+ title: string;
+ impact: string;
+ why: ActionWhy[];
+ target: { kind: ActionTargetKind; path: string; symbol: string | null };
+ surface: ActionSurface;
+ effort: "S" | "M" | "L";
+ confidence: "high" | "medium";
+ done_when: string;
+ command: string | null;
+ /** The biomarker behind the action, for the glossary label. */
+ marker: string | null;
+ evidence_ids: string[];
+ evidence_total: number;
+ /** Files a folder-level or roll-up action speaks for. */
+ includes: string[];
+ /** Sent back with a dismissal; the action returns when it changes. */
+ fingerprint: string;
+ /** The evidence itself, capped; `details_total` is how many there were. */
+ details: ActionDetail[];
+ details_total: number;
+ commands: ActionCommand[];
+}
+
+export interface ActionHorizon {
+ actions: NextAction[];
+ /** Every visible action in this horizon, not only those listed. */
+ total: number;
+ /** Actions the person dismissed, snoozed or marked done. */
+ hidden: number;
+ by_tier: Partial<Record<ActionTier, number>>;
+}
+
+export interface ActionRuleReport {
+ rule: ActionRule;
+ status: ActionRuleStatus;
+ reason: string;
+ emitted: number;
+}
+
+export interface ActionsResponse {
+ status: "available";
+ /** Newest indexed commit; "this week" counts back from here, not from today. */
+ anchor: string | null;
+ week_start: string | null;
+ context: {
+ production_files: number;
+ active_authors_90d: number;
+ fix_commits_90d: number;
+ busy_threshold: number;
+ coverage: "measured" | "stale" | "unknown";
+ };
+ horizons: Record<ActionHorizonKey, ActionHorizon>;
+ rules: ActionRuleReport[];
+ /** Store name to why it could not be read. */
+ unavailable: Record<string, string>;
+}
+
+export interface ActionStateRequest {
+ /** `null` clears the person's answer. */
+ state: ActionStateValue | null;
+ fingerprint?: string;
+ snooze_days?: number;
+}
+
+export interface ActionStateResponse {
+ action_id: string;
+ state: ActionStateValue | null;
+ until: string | null;
+}
+
+export interface WorkspaceRepoActions {
+ alias: string;
+ repo_id: string | null;
+ status: "available" | "unavailable";
+ reason: string;
+ /** The strongest work per horizon (act now and plan tiers), with totals. */
+ horizons: Partial<Record<ActionHorizonKey, ActionHorizon>>;
+}
+
+export interface WorkspaceCrossRepoAction {
+ kind: "breaking_contract";
+ title: string;
+ impact: string;
+ count: number;
+ repos: string[];
+}
+
+export interface WorkspaceActionsResponse {
+ repos: WorkspaceRepoActions[];
+ cross_repo: WorkspaceCrossRepoAction[];
+}
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 3bfbc2b9c..fc2d22239 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -9,6 +9,82 @@
// `?` mirrors the schema's `required` list, which states what a request may
// omit. A response field with a server-side default is still always sent.
+export interface ActionCommand {
+ purpose: string;
+ mcp?: string | null;
+ cli?: string | null;
+}
+
+export interface ActionContext {
+ production_files: number;
+ active_authors_90d: number;
+ fix_commits_90d: number;
+ busy_threshold: number;
+ coverage: "measured" | "stale" | "unknown";
+}
+
+export interface ActionDetail {
+ path: string;
+ line?: number | null;
+ symbol?: string | null;
+ marker?: string | null;
+ severity?: string | null;
+ reason?: string;
+ ref?: string | null;
+}
+
+export interface ActionHorizon {
+ actions: NextAction[];
+ /** Every visible action in this horizon, not only those listed. */
+ total: number;
+ /** Actions the person dismissed, snoozed or marked done. */
+ hidden: number;
+ by_tier: Record<string, number>;
+}
+
+export interface ActionRuleStatus {
+ rule: string;
+ status: "evaluated" | "not_applicable" | "unavailable";
+ reason: string;
+ emitted: number;
+}
+
+export interface ActionStateRequest {
+ /** None clears the person's answer. */
+ state: "dismissed" | "snoozed" | "done" | null;
+ fingerprint?: string;
+ snooze_days?: number;
+}
+
+export interface ActionStateResponse {
+ action_id: string;
+ state: "dismissed" | "snoozed" | "done" | null;
+ until?: string | null;
+}
+
+export interface ActionTarget {
+ kind: "file" | "symbol" | "folder" | "document" | "decision" | "repo";
+ path: string;
+ symbol?: string | null;
+}
+
+export interface ActionWhy {
+ label: string;
+ value: string;
+ basis: "measured" | "inferred" | "unknown";
+}
+
+export interface ActionsResponse {
+ status: "available";
+ /** Newest indexed commit time; windows count back from it. */
+ anchor: string | null;
+ week_start: string | null;
+ context: ActionContext;
+ horizons: Record<string, ActionHorizon>;
+ rules: ActionRuleStatus[];
+ unavailable: Record<string, string>;
+}
+
/** The provider/model this scope resolves to; ``None`` when unset. */
export interface ActiveProviderSelection {
provider?: string | null;
@@ -2002,6 +2078,32 @@ export interface NeighboringCommunity {
cross_edge_count: number;
}
+export interface NextAction {
+ id: string;
+ rule: string;
+ tier: "act_now" | "plan" | "improve_signal";
+ horizons: ("week" | "quarter")[];
+ severity: "critical" | "high" | "medium" | "low";
+ /** Verb first; paths and symbols wrapped in backticks. */
+ title: string;
+ impact: string;
+ why: ActionWhy[];
+ target: ActionTarget;
+ surface: string;
+ effort: "S" | "M" | "L";
+ confidence: "high" | "medium";
+ done_when: string;
+ command?: string | null;
+ marker?: string | null;
+ evidence_ids: string[];
+ evidence_total: number;
+ includes: string[];
+ fingerprint: string;
+ details?: ActionDetail[];
+ details_total?: number;
+ commands?: ActionCommand[];
+}
+
export interface NodeSearchResult {
node_id: string;
language: string;
@@ -2986,6 +3088,11 @@ export interface WebhookResponse {
status?: string;
}
+export interface WorkspaceActionsResponse {
+ repos: WorkspaceRepoActions[];
+ cross_repo: WorkspaceCrossRepoAction[];
+}
+
/** Architecture-complexity metrics over the system graph (Phase 6). */
export interface WorkspaceArchitectureResponse {
node_count?: number;
@@ -3163,6 +3270,14 @@ export interface WorkspaceContractsResponse {
by_type?: Record<string, number>;
}
+export interface WorkspaceCrossRepoAction {
+ kind: "breaking_contract";
+ title: string;
+ impact: string;
+ count: number;
+ repos: string[];
+}
+
export interface WorkspaceCrossRepoSummary {
co_change_count?: number;
package_dep_count?: number;
@@ -3254,6 +3369,14 @@ export interface WorkspaceOrphanProvider {
contract_type: string;
}
+export interface WorkspaceRepoActions {
+ alias: string;
+ repo_id: string | null;
+ status: "available" | "unavailable";
+ reason?: string;
+ horizons?: Record<string, ActionHorizon>;
+}
+
export interface WorkspaceRepoDiagnostics {
repo: string;
providers_by_type?: Record<string, number>;
diff --git a/packages/ui/__tests__/health/action-prompt.test.ts b/packages/ui/__tests__/health/action-prompt.test.ts
new file mode 100644
index 000000000..a4921ffc7
--- /dev/null
+++ b/packages/ui/__tests__/health/action-prompt.test.ts
@@ -0,0 +1,65 @@
+import { describe, expect, it } from "vitest";
+import type { NextAction } from "@repowise-dev/types/actions";
+
+import { buildActionPrompt } from "../../src/health/ai-prompts/action-prompt";
+
+const rollup: NextAction = {
+ id: "act_1",
+ rule: "fresh_regressions",
+ tier: "act_now",
+ horizons: ["week"],
+ severity: "critical",
+ title: "Clean up what this week's commits left: 3 serious findings in 2 files",
+ impact: "2 commits in the last 7 days added or worsened them.",
+ why: [{ label: "critical", value: "1", basis: "measured" }],
+ target: { kind: "repo", path: "", symbol: null },
+ surface: "commits",
+ effort: "M",
+ confidence: "high",
+ done_when: "The findings close on the next update.",
+ command: null,
+ marker: null,
+ evidence_ids: ["abc1234def"],
+ evidence_total: 3,
+ includes: ["src/a.py", "src/b.py"],
+ fingerprint: "fp",
+ details: [
+ {
+ path: "src/a.py",
+ line: 40,
+ symbol: "src/a.py::build",
+ marker: "complex_method",
+ severity: "critical",
+ reason: "build has cyclomatic complexity 31",
+ ref: "abc1234def5678",
+ },
+ ],
+ details_total: 3,
+ commands: [
+ {
+ purpose: "Every open finding in these files",
+ mcp: 'get_health(targets=["src/a.py", "src/b.py"], include=["biomarkers"])',
+ cli: "repowise health --file src/a.py",
+ },
+ ],
+};
+
+describe("buildActionPrompt", () => {
+ it("carries the findings themselves, not just file names", () => {
+ const text = buildActionPrompt({ action: rollup });
+ expect(text).toContain("`src/a.py:40`: `build`");
+ expect(text).toContain("build has cyclomatic complexity 31");
+ expect(text).toContain("commit abc1234def");
+ expect(text).toContain("## Evidence (1 of 3, worst first)");
+ expect(text).toContain("…and 2 more.");
+ });
+
+ it("gives an MCP agent the MCP call and anyone else the CLI line", () => {
+ expect(buildActionPrompt({ action: rollup, flavor: "claude-code-mcp" })).toContain(
+ 'get_health(targets=["src/a.py", "src/b.py"], include=["biomarkers"])',
+ );
+ const generic = buildActionPrompt({ action: rollup, flavor: "generic" });
+ expect(generic).toContain("repowise health --file src/a.py");
+ expect(generic).not.toContain("working on one file");
+ });
+});
diff --git a/packages/ui/__tests__/health/performance-presentation.test.ts b/packages/ui/__tests__/health/performance-presentation.test.ts
index 05e5ccbe5..24f9ede52 100644
--- a/packages/ui/__tests__/health/performance-presentation.test.ts
+++ b/packages/ui/__tests__/health/performance-presentation.test.ts
@@ -12,15 +12,34 @@ import {
planPresentation,
siblingFixLabel,
whyRankedLabel,
+ whyRankedPhrase,
} from "../../src/health/performance/presentation";
import { contiguousSections } from "../../src/health/performance/queue";
import { opportunity } from "./fixtures/performance";
describe("performance presentation", () => {
- it("titles a cause in words and keeps the sink out of the title", () => {
+ it("titles a cause in words, then names where by its short symbol", () => {
const title = opportunityTitle(opportunity());
- expect(title).toBe("Database call inside a loop");
+ expect(title).toBe("Database call inside a loop in load");
expect(title).not.toContain("::");
+ expect(opportunityTitle(opportunity({ intervention_symbol: null }))).toBe(
+ "Database call inside a loop in run",
+ );
+ });
+
+ it("reads rank factors as reasons, not points", () => {
+ expect(whyRankedPhrase({ factor: "affected_call_sites", value: 8, points: 6 })).toBe(
+ "8 call sites",
+ );
+ expect(whyRankedPhrase({ factor: "boundary_kind", value: "db", points: 4 })).toBe(
+ "a database call",
+ );
+ expect(whyRankedPhrase({ factor: "multiplier_shape", value: "io_in_loop", points: 4 })).toBe(
+ "runs once per loop iteration",
+ );
+ expect(whyRankedPhrase({ factor: "entry_reachability", value: true, points: 3 })).toBe(
+ "reachable from an entry point",
+ );
});
it("gives every performance marker a non-empty title", () => {
diff --git a/packages/ui/__tests__/health/performance-view.test.tsx b/packages/ui/__tests__/health/performance-view.test.tsx
index da95fb704..c42e6b88a 100644
--- a/packages/ui/__tests__/health/performance-view.test.tsx
+++ b/packages/ui/__tests__/health/performance-view.test.tsx
@@ -105,10 +105,11 @@ describe("PerformanceView queue", () => {
expect(headings[2]).toContain("Needs investigation");
});
- it("shows the cause in words with the sink as separate monospace evidence", async () => {
+ it("shows the cause in words, where in mono, and the sink as separate evidence", async () => {
render(<PerformanceView adapter={adapter()} />);
const [first] = await rows();
- expect(within(first!).getByText("Database call inside a loop")).toBeTruthy();
+ expect(within(first!).getByText(/Database call inside a loop in/)).toBeTruthy();
+ expect(within(first!).getByText("load").tagName).toBe("CODE");
expect(within(first!).getByText("src/db.py::fetch")).toBeTruthy();
expect(within(first!).getByText(/2 call sites across 2 files/)).toBeTruthy();
expect(within(first!).getByText(/High evidence confidence/)).toBeTruthy();
@@ -780,7 +781,7 @@ describe("PerformanceView accessibility", () => {
render(<PerformanceView adapter={adapter()} />);
const [first] = await rows();
expect(first!.getAttribute("tabindex")).toBe("0");
- expect(first!.getAttribute("aria-label")).toBe("Inspect Database call inside a loop");
+ expect(first!.getAttribute("aria-label")).toBe("Inspect Database call inside a loop in load");
fireEvent.keyDown(first!, { key: "Enter" });
expect(await screen.findByRole("dialog")).toBeTruthy();
});
diff --git a/packages/ui/__tests__/health/refactoring-card.test.tsx b/packages/ui/__tests__/health/refactoring-card.test.tsx
index 62a36c286..35b60b71a 100644
--- a/packages/ui/__tests__/health/refactoring-card.test.tsx
+++ b/packages/ui/__tests__/health/refactoring-card.test.tsx
@@ -111,3 +111,23 @@ describe("RefactoringCard lazy findings", () => {
expect(screen.queryByRole("button", { name: /findings/ })).not.toBeInTheDocument();
});
});
+
+describe("a file led by a history marker", () => {
+ it("reads as Watch, explains why, and offers no fix prompt", () => {
+ render(
+ <RefactoringCard
+ target={target({ primary_biomarker: "change_entropy", biomarkers: ["change_entropy"] })}
+ onGeneratePrompt={vi.fn()}
+ />,
+ );
+ expect(screen.getByText("Watch")).toBeInTheDocument();
+ expect(screen.getByText(/Editing the file will not clear it/)).toBeInTheDocument();
+ expect(screen.queryByText("AI fix prompt")).not.toBeInTheDocument();
+ });
+
+ it("keeps the fix prompt for a code-shape lead", () => {
+ render(<RefactoringCard target={target()} onGeneratePrompt={vi.fn()} />);
+ expect(screen.getByText("AI fix prompt")).toBeInTheDocument();
+ expect(screen.queryByText("Watch")).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/__tests__/overview/next-actions.test.tsx b/packages/ui/__tests__/overview/next-actions.test.tsx
new file mode 100644
index 000000000..3e97ea4bc
--- /dev/null
+++ b/packages/ui/__tests__/overview/next-actions.test.tsx
@@ -0,0 +1,177 @@
+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 { actionHref } from "../../src/overview/action-href.js";
+
+function action(overrides: Partial<NextAction> = {}): NextAction {
+ return {
+ id: "act_1",
+ rule: "fragile_file",
+ tier: "plan",
+ horizons: ["quarter"],
+ severity: "high",
+ title: "Raise test coverage on `src/a.py` from 62%",
+ impact: "Changed 30 times in 90 days, and 9 of those commits were bug fixes.",
+ why: [
+ { label: "commits in 90 days", value: "30", basis: "measured" },
+ { label: "line coverage", value: "Unknown, no report", basis: "unknown" },
+ ],
+ target: { kind: "file", path: "src/a.py", symbol: null },
+ surface: "file",
+ effort: "M",
+ confidence: "high",
+ done_when: "Line coverage on this file reaches 80%.",
+ command: null,
+ marker: null,
+ evidence_ids: [],
+ evidence_total: 0,
+ details: [],
+ details_total: 0,
+ commands: [],
+ includes: [],
+ fingerprint: "fp1",
+ ...overrides,
+ };
+}
+
+function response(week: NextAction[], quarter: NextAction[]): ActionsResponse {
+ const horizon = (actions: NextAction[]) => ({
+ actions,
+ total: actions.length,
+ hidden: 0,
+ by_tier: actions.reduce<Record<string, number>>((acc, a) => {
+ acc[a.tier] = (acc[a.tier] ?? 0) + 1;
+ return acc;
+ }, {}),
+ });
+ return {
+ status: "available",
+ anchor: "2026-09-28T09:45:08",
+ week_start: "2026-09-21T09:45:08",
+ context: {
+ production_files: 100,
+ active_authors_90d: 2,
+ fix_commits_90d: 40,
+ busy_threshold: 8,
+ coverage: "unknown",
+ },
+ horizons: { week: horizon(week), quarter: horizon(quarter) },
+ rules: [
+ { rule: "fragile_file", status: "evaluated", reason: "", emitted: 1 },
+ {
+ rule: "knowledge_loss",
+ status: "not_applicable",
+ reason: "2 active authors in 90 days.",
+ emitted: 0,
+ },
+ ],
+ unavailable: {},
+ };
+}
+
+describe("NextActions", () => {
+ it("sets paths in mono and leads with the time frame that has work", () => {
+ render(<NextActions data={response([], [action()])} hrefFor={() => "/x"} />);
+ const row = screen.getByRole("listitem", { name: /Open Raise test coverage/ });
+ expect(within(row).getByText("src/a.py").tagName).toBe("CODE");
+ expect(screen.getByRole("radio", { name: /This quarter/ })).toHaveAttribute(
+ "aria-checked",
+ "true",
+ );
+ expect(screen.getByText("Unknown, no report")).toBeInTheDocument();
+ });
+
+ it("switches horizon with the segmented control", () => {
+ const now = action({ id: "act_now", tier: "act_now", severity: "critical", horizons: ["week"], title: "Clean up `b.ts`" });
+ render(<NextActions data={response([now], [action()])} hrefFor={() => null} />);
+ expect(screen.getByText("Now")).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("radio", { name: /This quarter/ }));
+ expect(screen.getByText("Worth planning")).toBeInTheDocument();
+ expect(screen.queryByText("Now")).not.toBeInTheDocument();
+ });
+
+ it("explains an empty time frame instead of rendering nothing", () => {
+ render(<NextActions data={response([], [])} hrefFor={() => null} />);
+ expect(screen.getByText(/none of them produced work/)).toBeInTheDocument();
+ expect(screen.getByText("2 active authors in 90 days.")).toBeInTheDocument();
+ });
+
+ it("removes a dismissed row at once and sends its fingerprint", async () => {
+ const onSetState = vi.fn().mockResolvedValue(undefined);
+ render(
+ <NextActions data={response([], [action()])} hrefFor={() => null} onSetState={onSetState} />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /More for Raise test coverage/ }));
+ fireEvent.click(await screen.findByText("Dismiss"));
+ expect(screen.queryByText(/Raise test coverage/)).not.toBeInTheDocument();
+ await waitFor(() => expect(onSetState).toHaveBeenCalledTimes(1));
+ expect(onSetState.mock.calls[0]?.[1]).toBe("dismissed");
+ expect(onSetState.mock.calls[0]?.[0].fingerprint).toBe("fp1");
+ });
+
+ it("brings a row back when the write fails", async () => {
+ const onSetState = vi.fn().mockRejectedValue(new Error("nope"));
+ render(
+ <NextActions data={response([], [action()])} hrefFor={() => null} onSetState={onSetState} />,
+ );
+ fireEvent.click(screen.getByRole("button", { name: /More for Raise test coverage/ }));
+ fireEvent.click(await screen.findByText("Snooze for 14 days"));
+ await waitFor(() => expect(screen.getByText(/Raise test coverage/)).toBeInTheDocument());
+ });
+
+ it("renders nothing for a server that predates actions", () => {
+ const { container } = render(<NextActions data={null} hrefFor={() => null} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
+
+describe("the action drawer", () => {
+ it("opens on a row click with the evidence link, the facts and the prompt", async () => {
+ render(<NextActions data={response([], [action()])} hrefFor={() => "/repos/r/files/src/a.py"} />);
+ fireEvent.click(screen.getByRole("listitem", { name: /Open Raise test coverage/ }));
+ const dialog = await screen.findByRole("dialog");
+ expect(within(dialog).getByRole("link", { name: /Open the file/ })).toHaveAttribute(
+ "href",
+ "/repos/r/files/src/a.py",
+ );
+ expect(within(dialog).getByText("Why it is on the list")).toBeInTheDocument();
+ expect(within(dialog).getByText("Not measured.")).toBeInTheDocument();
+ expect(within(dialog).getByRole("button", { name: /Copy prompt/ })).toBeInTheDocument();
+ expect(within(dialog).getAllByText(/Line coverage on this file reaches 80%/).length).toBe(2);
+ });
+});
+
+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\.$/);
+ });
+
+ 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.",
+ );
+ });
+});
+
+describe("actionHref", () => {
+ it("routes each surface to the page that holds its evidence", () => {
+ expect(actionHref(action(), "/repos/r")).toBe("/repos/r/files/src/a.py");
+ expect(
+ actionHref(action({ surface: "performance", evidence_ids: ["perf2_x"] }), "/repos/r"),
+ ).toBe("/repos/r/code-health?tab=performance&opportunity=perf2_x");
+ expect(
+ actionHref(
+ action({ surface: "decisions", target: { kind: "decision", path: "d1", symbol: null } }),
+ "/repos/r",
+ ),
+ ).toBe("/repos/r/decisions/d1");
+ });
+});
diff --git a/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx
new file mode 100644
index 000000000..eb23cbe7b
--- /dev/null
+++ b/packages/ui/__tests__/workspace/workspace-next-actions.test.tsx
@@ -0,0 +1,97 @@
+import { describe, expect, it } from "vitest";
+import { render, screen } from "@testing-library/react";
+import type { NextAction, WorkspaceActionsResponse } from "@repowise-dev/types/actions";
+
+import { WorkspaceNextActions } from "../../src/workspace/workspace-next-actions.js";
+
+function action(id: string, title: string, tier: NextAction["tier"] = "plan"): NextAction {
+ return {
+ id,
+ rule: "fragile_file",
+ tier,
+ horizons: ["week", "quarter"],
+ severity: tier === "act_now" ? "critical" : "high",
+ title,
+ impact: "Changed 30 times in 90 days.",
+ why: [],
+ target: { kind: "file", path: "src/a.py", symbol: null },
+ surface: "file",
+ effort: "M",
+ confidence: "high",
+ done_when: "Coverage reaches 80%.",
+ command: null,
+ marker: null,
+ evidence_ids: [],
+ evidence_total: 0,
+ details: [],
+ details_total: 0,
+ commands: [],
+ includes: [],
+ fingerprint: "fp",
+ };
+}
+
+function horizon(actions: NextAction[], total = actions.length) {
+ return {
+ actions,
+ total,
+ hidden: 0,
+ by_tier: {
+ act_now: actions.filter((a) => a.tier === "act_now").length,
+ plan: total - actions.filter((a) => a.tier === "act_now").length,
+ },
+ };
+}
+
+const data: WorkspaceActionsResponse = {
+ repos: [
+ {
+ alias: "backend",
+ repo_id: "b1",
+ status: "available",
+ reason: "",
+ horizons: { week: horizon([action("x", "Add tests around `poll.py`")], 3), quarter: horizon([]) },
+ },
+ {
+ alias: "frontend",
+ repo_id: "f1",
+ status: "available",
+ reason: "",
+ horizons: {
+ week: horizon([action("y", "Clean up `app.tsx`", "act_now")]),
+ quarter: horizon([]),
+ },
+ },
+ { alias: "docs", repo_id: null, status: "unavailable", reason: "Not indexed yet.", horizons: {} },
+ ],
+ cross_repo: [
+ {
+ kind: "breaking_contract",
+ title: "Resolve 2 breaking contract changes",
+ impact: "A provider changed a route another repository consumes.",
+ count: 2,
+ repos: ["frontend"],
+ },
+ ],
+};
+
+describe("WorkspaceNextActions", () => {
+ it("leads with cross-repo work, then the repository with work to do now", () => {
+ render(
+ <WorkspaceNextActions
+ data={data}
+ hrefFor={() => null}
+ repoHref={(id) => `/repos/${id}/overview`}
+ contractsHref="/workspace/contracts"
+ />,
+ );
+ const headings = screen.getAllByRole("heading", { level: 3 }).map((h) => h.textContent);
+ expect(headings).toEqual(["Across repositories", "frontend", "backend"]);
+ expect(screen.getByRole("link", { name: "All 3 in backend" })).toHaveAttribute(
+ "href",
+ "/repos/b1/overview",
+ );
+ expect(screen.getByText(/Not included: docs \(not indexed yet\)/)).toBeInTheDocument();
+ expect(screen.getByText(/5 things worth doing this week/)).toBeInTheDocument();
+ });
+});
diff --git a/packages/ui/src/health/ai-prompt-builder.ts b/packages/ui/src/health/ai-prompt-builder.ts
index a2b11c463..e29088f16 100644
--- a/packages/ui/src/health/ai-prompt-builder.ts
+++ b/packages/ui/src/health/ai-prompt-builder.ts
@@ -8,6 +8,7 @@
export type { AiPromptFlavor } from "./ai-prompts/shared";
export { buildAiPrompt, type BuildPromptOptions } from "./ai-prompts/refactor-prompt";
+export { buildActionPrompt, type BuildActionPromptOptions } from "./ai-prompts/action-prompt";
export {
buildCoverageAiPrompt,
type BuildCoveragePromptOptions,
diff --git a/packages/ui/src/health/ai-prompt-modal.tsx b/packages/ui/src/health/ai-prompt-modal.tsx
index d0c81fed6..7a5558183 100644
--- a/packages/ui/src/health/ai-prompt-modal.tsx
+++ b/packages/ui/src/health/ai-prompt-modal.tsx
@@ -54,14 +54,19 @@ function loadStoredFlavor(): AiPromptFlavor {
return "generic";
}
-export function AiPromptModal({
- open,
- onOpenChange,
+/**
+ * The prompt itself: which agent it is written for, the text, and a copy
+ * button. Shared by the modal and by drawers that show the prompt inline, so
+ * the chosen agent persists across both.
+ */
+export function AiPromptBlock({
getPrompt,
- filePath,
- title = "AI fix prompt",
- description = "A ready-to-paste prompt that gives your AI coding agent every detail needed to make this change in one focused pass.",
-}: AiPromptModalProps) {
+ bleed = "px-6",
+}: {
+ getPrompt: ((flavor: AiPromptFlavor) => string) | null;
+ /** Horizontal padding that matches the host's own, so the hairlines run edge to edge. */
+ bleed?: string;
+}) {
const [flavor, setFlavorState] = useState<AiPromptFlavor>(loadStoredFlavor);
const [copied, setCopied] = useState(false);
@@ -74,14 +79,9 @@ export function AiPromptModal({
}
};
- const prompt = useMemo(
- () => (getPrompt ? getPrompt(flavor) : ""),
- [getPrompt, flavor],
- );
+ const prompt = useMemo(() => (getPrompt ? getPrompt(flavor) : ""), [getPrompt, flavor]);
- useEffect(() => {
- if (!open) setCopied(false);
- }, [open]);
+ useEffect(() => setCopied(false), [prompt]);
const handleCopy = async () => {
try {
@@ -93,6 +93,74 @@ export function AiPromptModal({
}
};
+ return (
+ <div className="min-w-0 space-y-4">
+ {/* Full-bleed hairlines rather than a bordered, filled well. The
+ prompt is the thing you opened this to read, not an object you
+ can select or act on, so it does not earn a container. */}
+ <div className="min-w-0 divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
+ <div className={`min-w-0 space-y-2 py-4 ${bleed}`}>
+ <p className="font-mono text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
+ Target agent
+ </p>
+ <div className="max-w-full overflow-x-auto">
+ <ViewToggle
+ value={flavor}
+ options={FLAVORS.map((f) => ({ value: f.value, label: f.label }))}
+ onChange={setFlavor}
+ />
+ </div>
+ <p className="text-xs leading-snug text-[var(--color-text-tertiary)]">
+ {FLAVORS.find((f) => f.value === flavor)?.hint}
+ </p>
+ </div>
+
+ <div className={`min-w-0 max-w-full max-h-[420px] overflow-x-hidden overflow-y-auto py-4 ${bleed}`}>
+ <pre className="min-w-0 max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-[var(--color-text-primary)]">
+ {prompt}
+ </pre>
+ </div>
+ </div>
+
+ <div className={`flex min-w-0 flex-wrap items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)] ${bleed}`}>
+ <span className="min-w-0 tabular-nums">
+ {prompt.length.toLocaleString()} chars, approx{" "}
+ {Math.round(prompt.length / 4).toLocaleString()} tokens
+ </span>
+ <button
+ type="button"
+ onClick={handleCopy}
+ disabled={!prompt}
+ className={
+ "inline-flex shrink-0 items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " +
+ (copied
+ ? "bg-[var(--color-success)] text-[var(--color-text-inverse)]"
+ : "bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]")
+ }
+ >
+ {copied ? (
+ <>
+ <Check className="h-3.5 w-3.5" /> Copied
+ </>
+ ) : (
+ <>
+ <Copy className="h-3.5 w-3.5" /> Copy prompt
+ </>
+ )}
+ </button>
+ </div>
+ </div>
+ );
+}
+
+export function AiPromptModal({
+ open,
+ onOpenChange,
+ getPrompt,
+ filePath,
+ title = "AI fix prompt",
+ description = "A ready-to-paste prompt that gives your AI coding agent every detail needed to make this change in one focused pass.",
+}: AiPromptModalProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="min-w-0 w-[calc(100vw-2rem)] max-w-3xl overflow-hidden">
@@ -108,66 +176,9 @@ export function AiPromptModal({
</DialogTitle>
<DialogDescription>{description}</DialogDescription>
</DialogHeader>
-
- <div className="min-w-0 space-y-4">
- {/* Full-bleed hairlines rather than a bordered, filled well. The
- prompt is the thing you opened this to read, not an object you
- can select or act on, so it does not earn a container — and a
- second plane inside a floating panel is one plane too many. The
- rules run to the modal's edge (`-mx-6` against its `p-6`) so they
- read as the page's section dividers do, rather than as a box that
- happens to have lost its sides. */}
- <div className="-mx-6 min-w-0 divide-y divide-[var(--color-border-default)] border-y border-[var(--color-border-default)]">
- <div className="min-w-0 space-y-2 px-6 py-4">
- <p className="font-mono text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">
- Target agent
- </p>
- <div className="max-w-full overflow-x-auto">
- <ViewToggle
- value={flavor}
- options={FLAVORS.map((f) => ({ value: f.value, label: f.label }))}
- onChange={setFlavor}
- />
- </div>
- <p className="text-xs leading-snug text-[var(--color-text-tertiary)]">
- {FLAVORS.find((f) => f.value === flavor)?.hint}
- </p>
- </div>
-
- <div className="min-w-0 max-w-full max-h-[420px] overflow-x-hidden overflow-y-auto px-6 py-4">
- <pre className="min-w-0 max-w-full whitespace-pre-wrap [overflow-wrap:anywhere] font-mono text-xs leading-relaxed text-[var(--color-text-primary)]">
- {prompt}
- </pre>
- </div>
- </div>
-
- <div className="flex min-w-0 flex-wrap items-center justify-between gap-2 text-xs text-[var(--color-text-tertiary)]">
- <span className="min-w-0 tabular-nums">
- {prompt.length.toLocaleString()} chars, approx{" "}
- {Math.round(prompt.length / 4).toLocaleString()} tokens
- </span>
- <button
- type="button"
- onClick={handleCopy}
- disabled={!prompt}
- className={
- "inline-flex shrink-0 items-center gap-1.5 rounded-md px-3 py-1.5 text-xs font-semibold transition-colors " +
- (copied
- ? "bg-[var(--color-success)] text-[var(--color-text-inverse)]"
- : "bg-[var(--color-model)] text-[var(--color-text-on-model)] hover:bg-[var(--color-model-hover)]")
- }
- >
- {copied ? (
- <>
- <Check className="h-3.5 w-3.5" /> Copied
- </>
- ) : (
- <>
- <Copy className="h-3.5 w-3.5" /> Copy prompt
- </>
- )}
- </button>
- </div>
+ {/* The block's hairlines run to the modal's edge (`-mx-6` against its `p-6`). */}
+ <div className="-mx-6 min-w-0">
+ {open ? <AiPromptBlock getPrompt={getPrompt} /> : null}
</div>
</DialogContent>
</Dialog>
diff --git a/packages/ui/src/health/ai-prompts/action-prompt.ts b/packages/ui/src/health/ai-prompts/action-prompt.ts
new file mode 100644
index 000000000..8631501f5
--- /dev/null
+++ b/packages/ui/src/health/ai-prompts/action-prompt.ts
@@ -0,0 +1,137 @@
+import type { ActionDetail, NextAction } from "@repowise-dev/types/actions";
+
+import { biomarkerLabel } from "../biomarker-glossary";
+import { bulletList, closingSections, joinSections, repoSuffix, type AiPromptFlavor } from "./shared";
+
+// ─────────────────────────────────────────────────────────────────────
+// Next action prompt: one action from "Do next", handed to an agent cold
+// ─────────────────────────────────────────────────────────────────────
+
+export interface BuildActionPromptOptions {
+ action: NextAction;
+ flavor?: AiPromptFlavor;
+ repoName?: string;
+}
+
+/**
+ * The opening. Not the fix-prompt preamble: an action can span many files and
+ * is built from stored analysis, so the agent is told both before it reads a
+ * line.
+ */
+const OPENING: Record<AiPromptFlavor, string> = {
+ generic:
+ "You are a senior engineer in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis of the repository (git history, code health, the dependency graph). Its evidence is listed in full or in part; treat each item as a lead to verify against the code, not as ground truth.",
+ "claude-code":
+ "You are Claude Code in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: read the code with Read and Grep, confirm it, and use TodoWrite to track the files you work through.",
+ "claude-code-mcp":
+ "You are Claude Code in this repository, which Repowise indexes and serves over MCP. The action below comes from Repowise's stored analysis. Use the MCP calls listed under \"Look closer\" before reading files by hand: they return the full evidence with line numbers, reasons and history. Treat each item as a lead to confirm against the code.",
+ cursor:
+ "Work in this repository. Repowise, a code-intelligence index, produced the action below from its stored analysis. Treat each evidence item as a lead: open the file with @file, confirm it, then act.",
+};
+
+const CONSTRAINTS = [
+ "**Confirm each item before changing anything.** The analysis is stored, not live; the code may have moved since it ran.",
+ "**Stay inside what the action names.** Work only on the files and functions listed. If the right fix is elsewhere, stop and say where and why.",
+ "**Keep behaviour unless the action is about behaviour.** Refactors and test additions must not change what the code does; run the tests that cover each file before and after.",
+ "**Say when an item is wrong.** If a finding does not hold, or its fix would cost more than it saves, report that rather than forcing an edit.",
+];
+
+const EXPECTED = [
+ "1. For each item you looked at: whether it held, and what you changed or why you left it.",
+ "2. The tests you ran, before and after.",
+ "3. What remains against the done condition.",
+];
+
+function detailLine(d: ActionDetail): string {
+ const where = `\`${d.path}${d.line ? `:${d.line}` : ""}\``;
+ const what = [
+ d.symbol ? `\`${d.symbol.split("::").pop()}\`` : null,
+ d.marker ? biomarkerLabel(d.marker) : null,
+ d.severity,
+ ]
+ .filter(Boolean)
+ .join(", ");
+ const ref = d.ref && /^[0-9a-f]{7,40}$/.test(d.ref) ? ` (commit ${d.ref.slice(0, 10)})` : "";
+ return `- ${where}${what ? `: ${what}` : ""}${ref}${d.reason ? `\n - ${d.reason}` : ""}`;
+}
+
+/**
+ * Hand one next action to an agent: the claim, the evidence itself, how to get
+ * the rest, and what finished looks like. Written so an agent with no prior
+ * context can start work from this text alone.
+ */
+export function buildActionPrompt({
+ action,
+ flavor = "generic",
+ repoName,
+}: BuildActionPromptOptions): string {
+ const useMcp = flavor === "claude-code-mcp";
+ const shownDetails = action.details.length;
+ const moreDetails = action.details_total - shownDetails;
+ const target = action.target.symbol
+ ? `\`${action.target.path}\` (\`${action.target.symbol.split("::").pop()}\`)`
+ : action.target.path
+ ? `\`${action.target.path}\``
+ : null;
+
+ const commands = action.commands
+ .map((c) => {
+ const line = useMcp ? (c.mcp ?? c.cli) : (c.cli ?? c.mcp);
+ return line ? `- ${c.purpose}:\n \`${line}\`` : null;
+ })
+ .filter((l): l is string => l !== null);
+
+ return joinSections([
+ OPENING[flavor],
+ "",
+ `## Action${repoSuffix(repoName)}`,
+ "",
+ `**${action.title}**`,
+ "",
+ action.impact,
+ "",
+ "## Why it is on the list",
+ "",
+ bulletList([
+ target ? `Target: ${target}` : null,
+ ...action.why.map(
+ (w) => `${w.label}: ${w.value}${w.basis === "measured" ? "" : ` (${w.basis})`}`,
+ ),
+ `Effort estimate: ${action.effort}; confidence in the facts: ${action.confidence}`,
+ ]),
+ "",
+ shownDetails
+ ? joinSections([
+ `## Evidence (${shownDetails.toLocaleString()} of ${action.details_total.toLocaleString()}${
+ moreDetails > 0 ? ", worst first" : ""
+ })`,
+ "",
+ action.details.map(detailLine).join("\n"),
+ moreDetails > 0
+ ? `\n…and ${moreDetails.toLocaleString()} more. The first call under "Look closer" returns them.`
+ : "",
+ "",
+ ])
+ : action.includes.length
+ ? joinSections([
+ "## Files",
+ "",
+ action.includes.map((p) => `- \`${p}\``).join("\n"),
+ "",
+ ])
+ : "",
+ commands.length
+ ? joinSections([
+ useMcp ? "## Look closer (Repowise MCP)" : "## Look closer (Repowise CLI)",
+ "",
+ commands.join("\n"),
+ "",
+ ])
+ : "",
+ "## Done when",
+ "",
+ action.done_when + (action.command ? `\n\nCommand: \`${action.command}\`` : ""),
+ "",
+ ...closingSections(CONSTRAINTS, EXPECTED),
+ ]);
+}
diff --git a/packages/ui/src/health/biomarker-glossary.ts b/packages/ui/src/health/biomarker-glossary.ts
index 2a7466329..d49fb41f2 100644
--- a/packages/ui/src/health/biomarker-glossary.ts
+++ b/packages/ui/src/health/biomarker-glossary.ts
@@ -533,5 +533,20 @@ export const HISTORY_CHIP =
export const HISTORY_LABEL = "Watch";
+/**
+ * History-category markers that are still work: writing or updating a
+ * decision clears them. Mirrors core `GOVERNANCE_BIOMARKERS`.
+ */
+const GOVERNANCE_BIOMARKERS: ReadonlySet<string> = new Set([
+ "ungoverned_hotspot",
+ "stale_governance",
+ "contradictory_decision",
+]);
+
+/** A marker nothing in the repository can clear: context for a reviewer. */
+export function isWatchOnlyBiomarker(name: string): boolean {
+ return isHistoryBiomarker(name) && !GOVERNANCE_BIOMARKERS.has(name);
+}
+
export const HISTORY_EXPLAINER =
"Measured from this file's git history, not its code. Editing the file will not clear it.";
diff --git a/packages/ui/src/health/findings-view.tsx b/packages/ui/src/health/findings-view.tsx
index 5991d8f07..41f958a85 100644
--- a/packages/ui/src/health/findings-view.tsx
+++ b/packages/ui/src/health/findings-view.tsx
@@ -36,7 +36,12 @@ import {
import type { HealthWorkItemFinding } from "./refactoring-card";
import { FilterSelect, FilterChip } from "./code-health-controls";
import { ImpactEffortQuadrant } from "./impact-effort-quadrant";
-import { biomarkerLabel } from "./biomarker-glossary";
+import {
+ biomarkerLabel,
+ HISTORY_EXPLAINER,
+ HISTORY_LABEL,
+ isWatchOnlyBiomarker,
+} from "./biomarker-glossary";
import { buildAiPrompt } from "./ai-prompt-builder";
import { SEVERITY_LABEL, type Severity } from "./tokens";
import type { CodeHealthAdapter } from "./code-health-adapter";
@@ -270,7 +275,19 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
// not group size, so "Leverage" sorted stays leverage-led inside and out.
const grouped = useMemo(() => {
const targets = queue?.targets ?? [];
- if (groupBy === "none") return [{ key: "All", targets }];
+ if (groupBy === "none") {
+ // A file led by a history marker has nothing in its code to change, so
+ // it reads under Watch, after the files an edit can improve. The lead is
+ // a history marker only when the file has no code-shape finding at all.
+ const fix = targets.filter((t) => !isWatchOnlyBiomarker(t.primary_biomarker));
+ const watch = targets.filter((t) => isWatchOnlyBiomarker(t.primary_biomarker));
+ return watch.length
+ ? [
+ { key: "All", targets: fix },
+ { key: HISTORY_LABEL, targets: watch },
+ ].filter((g) => g.targets.length > 0)
+ : [{ key: "All", targets }];
+ }
const groups = new Map<string, typeof targets>();
for (const t of targets) {
let key = "—";
@@ -487,14 +504,20 @@ export function FindingsView({ adapter }: { adapter: CodeHealthAdapter }) {
<div className="space-y-6">
{grouped.map((g) => (
<section key={g.key} className="space-y-2">
- {groupBy !== "none" ? (
+ {groupBy !== "none" || g.key === HISTORY_LABEL ? (
<h3 className="text-xs font-medium uppercase tracking-wider text-[var(--color-text-tertiary)]">
{g.key}{" "}
<span className="text-[var(--color-text-secondary)]">
- ({g.targets.length})
+ ({g.targets.length}
+ {groupBy === "none" ? " on this page" : ""})
</span>
</h3>
) : null}
+ {groupBy === "none" && g.key === HISTORY_LABEL ? (
+ <p className="max-w-[72ch] text-xs text-[var(--color-text-tertiary)]">
+ {HISTORY_EXPLAINER}
+ </p>
+ ) : null}
<HealthWorkQueueList
targets={g.targets}
onSelect={(t) => setSelectedFile(t.file_path)}
diff --git a/packages/ui/src/health/performance-view.tsx b/packages/ui/src/health/performance-view.tsx
index 250b4549c..671c9757c 100644
--- a/packages/ui/src/health/performance-view.tsx
+++ b/packages/ui/src/health/performance-view.tsx
@@ -199,6 +199,12 @@ export function PerformanceView({
sub: `of ${summary.total.toLocaleString()} causes`,
},
];
+ // A zero does not lead: when nothing is proven safe, the ribbon opens on
+ // what there is, and "Plan ready: 0" still reads, just not first.
+ if (!summary.actionability?.plan_ready) {
+ const first = stats.shift();
+ if (first) stats.push(first);
+ }
return (
<div className="space-y-8">
diff --git a/packages/ui/src/health/performance/drawer.tsx b/packages/ui/src/health/performance/drawer.tsx
index 7013ebb43..e5faf3b83 100644
--- a/packages/ui/src/health/performance/drawer.tsx
+++ b/packages/ui/src/health/performance/drawer.tsx
@@ -203,27 +203,58 @@ function SiblingsNote({
);
}
-/** The plan's edits in order; only the rarer mechanical ones are marked. */
+/**
+ * The plan's edits in order; only the rarer mechanical ones are marked.
+ *
+ * Consecutive steps that make the same edit at different call sites read as
+ * one step with its locations: the server emits one step per site, and eight
+ * copies of "Collect the keys before the loop" said nothing seven times.
+ */
function PlanSteps({ steps }: { steps: PerformanceOpportunityPlanStep[] }) {
+ const groups: PerformanceOpportunityPlanStep[][] = [];
+ for (const step of [...steps].sort((a, b) => a.order - b.order)) {
+ const last = groups[groups.length - 1];
+ if (last && last[0]!.action === step.action && last[0]!.applicability === step.applicability) {
+ last.push(step);
+ } else {
+ groups.push([step]);
+ }
+ }
+ const where = (step: PerformanceOpportunityPlanStep) =>
+ step.file_path ? `${step.file_path}${step.line ? `:${step.line}` : ""}` : null;
return (
<ol className="mt-3 space-y-1.5">
- {[...steps]
- .sort((a, b) => a.order - b.order)
- .map((step) => (
- <li key={step.order} className="text-sm text-[var(--color-text-secondary)]">
- <span className="tabular-nums text-[var(--color-text-tertiary)]">{step.order}.</span>{" "}
- {step.action}
- {step.applicability === "mechanical" ? (
+ {groups.map((group, index) => {
+ const first = group[0]!;
+ const places = group.map(where).filter((p): p is string => Boolean(p));
+ return (
+ <li key={first.order} className="text-sm text-[var(--color-text-secondary)]">
+ <span className="tabular-nums text-[var(--color-text-tertiary)]">{index + 1}.</span>{" "}
+ {first.action}
+ {group.length > 1 ? (
+ <span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">
+ {`at ${group.length} call sites`}
+ </span>
+ ) : null}
+ {first.applicability === "mechanical" ? (
<span className="ml-1.5 text-xs text-[var(--color-text-tertiary)]">mechanical</span>
) : null}
- {step.file_path ? (
+ {places.length === 1 ? (
<span className="ml-1.5 break-all font-mono text-xs text-[var(--color-text-tertiary)]">
- {step.file_path}
- {step.line ? `:${step.line}` : ""}
+ {places[0]}
</span>
+ ) : places.length > 1 ? (
+ <ul className="mt-1 space-y-0.5 pl-5">
+ {places.map((p) => (
+ <li key={p} className="break-all font-mono text-xs text-[var(--color-text-tertiary)]">
+ {p}
+ </li>
+ ))}
+ </ul>
) : null}
</li>
- ))}
+ );
+ })}
</ol>
);
}
diff --git a/packages/ui/src/health/performance/presentation.ts b/packages/ui/src/health/performance/presentation.ts
index b7b7791a6..417bc0762 100644
--- a/packages/ui/src/health/performance/presentation.ts
+++ b/packages/ui/src/health/performance/presentation.ts
@@ -126,11 +126,8 @@ const CAUSE_BY_MARKER: Record<string, (boundary: C4IoKind | null) => string> = {
`${b ? boundaryNoun(b) : "Resource"} client constructed on every iteration`,
};
-/**
- * The cause a reader should act on, in words. The terminal sink is deliberately
- * absent: it is machine evidence and belongs in the monospace line beneath.
- */
-export function opportunityTitle(opportunity: PerformanceOpportunity): string {
+/** The cause in words: "Database call inside a loop". */
+export function opportunityCause(opportunity: PerformanceOpportunity): string {
const cause = CAUSE_BY_MARKER[opportunity.biomarker_type];
const phrase = cause
? cause(opportunity.boundary_kind)
@@ -138,6 +135,28 @@ export function opportunityTitle(opportunity: PerformanceOpportunity): string {
return phrase[0]!.toUpperCase() + phrase.slice(1);
}
+/**
+ * The short name of the place to change: the intervention symbol without its
+ * path, else the first caller, else the file's name. It is what separates two
+ * rows that share a cause; the full path stays in the evidence line.
+ */
+export function opportunitySubject(opportunity: PerformanceOpportunity): string {
+ const symbol = opportunity.intervention_symbol?.trim();
+ if (symbol) return symbol.split("::").pop() ?? symbol;
+ const first = opportunity.evidence[0]?.function_name;
+ if (first) return first;
+ return opportunity.file_path.split("/").pop() ?? opportunity.file_path;
+}
+
+/**
+ * The row's title: the cause, then where. Every database loop in a repository
+ * used to share one title ("Database call inside a loop" on 273 rows), so the
+ * part that told rows apart was the mono line nobody reads first.
+ */
+export function opportunityTitle(opportunity: PerformanceOpportunity): string {
+ return `${opportunityCause(opportunity)} in ${opportunitySubject(opportunity)}`;
+}
+
/**
* The machine evidence under the title: the sink the paths converge on, or the
* symbol worth editing, or the file. Whichever exists is monospace.
@@ -161,6 +180,43 @@ export function affectedSummary(opportunity: PerformanceOpportunity): string {
return `${sitePart} across ${filePart}`;
}
+const MULTIPLIER_PHRASE: Record<string, string> = {
+ io_in_loop: "runs once per loop iteration",
+ serial_await_in_loop: "awaited one at a time",
+ nested_loop_with_io: "runs inside nested loops",
+};
+
+/**
+ * A rank factor as a reader's reason, without the points: "8 call sites",
+ * "reachable from an entry point". The points stay in `whyRankedLabel`, which
+ * the drawer shows for anyone checking the arithmetic.
+ */
+export function whyRankedPhrase(factor: PerformanceWhyRanked): string {
+ const value = factor.value;
+ switch (factor.factor) {
+ case "affected_call_sites":
+ return typeof value === "number"
+ ? `${value.toLocaleString()} call site${value === 1 ? "" : "s"}`
+ : "several call sites";
+ case "boundary_kind":
+ return !value || value === NO_BOUNDARY
+ ? "in-process work"
+ : `a ${boundaryLabel(String(value)).toLowerCase()} call`;
+ case "multiplier_shape":
+ return MULTIPLIER_PHRASE[String(value)] ?? humanizeToken(String(value));
+ case "execution_context":
+ return `${contextLabel(String(value) as PerformanceExecutionContext).toLowerCase()} code`;
+ case "entry_reachability":
+ return "reachable from an entry point";
+ case "loop_magnitude":
+ return value === "grows_with_data" ? "grows with the data" : humanizeToken(String(value));
+ case "provenance":
+ return value === "call-site" ? "seen at the call site" : humanizeToken(String(value));
+ default:
+ return whyRankedLabel(factor);
+ }
+}
+
/** `Multiplier shape: serial await in loop (+4)`, capped by the server at three. */
export function whyRankedLabel(factor: PerformanceWhyRanked): string {
const name = humanizeToken(factor.factor);
diff --git a/packages/ui/src/health/performance/queue.tsx b/packages/ui/src/health/performance/queue.tsx
index 539f41299..7c58971aa 100644
--- a/packages/ui/src/health/performance/queue.tsx
+++ b/packages/ui/src/health/performance/queue.tsx
@@ -22,9 +22,12 @@ import {
contextLabel,
CONFIDENCE_LABEL,
opportunityEvidenceLine,
+ opportunityCause,
+ opportunitySubject,
opportunityTitle,
planPresentation,
whyRankedLabel,
+ whyRankedPhrase,
} from "./presentation";
/**
@@ -167,7 +170,10 @@ const OpportunityRow = memo(function OpportunityRow({
<div className="min-w-0 flex-1">
<p className="text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">
- {title}
+ {opportunityCause(opportunity)} in{" "}
+ <code className="font-mono text-[0.85em] [overflow-wrap:anywhere]">
+ {opportunitySubject(opportunity)}
+ </code>
</p>
<p className="mt-1 break-all font-mono text-xs text-[var(--color-text-secondary)]">
{opportunityEvidenceLine(opportunity)}
@@ -179,8 +185,11 @@ const OpportunityRow = memo(function OpportunityRow({
{CONFIDENCE_LABEL[opportunity.confidence]} evidence confidence
</p>
{why.length > 0 ? (
- <p className="mt-1 text-xs text-[var(--color-text-tertiary)]">
- Ranked on {why.map(whyRankedLabel).join(", ")}
+ <p
+ className="mt-1 text-xs text-[var(--color-text-tertiary)]"
+ title={`Ranked on ${why.map(whyRankedLabel).join(", ")}`}
+ >
+ Why here: {why.map(whyRankedPhrase).join(", ")}
</p>
) : null}
<div className="mt-2 sm:hidden">
diff --git a/packages/ui/src/health/refactoring-card.tsx b/packages/ui/src/health/refactoring-card.tsx
index dd6ed9215..5df146df6 100644
--- a/packages/ui/src/health/refactoring-card.tsx
+++ b/packages/ui/src/health/refactoring-card.tsx
@@ -3,7 +3,13 @@
import { useState } from "react";
import { ArrowUpRight, ChevronDown, ChevronRight, Sparkles } from "lucide-react";
import { InfoTip } from "../shared/info-tip";
-import { biomarkerInfo, biomarkerLabel } from "./biomarker-glossary";
+import {
+ biomarkerInfo,
+ biomarkerLabel,
+ HISTORY_EXPLAINER,
+ HISTORY_LABEL,
+ isWatchOnlyBiomarker,
+} from "./biomarker-glossary";
import type { BiomarkerDetailsRecord } from "./biomarker-details";
import { EFFORT_TINT, type Severity } from "./tokens";
import { ImpactFigure } from "./impact-figure";
@@ -113,6 +119,9 @@ export function HealthWorkItemCard({
// label no longer depend on shipping the findings themselves.
const findings = target.all_findings ?? loaded;
const hasFindings = target.finding_count > 0;
+ // Led by a history marker: context for a reviewer, not something an edit
+ // clears, so the card neither rates it as a defect nor offers a fix prompt.
+ const watch = isWatchOnlyBiomarker(target.primary_biomarker);
const toggle = async () => {
const next = !expanded;
@@ -145,7 +154,13 @@ export function HealthWorkItemCard({
>
<div className="p-4 space-y-2">
<div className="flex items-center gap-2 flex-wrap">
- <SeverityMark severity={target.primary_severity} />
+ {watch ? (
+ <span className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {HISTORY_LABEL}
+ </span>
+ ) : (
+ <SeverityMark severity={target.primary_severity} />
+ )}
<span className="inline-flex items-center gap-1 text-xs font-semibold text-[var(--color-text-primary)]">
{biomarkerLabel(target.primary_biomarker)}
{biomarkerInfo(target.primary_biomarker).description ? (
@@ -176,7 +191,11 @@ export function HealthWorkItemCard({
target: target.file_path,
targetKind: "path",
}}
- question={`Explain the ${biomarkerLabel(target.primary_biomarker)} finding in ${target.file_path} and propose a safe way to address it.`}
+ question={
+ watch
+ ? `What does the ${biomarkerLabel(target.primary_biomarker)} signal say about ${target.file_path}, and what should a reviewer watch for when it changes?`
+ : `Explain the ${biomarkerLabel(target.primary_biomarker)} finding in ${target.file_path} and propose a safe way to address it.`
+ }
label={`Ask about the finding in ${target.file_path}`}
className="-my-1 h-6 w-6"
/>
@@ -221,7 +240,10 @@ export function HealthWorkItemCard({
</span>
<span className="ml-auto tabular-nums">leverage {target.impact_per_effort.toFixed(2)}</span>
</div>
- {onGeneratePrompt ? (
+ {watch ? (
+ <p className="text-xs text-[var(--color-text-tertiary)]">{HISTORY_EXPLAINER}</p>
+ ) : null}
+ {onGeneratePrompt && !watch ? (
<div className="pt-2">
<button
type="button"
diff --git a/packages/ui/src/overview/action-drawer.tsx b/packages/ui/src/overview/action-drawer.tsx
new file mode 100644
index 000000000..9d6a00bcb
--- /dev/null
+++ b/packages/ui/src/overview/action-drawer.tsx
@@ -0,0 +1,353 @@
+"use client";
+
+import { useState, type ElementType, type ReactNode } from "react";
+import { ArrowUpRight, BellOff, Check, X } from "lucide-react";
+import type {
+ ActionDetail,
+ ActionStateValue,
+ ActionSurface,
+ NextAction,
+} from "@repowise-dev/types/actions";
+
+import { AiPromptBlock } from "../health/ai-prompt-modal";
+import { buildActionPrompt } from "../health/ai-prompts/action-prompt";
+import { biomarkerLabel } from "../health/biomarker-glossary";
+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",
+};
+
+const EFFORT_LABEL: Record<NextAction["effort"], string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+};
+
+/** What the evidence link opens, named for the place it lands. */
+const EVIDENCE_LABEL: Record<ActionSurface, string> = {
+ file: "Open the file",
+ findings: "Open the findings",
+ performance: "Open it on Performance",
+ security: "Open Security",
+ doc_drift: "Open Doc drift",
+ dead_code: "Open Dead code",
+ decisions: "Open the decision",
+ commits: "Open recent commits",
+ coverage: "Open Coverage",
+};
+
+const BASIS_NOTE: Record<string, string | null> = {
+ measured: null,
+ inferred: "Inferred from the code graph, not measured.",
+ unknown: "Not measured.",
+};
+
+export interface ActionDrawerProps {
+ action: NextAction | null;
+ onClose: () => void;
+ /** Where the action's evidence lives; the old row link. */
+ evidenceHref: string | null;
+ /** A file's own page, for the files the action names. */
+ fileHref?: ((path: string) => string | null) | undefined;
+ /** Omit to hide the done, snooze and dismiss verbs. */
+ onAnswer?: ((state: ActionStateValue, message: string) => void) | undefined;
+ repoName?: string | undefined;
+ LinkComponent?: ElementType | undefined;
+ renderTitle: (title: string) => ReactNode;
+}
+
+function Section({ title, children }: { title: string; children: ReactNode }) {
+ return (
+ <section>
+ <h4 className="mb-2 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {title}
+ </h4>
+ {children}
+ </section>
+ );
+}
+
+/**
+ * One action, opened: why it is on the list, where to work, what done looks
+ * like, and a prompt ready for an agent. The row stays a one-line summary; the
+ * reading happens here, the same way a performance cause or a file opens on
+ * the Code Health pages.
+ */
+export function ActionDrawer({
+ action,
+ onClose,
+ evidenceHref,
+ fileHref,
+ onAnswer,
+ repoName,
+ LinkComponent,
+ renderTitle,
+}: ActionDrawerProps) {
+ const Link = LinkComponent ?? "a";
+ const linkCls =
+ "rounded text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";
+
+ return (
+ <AdaptivePanel
+ open={action !== null}
+ onOpenChange={(open) => {
+ if (!open) onClose();
+ }}
+ eyebrow={action ? TIER_LABEL[action.tier] : "Next action"}
+ title={action ? renderTitle(action.title) : "Next action"}
+ widthClassName="md:max-w-[680px]"
+ >
+ {action ? (
+ <div className="flex min-h-0 flex-1 flex-col">
+ <div className="flex-1 space-y-7 overflow-y-auto px-5 py-5">
+ <div className="space-y-2">
+ {action.tier === "act_now" ? <SeverityMark severity={action.severity} /> : null}
+ <p className="text-[15px] leading-relaxed text-[var(--color-text-primary)] [text-wrap:pretty]">
+ {renderTitle(action.impact)}
+ </p>
+ {evidenceHref ? (
+ <Link href={evidenceHref} className={`inline-flex items-center gap-1 text-sm ${linkCls}`}>
+ {EVIDENCE_LABEL[action.surface]}
+ <ArrowUpRight className="h-3.5 w-3.5" aria-hidden="true" />
+ </Link>
+ ) : null}
+ </div>
+
+ {action.why.length > 0 ? (
+ <Section title="Why it is on the list">
+ <dl className="grid grid-cols-1 gap-x-4 gap-y-4 sm:grid-cols-2">
+ {action.why.map((w) => (
+ <div key={w.label} className="min-w-0">
+ <dt className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {w.label}
+ </dt>
+ <dd className="mt-0.5 font-mono text-sm font-medium tabular-nums text-[var(--color-text-primary)] [overflow-wrap:anywhere]">
+ {w.value}
+ </dd>
+ {BASIS_NOTE[w.basis] ? (
+ <dd className="mt-0.5 text-xs text-[var(--color-text-tertiary)]">
+ {BASIS_NOTE[w.basis]}
+ </dd>
+ ) : null}
+ </div>
+ ))}
+ </dl>
+ </Section>
+ ) : null}
+
+ {action.details.length > 0 ? (
+ <Section
+ title={`Evidence (${action.details_total.toLocaleString()})`}
+ >
+ <EvidenceList
+ key={action.id}
+ details={action.details}
+ total={action.details_total}
+ fileHref={fileHref}
+ LinkComponent={LinkComponent}
+ />
+ </Section>
+ ) : null}
+
+ {action.details.length === 0 && (action.target.path || action.includes.length > 0) ? (
+ <Section title={action.includes.length > 0 ? "Where to start" : "Where"}>
+ {action.target.path && action.target.kind !== "decision" ? (
+ <p className="font-mono text-sm text-[var(--color-text-primary)] [overflow-wrap:anywhere]">
+ {action.target.path}
+ {action.target.symbol ? (
+ <span className="text-[var(--color-text-secondary)]">
+ {" :: "}
+ {action.target.symbol.split("::").pop()}
+ </span>
+ ) : null}
+ </p>
+ ) : null}
+ {action.includes.length > 0 ? (
+ <ol className="mt-1 space-y-1">
+ {action.includes.map((path) => {
+ const href = fileHref?.(path) ?? null;
+ return (
+ <li key={path} className="font-mono text-xs [overflow-wrap:anywhere]">
+ {href ? (
+ <Link href={href} className={linkCls}>
+ {path}
+ </Link>
+ ) : (
+ <span className="text-[var(--color-text-secondary)]">{path}</span>
+ )}
+ </li>
+ );
+ })}
+ </ol>
+ ) : null}
+ {action.evidence_total > action.includes.length && action.includes.length > 0 ? (
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ {`The worst ${action.includes.length} shown; the evidence link has the rest.`}
+ </p>
+ ) : null}
+ </Section>
+ ) : null}
+
+ <Section title="Done when">
+ <p className="text-sm text-[var(--color-text-secondary)]">{renderTitle(action.done_when)}</p>
+ {action.command ? (
+ <pre className="mt-2 overflow-x-auto rounded bg-[var(--color-bg-inset)] px-3 py-2 font-mono text-xs text-[var(--color-text-primary)]">
+ {action.command}
+ </pre>
+ ) : null}
+ <p className="mt-2 text-xs text-[var(--color-text-tertiary)]">
+ {`${EFFORT_LABEL[action.effort]} effort. `}
+ {action.confidence === "high"
+ ? "High confidence in the facts above."
+ : "Worth a check: the facts come from signals that can be wrong for this code."}
+ </p>
+ </Section>
+
+ {action.commands.length > 0 ? (
+ <Section title="Look closer">
+ <ul className="space-y-3">
+ {action.commands.map((c) => (
+ <li key={c.purpose} className="space-y-1">
+ <p className="text-sm text-[var(--color-text-secondary)]">{c.purpose}</p>
+ {c.cli ? (
+ <pre className="overflow-x-auto rounded bg-[var(--color-bg-inset)] px-3 py-1.5 font-mono text-xs text-[var(--color-text-primary)]">
+ {c.cli}
+ </pre>
+ ) : null}
+ {c.mcp ? (
+ <pre className="overflow-x-auto rounded bg-[var(--color-bg-inset)] px-3 py-1.5 font-mono text-xs text-[var(--color-text-secondary)]">
+ <span className="text-[var(--color-text-tertiary)]">MCP </span>
+ {c.mcp}
+ </pre>
+ ) : null}
+ </li>
+ ))}
+ </ul>
+ </Section>
+ ) : null}
+
+ <Section title="Hand it to an agent">
+ <div className="-mx-5">
+ <AiPromptBlock
+ bleed="px-5"
+ getPrompt={(flavor) =>
+ buildActionPrompt({ action, flavor, ...(repoName ? { repoName } : {}) })
+ }
+ />
+ </div>
+ </Section>
+ </div>
+
+ {onAnswer ? (
+ <div className="flex flex-wrap items-center gap-2 border-t border-[var(--color-border-default)] bg-[var(--color-bg-elevated)] px-5 py-3">
+ {(
+ [
+ ["done", "Mark done", Check, "Marked done. It returns if the facts change."],
+ ["snoozed", "Snooze 14 days", BellOff, "Snoozed for 14 days"],
+ ["dismissed", "Dismiss", X, "Dismissed. It returns if the facts change."],
+ ] as const
+ ).map(([state, label, Icon, message]) => (
+ <button
+ key={state}
+ type="button"
+ onClick={() => {
+ onAnswer(state, message);
+ onClose();
+ }}
+ className="inline-flex items-center gap-1.5 rounded-md border border-[var(--color-border-default)] px-2.5 py-1.5 text-xs font-medium text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-surface)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <Icon className="h-3.5 w-3.5" aria-hidden="true" />
+ {label}
+ </button>
+ ))}
+ </div>
+ ) : null}
+ </div>
+ ) : null}
+ </AdaptivePanel>
+ );
+}
+
+/** Rows shown before "Show all"; the payload carries up to 40. */
+const EVIDENCE_PREVIEW = 8;
+
+const SEVERITIES = new Set(["critical", "high", "medium", "low"]);
+
+function EvidenceList({
+ details,
+ total,
+ fileHref,
+ LinkComponent,
+}: {
+ details: ActionDetail[];
+ total: number;
+ fileHref?: ((path: string) => string | null) | undefined;
+ LinkComponent?: ElementType | undefined;
+}) {
+ const [all, setAll] = useState(false);
+ const Link = LinkComponent ?? "a";
+ const shown = all ? details : details.slice(0, EVIDENCE_PREVIEW);
+ return (
+ <div className="space-y-2">
+ <ul className="divide-y divide-[var(--color-border-default)]">
+ {shown.map((d, i) => {
+ const href = fileHref?.(d.path) ?? null;
+ const where = `${d.path}${d.line ? `:${d.line}` : ""}`;
+ return (
+ <li key={`${d.path}:${d.line ?? ""}:${d.symbol ?? ""}:${d.marker ?? ""}:${i}`} className="space-y-0.5 py-2">
+ <div className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-0.5">
+ {d.severity && SEVERITIES.has(d.severity) ? (
+ <SeverityMark severity={d.severity as Severity} compact />
+ ) : null}
+ {href ? (
+ <Link
+ href={href}
+ className="min-w-0 rounded font-mono text-xs text-[var(--color-accent-primary)] [overflow-wrap:anywhere] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {where}
+ </Link>
+ ) : (
+ <span className="min-w-0 font-mono text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">
+ {where}
+ </span>
+ )}
+ {d.symbol ? (
+ <code className="font-mono text-xs text-[var(--color-text-primary)]">
+ {d.symbol.split("::").pop()}
+ </code>
+ ) : null}
+ {d.marker ? (
+ <span className="text-xs text-[var(--color-text-secondary)]">{biomarkerLabel(d.marker)}</span>
+ ) : null}
+ </div>
+ {d.reason ? (
+ <p className="text-xs text-[var(--color-text-tertiary)] [overflow-wrap:anywhere]">{d.reason}</p>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ {details.length > EVIDENCE_PREVIEW || total > details.length ? (
+ <p className="flex flex-wrap items-baseline gap-x-3 text-xs text-[var(--color-text-tertiary)]">
+ {details.length > EVIDENCE_PREVIEW ? (
+ <button
+ type="button"
+ onClick={() => setAll((a) => !a)}
+ className="rounded text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {all ? "Show fewer" : `Show all ${details.length.toLocaleString()}`}
+ </button>
+ ) : null}
+ {total > details.length ? (
+ <span>{`${(total - details.length).toLocaleString()} more; "Look closer" below lists them.`}</span>
+ ) : null}
+ </p>
+ ) : null}
+ </div>
+ );
+}
diff --git a/packages/ui/src/overview/action-href.ts b/packages/ui/src/overview/action-href.ts
new file mode 100644
index 000000000..3a2270f8b
--- /dev/null
+++ b/packages/ui/src/overview/action-href.ts
@@ -0,0 +1,42 @@
+import type { NextAction } from "@repowise-dev/types/actions";
+
+import { attentionSourceHref } from "../dashboard/attention-href";
+import { fileEntityPath } from "../shared/entity/routes";
+
+/**
+ * Where an action's evidence lives, relative to the repo link prefix.
+ *
+ * A plain module, not beside the client component that renders the rows, so a
+ * server page can call it too (see the note on `getDefaultHref`).
+ */
+export function actionHref(action: NextAction, prefix: string): string {
+ const { path } = action.target;
+ switch (action.surface) {
+ case "file":
+ return path ? fileEntityPath(prefix, path) : `${prefix}/code-health?tab=findings`;
+ case "findings":
+ return action.target.kind === "file" || action.target.kind === "symbol"
+ ? fileEntityPath(prefix, path)
+ : `${prefix}/code-health?tab=findings`;
+ case "performance":
+ return action.evidence_ids[0]
+ ? `${prefix}/code-health?tab=performance&opportunity=${encodeURIComponent(action.evidence_ids[0])}`
+ : `${prefix}/code-health?tab=performance`;
+ case "coverage":
+ return `${prefix}/code-health?tab=coverage`;
+ case "commits":
+ return `${prefix}/commits`;
+ case "decisions":
+ return action.target.kind === "decision" && path
+ ? `${prefix}/decisions/${encodeURIComponent(path)}`
+ : `${prefix}/decisions`;
+ case "security":
+ return attentionSourceHref("security", prefix);
+ case "doc_drift":
+ return attentionSourceHref("doc_drift", prefix);
+ case "dead_code":
+ return attentionSourceHref("dead_code", prefix);
+ default:
+ return prefix;
+ }
+}
diff --git a/packages/ui/src/overview/index.ts b/packages/ui/src/overview/index.ts
index eb72bab34..5eb116aaa 100644
--- a/packages/ui/src/overview/index.ts
+++ b/packages/ui/src/overview/index.ts
@@ -40,6 +40,9 @@ export { AttentionSources } from "./attention-sources";
export type { AttentionRowItem } from "./attention-rows";
export { HotspotTable } from "./hotspot-table";
+export { actionHref } from "./action-href";
+export { NextActions, actionsStatus, renderActionTitle } from "./next-actions";
+export type { NextActionsProps } from "./next-actions";
export { ExploreList } from "./explore-list";
export type { ExploreEntry } from "./explore-list";
export { LanguageBar } from "./language-bar";
diff --git a/packages/ui/src/overview/next-actions.tsx b/packages/ui/src/overview/next-actions.tsx
new file mode 100644
index 000000000..4737aa18c
--- /dev/null
+++ b/packages/ui/src/overview/next-actions.tsx
@@ -0,0 +1,384 @@
+"use client";
+
+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,
+} from "@repowise-dev/types/actions";
+
+import { SeverityMark } from "../health/severity-mark";
+import { CLICKABLE_ROW_CLS, clickableRowProps } from "../shared/responsive-table";
+import { RowOverflow } from "../shared/row-overflow";
+import { Segmented } from "../shared/segmented";
+import { ActionDrawer } from "./action-drawer";
+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",
+};
+
+const EFFORT_LABEL: Record<NextAction["effort"], string> = {
+ S: "Small",
+ M: "Medium",
+ L: "Large",
+};
+
+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. */
+ onSetState?: (action: NextAction, state: ActionStateValue | null) => Promise<void>;
+ repoName?: string | undefined;
+ LinkComponent?: ElementType | undefined;
+}
+
+/** Split a title on backticks so paths and symbols set in mono. */
+export function renderActionTitle(title: string): ReactNode {
+ return title.split("`").map((part, i) =>
+ i % 2 === 1 ? (
+ <code key={i} className="font-mono text-[0.85em] [overflow-wrap:anywhere]">
+ {part}
+ </code>
+ ) : (
+ <Fragment key={i}>{part}</Fragment>
+ ),
+ );
+}
+
+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,
+ fileHref,
+ onSetState,
+ repoName,
+ LinkComponent,
+}: 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;
+ 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());
+ const [opened, setOpened] = useState<NextAction | null>(null);
+
+ const rows = useMemo(
+ () => (data ? data.horizons[horizon].actions.filter((a) => !answered.has(a.id)) : []),
+ [data, horizon, answered],
+ );
+ if (!data) return null;
+
+ const h = data.horizons[horizon];
+ const shown = expanded ? rows : rows.slice(0, PREVIEW);
+ const total = h.total - (h.actions.length - rows.length);
+ const unavailable = Object.keys(data.unavailable);
+
+ const answer = (action: NextAction, state: ActionStateValue, message: string) => {
+ if (!onSetState) return;
+ setAnswered((s) => new Set(s).add(action.id));
+ const restore = () =>
+ setAnswered((s) => {
+ const next = new Set(s);
+ next.delete(action.id);
+ return next;
+ });
+ onSetState(action, state).then(
+ () =>
+ toast.success(message, {
+ action: {
+ label: "Undo",
+ onClick: () => {
+ restore();
+ void onSetState(action, null).catch(() => toast.error("Could not undo"));
+ },
+ },
+ }),
+ () => {
+ restore();
+ toast.error("Could not save that; the action is back in the list");
+ },
+ );
+ };
+
+
+ return (
+ <OverviewSection
+ title="Do next"
+ description={actionsStatus(data, horizon, answered)}
+ action={
+ <Segmented
+ label="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" },
+ ]}
+ onChange={(v) => {
+ setHorizon(v);
+ setExpanded(false);
+ }}
+ />
+ }
+ >
+ {shown.length === 0 && answered.size > 0 && h.actions.length > 0 ? (
+ <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>
+ ) : shown.length === 0 ? (
+ <EmptyActions data={data} />
+ ) : (
+ <div className="flex flex-col">
+ {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]}
+ </h3>
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
+ {items.map((action) => (
+ <ActionRow
+ key={action.id}
+ action={action}
+ selected={opened?.id === action.id}
+ onOpen={() => setOpened(action)}
+ onAnswer={onSetState ? (state, message) => answer(action, state, message) : undefined}
+ />
+ ))}
+ </ul>
+ </div>
+ ))}
+ </div>
+ )}
+
+ <div className="flex flex-wrap items-baseline gap-x-3 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ {rows.length > PREVIEW && (
+ <button
+ type="button"
+ onClick={() => setExpanded((e) => !e)}
+ className="rounded text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {expanded ? "Show fewer" : `Show all ${Math.min(rows.length, total).toLocaleString()}`}
+ </button>
+ )}
+ {total > rows.length && (
+ <span className="tabular-nums">
+ {`Listing ${rows.length.toLocaleString()} of ${total.toLocaleString()}.`}
+ </span>
+ )}
+ {h.hidden + (h.actions.length - rows.length) > 0 && (
+ <span className="tabular-nums">{`${plural(
+ h.hidden + (h.actions.length - rows.length),
+ "action",
+ )} answered (done, snoozed or dismissed).`}</span>
+ )}
+ {unavailable.length > 0 && (
+ <span>
+ {`Not checked: ${unavailable.join(", ").replace(/_/g, " ")}. Run `}
+ <code className="font-mono text-[0.85em]">repowise update</code>
+ {" to include them."}
+ </span>
+ )}
+ </div>
+
+ <ActionDrawer
+ action={opened}
+ onClose={() => setOpened(null)}
+ evidenceHref={opened ? hrefFor(opened) : null}
+ fileHref={fileHref}
+ onAnswer={
+ onSetState && opened
+ ? (state, message) => answer(opened, state, message)
+ : undefined
+ }
+ repoName={repoName}
+ LinkComponent={LinkComponent}
+ renderTitle={renderActionTitle}
+ />
+ </OverviewSection>
+ );
+}
+
+function groupByTier(actions: NextAction[]): [ActionTier, NextAction[]][] {
+ const out: [ActionTier, NextAction[]][] = [];
+ for (const a of actions) {
+ const last = out[out.length - 1];
+ if (last && last[0] === a.tier) last[1].push(a);
+ else out.push([a.tier, [a]]);
+ }
+ return out;
+}
+
+export function ActionRow({
+ action,
+ onOpen,
+ selected = false,
+ onAnswer,
+}: {
+ action: NextAction;
+ /** Open the action's drawer; the whole row is the trigger. */
+ onOpen: () => void;
+ selected?: boolean | undefined;
+ onAnswer?: ((state: ActionStateValue, message: string) => void) | undefined;
+}) {
+ const plainTitle = action.title.replace(/`/g, "");
+ const items = [
+ { label: "Open details", icon: PanelRight, onSelect: onOpen },
+ ...(onAnswer
+ ? [
+ {
+ label: "Mark done",
+ icon: Check,
+ onSelect: () => onAnswer("done", "Marked done. It returns if the facts change."),
+ },
+ {
+ label: "Snooze for 14 days",
+ icon: BellOff,
+ onSelect: () => onAnswer("snoozed", "Snoozed for 14 days"),
+ },
+ {
+ label: "Dismiss",
+ icon: X,
+ onSelect: () => onAnswer("dismissed", "Dismissed. It returns if the facts change."),
+ },
+ ]
+ : []),
+ ];
+ return (
+ <li
+ aria-label={`Open ${plainTitle}`}
+ aria-current={selected ? "true" : undefined}
+ className={`${CLICKABLE_ROW_CLS} group flex items-start gap-3 px-1 py-3.5 sm:gap-4 ${
+ selected ? "bg-[var(--color-bg-elevated)]" : "hover:bg-[var(--color-bg-elevated)]"
+ }`}
+ {...clickableRowProps(onOpen)}
+ >
+ <div className="min-w-0 flex-1">
+ <div className="flex min-w-0 flex-wrap items-baseline gap-x-2 gap-y-1">
+ {action.tier === "act_now" && (
+ <SeverityMark severity={action.severity} className="translate-y-[-1px]" />
+ )}
+ <p className="min-w-0 text-[15px] font-semibold leading-snug text-[var(--color-text-primary)] [text-wrap:pretty] group-hover:text-[var(--color-accent-primary)]">
+ {renderActionTitle(action.title)}
+ </p>
+ </div>
+ <p className="mt-1 max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)] [text-wrap:pretty]">
+ {renderActionTitle(action.impact)}
+ </p>
+ <dl className="mt-1.5 flex flex-wrap gap-x-4 gap-y-1 text-xs text-[var(--color-text-tertiary)]">
+ {action.why.map((w) => (
+ <div key={w.label} className="flex min-w-0 items-baseline gap-1.5">
+ <dt>{w.label}</dt>
+ <dd
+ className={`min-w-0 font-mono tabular-nums [overflow-wrap:anywhere] ${
+ w.basis === "unknown"
+ ? "text-[var(--color-text-tertiary)]"
+ : "text-[var(--color-text-secondary)]"
+ }`}
+ >
+ {w.value}
+ {w.basis === "inferred" && (
+ <span className="ml-1 font-sans text-[var(--color-text-tertiary)]">(inferred)</span>
+ )}
+ </dd>
+ </div>
+ ))}
+ </dl>
+ </div>
+ <div className="flex shrink-0 items-center gap-2">
+ <span className="text-xs text-[var(--color-text-tertiary)]">
+ <span className="hidden sm:inline">{`${EFFORT_LABEL[action.effort]} effort`}</span>
+ {action.confidence === "medium" && (
+ <>
+ <span className="hidden sm:inline">, </span>
+ <span>worth a check</span>
+ </>
+ )}
+ </span>
+ <RowOverflow label={`More for ${plainTitle}`} items={items} />
+ </div>
+ </li>
+ );
+}
+
+function EmptyActions({ data }: { data: ActionsResponse }) {
+ const checked = data.rules.filter((r) => r.status === "evaluated").length;
+ const skipped = data.rules.filter((r) => r.status === "not_applicable");
+ return (
+ <div className="flex flex-col gap-1 py-2 text-sm text-[var(--color-text-secondary)]">
+ <p>{`Repowise ran ${plural(checked, "check")} over this index and none of them produced work for this time frame.`}</p>
+ {skipped.length > 0 && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {skipped.map((r) => r.reason).join(" ")}
+ </p>
+ )}
+ </div>
+ );
+}
diff --git a/packages/ui/src/overview/overview-body.tsx b/packages/ui/src/overview/overview-body.tsx
index c6c2b82c8..f8e9056a1 100644
--- a/packages/ui/src/overview/overview-body.tsx
+++ b/packages/ui/src/overview/overview-body.tsx
@@ -27,8 +27,8 @@ import { OverviewSection, SectionLink } from "./section";
/** How many rows each list section shows before deferring to its own page. */
const ATTENTION_ROWS = 6;
-const HOTSPOT_ROWS = 5;
const DECISION_ROWS = 6;
+const HOTSPOT_ROWS = 5;
export interface OverviewBodySlots {
/** The identity header. Each host builds its own: OSS carries reindex
@@ -44,6 +44,11 @@ export interface OverviewBodySlots {
* routes to a chat page from Explore instead, and the section then does not
* render at all rather than rendering empty. */
ask?: React.ReactNode;
+ /** The "Do next" list, bound to the host's routes and write path. When
+ * present it leads the page and the per-detector areas fold into an
+ * inventory lower down; when absent (a host not yet serving actions) the
+ * areas keep their old place. */
+ actions?: React.ReactNode;
}
export interface OverviewBodyProps {
@@ -74,6 +79,10 @@ export interface OverviewBodyProps {
* directly under the health hero rather than fourth, because the page is
* mostly opened by someone who was here last week and wants the delta, not by
* a stranger who wants the tour.
+ *
+ * When the host supplies actions, "Do next" takes that place: a few things to
+ * do, each with its reason, instead of a count per detector. The per-detector
+ * areas stay reachable as a folded inventory further down.
*/
export function OverviewBody({
summary,
@@ -99,6 +108,41 @@ export function OverviewBody({
// nothing.
const attentionTotal = summary.attention_summary?.total ?? summary.attention.length;
const areas = summary.attention_summary?.areas ?? [];
+ const hasAttention = areas.length > 0 || summary.attention.length > 0;
+
+ const attention = (inventory: boolean) => (
+ <OverviewSection
+ title={inventory ? "Everything we found" : "Needs attention"}
+ description={
+ inventory
+ ? "Every detector's open count by area, each with its worst example. An inventory, not a to-do list: the actions above are the part worth doing."
+ : "Every detector, by area of work, each leading with the worst thing in it: code health and the test-quality biomarkers, security, refactoring, documentation drift, decision records, ownership, and dead code."
+ }
+ collapsible={inventory}
+ defaultOpen={!inventory}
+ hint={inventory ? `${formatNumber(attentionTotal)} open` : undefined}
+ // No section link: these span seven pages, so there is no single
+ // destination that holds "all of them", and a count linking to one
+ // of them would be a lie about where the rest live.
+ action={
+ <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
+ {formatNumber(attentionTotal)} open
+ </span>
+ }
+ >
+ {areas.length > 0 ? (
+ <AttentionAreas areas={areas} prefix={base} LinkComponent={LinkComponent} />
+ ) : (
+ // A server predating the area rollup still sends ranked items, and
+ // rendering those is strictly better than rendering nothing.
+ <AttentionRows
+ items={summary.attention.slice(0, ATTENTION_ROWS)}
+ hrefFor={(item) => getDefaultHref(item, base)}
+ LinkComponent={LinkComponent}
+ />
+ )}
+ </OverviewSection>
+ );
return (
<div className="mx-auto flex w-full max-w-[1280px] flex-col gap-6 p-[var(--page-pad)] sm:gap-8">
@@ -127,32 +171,7 @@ export function OverviewBody({
</div>
</div>
- {(areas.length > 0 || summary.attention.length > 0) && (
- <OverviewSection
- title="Needs attention"
- description="Every detector, by area of work, each leading with the worst thing in it: code health and the test-quality biomarkers, security, refactoring, documentation drift, decision records, ownership, and dead code."
- // No section link: these span seven pages, so there is no single
- // destination that holds "all of them", and a count linking to one
- // of them would be a lie about where the rest live.
- action={
- <span className="font-mono text-[11px] tabular-nums text-[var(--color-text-tertiary)]">
- {formatNumber(attentionTotal)} open
- </span>
- }
- >
- {areas.length > 0 ? (
- <AttentionAreas areas={areas} prefix={base} LinkComponent={LinkComponent} />
- ) : (
- // A server predating the area rollup still sends ranked items, and
- // rendering those is strictly better than rendering nothing.
- <AttentionRows
- items={summary.attention.slice(0, ATTENTION_ROWS)}
- hrefFor={(item) => getDefaultHref(item, base)}
- LinkComponent={LinkComponent}
- />
- )}
- </OverviewSection>
- )}
+ {slots.actions ?? (hasAttention && attention(false))}
<StatRibbon stats={ribbon} LinkComponent={LinkComponent} />
@@ -188,7 +207,11 @@ export function OverviewBody({
</div>
</OverviewSection>
- {summary.top_hotspots.length > 0 && (
+ {/* A host without actions keeps the hotspot table: with "Do next", its
+ files arrive as fragile-file and bug-fix concentration actions with
+ the reason attached, and a second "riskiest files" list would
+ disagree with Code Health's. */}
+ {!slots.actions && summary.top_hotspots.length > 0 && (
<OverviewSection
title="Where the risk concentrates"
description="Ranked by prior bug fixes and change frequency, mined from full git history rather than from the code alone."
@@ -206,6 +229,11 @@ export function OverviewBody({
</OverviewSection>
)}
+ {/* The areas, now as the inventory behind "Do next": every detector's
+ count and its worst example, folded because the list above already
+ says what to do. */}
+ {slots.actions && hasAttention && attention(true)}
+
{summary.languages.length > 0 && (
<OverviewSection
title="Composition"
diff --git a/packages/ui/src/shared/row-overflow.tsx b/packages/ui/src/shared/row-overflow.tsx
new file mode 100644
index 000000000..1899e2e63
--- /dev/null
+++ b/packages/ui/src/shared/row-overflow.tsx
@@ -0,0 +1,52 @@
+"use client";
+
+import { useState, type ComponentType } from "react";
+import { MoreHorizontal } from "lucide-react";
+
+import { Button } from "../ui/button";
+import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+
+export interface RowOverflowItem {
+ label: string;
+ icon: ComponentType<{ className?: string; "aria-hidden"?: boolean | "true" }>;
+ onSelect: () => void;
+}
+
+/**
+ * A row's secondary verbs behind one named button. The row itself carries the
+ * primary verb; everything here is a different kind of thing to do.
+ */
+export function RowOverflow({ label, items }: { label: string; items: RowOverflowItem[] }) {
+ const [open, setOpen] = useState(false);
+ return (
+ <Popover open={open} onOpenChange={setOpen}>
+ <PopoverTrigger asChild>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7 w-7 px-0 text-[var(--color-text-tertiary)]"
+ aria-label={label}
+ onClick={(event) => event.stopPropagation()}
+ >
+ <MoreHorizontal className="h-4 w-4" />
+ </Button>
+ </PopoverTrigger>
+ <PopoverContent align="end" className="w-60 p-1" onClick={(event) => event.stopPropagation()}>
+ {items.map(({ label: itemLabel, icon: Icon, onSelect }) => (
+ <button
+ key={itemLabel}
+ type="button"
+ onClick={() => {
+ setOpen(false);
+ onSelect();
+ }}
+ className="flex w-full items-center gap-2 rounded px-2 py-1.5 text-left text-sm text-[var(--color-text-secondary)] hover:bg-[var(--color-bg-elevated)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" aria-hidden="true" />
+ {itemLabel}
+ </button>
+ ))}
+ </PopoverContent>
+ </Popover>
+ );
+}
diff --git a/packages/ui/src/shared/segmented.tsx b/packages/ui/src/shared/segmented.tsx
new file mode 100644
index 000000000..d78efa842
--- /dev/null
+++ b/packages/ui/src/shared/segmented.tsx
@@ -0,0 +1,113 @@
+"use client";
+
+/**
+ * One axis, one control: a radiogroup of mutually exclusive options, with
+ * roving focus and arrow keys. Shared so every lens switch in the product
+ * behaves and reads the same way.
+ */
+
+import { useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
+
+export interface SegmentOption<T extends string> {
+ value: T;
+ label: string;
+ /** Figure after the label, e.g. a finding count. */
+ count?: string | undefined;
+ /** Set to disable the option; the reason is its tooltip and accessible description. */
+ disabledReason?: string | undefined;
+ hint?: string | undefined;
+}
+
+/**
+ * One axis, one control: a radiogroup of mutually exclusive options. A
+ * disabled option stays visible with its reason rather than vanishing, so the
+ * reader learns the lens exists and why it has nothing to show.
+ */
+export function Segmented<T extends string>({
+ label,
+ value,
+ options,
+ onChange,
+}: {
+ label: string;
+ value: T;
+ options: SegmentOption<T>[];
+ onChange: (value: T) => void;
+}) {
+ const refs = useRef<(HTMLButtonElement | null)[]>([]);
+ const [reason, setReason] = useState<string | null>(null);
+ // The roving tab stop: the active option, or the first enabled one when the
+ // active option is disabled, so the group never drops out of the tab order.
+ const activeIndex = options.findIndex((o) => o.value === value && !o.disabledReason);
+ const tabStop = activeIndex >= 0 ? activeIndex : Math.max(options.findIndex((o) => !o.disabledReason), 0);
+
+ // Arrows walk every option, disabled ones included, so a keyboard reader can
+ // reach a disabled lens and hear why; only enabled ones are selected.
+ const onKeyDown = (e: ReactKeyboardEvent) => {
+ const i = refs.current.findIndex((el) => el === document.activeElement);
+ const from = i >= 0 ? i : tabStop;
+ let next: number;
+ if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (from + 1) % options.length;
+ else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (from - 1 + options.length) % options.length;
+ else return;
+ e.preventDefault();
+ refs.current[next]?.focus();
+ const target = options[next];
+ if (target && !target.disabledReason) onChange(target.value);
+ };
+
+ return (
+ <div className="flex min-w-0 flex-col gap-1">
+ <div
+ role="radiogroup"
+ aria-label={label}
+ onKeyDown={onKeyDown}
+ className="inline-flex max-w-full flex-wrap self-start rounded-md border border-[var(--color-border-default)] p-0.5"
+ >
+ {options.map((o, i) => {
+ const active = o.value === value && !o.disabledReason;
+ const reasonId = o.disabledReason ? `seg-reason-${label}-${o.value}`.replace(/\s+/g, "-") : undefined;
+ const show = o.disabledReason ? () => setReason(o.disabledReason ?? null) : undefined;
+ return (
+ <button
+ key={o.value}
+ ref={(el) => {
+ refs.current[i] = el;
+ }}
+ type="button"
+ role="radio"
+ aria-checked={active}
+ aria-disabled={o.disabledReason ? true : undefined}
+ aria-describedby={reasonId}
+ tabIndex={i === tabStop ? 0 : -1}
+ title={o.disabledReason ?? o.hint}
+ onClick={() => (o.disabledReason ? show?.() : onChange(o.value))}
+ onMouseEnter={show}
+ onFocus={show}
+ onMouseLeave={o.disabledReason ? () => setReason(null) : undefined}
+ onBlur={o.disabledReason ? () => setReason(null) : undefined}
+ className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
+ active
+ ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
+ : o.disabledReason
+ ? "cursor-not-allowed font-medium text-[var(--color-text-tertiary)]"
+ : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
+ }`}
+ >
+ {o.label}
+ {o.count !== undefined && (
+ <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">{o.count}</span>
+ )}
+ {reasonId && (
+ <span id={reasonId} className="sr-only">
+ {o.disabledReason}
+ </span>
+ )}
+ </button>
+ );
+ })}
+ </div>
+ {reason && <p className="text-xs text-[var(--color-text-tertiary)]">{reason}</p>}
+ </div>
+ );
+}
diff --git a/packages/ui/src/workspace/system-map/system-map-filters.tsx b/packages/ui/src/workspace/system-map/system-map-filters.tsx
index 0d573db6b..387b4f8e0 100644
--- a/packages/ui/src/workspace/system-map/system-map-filters.tsx
+++ b/packages/ui/src/workspace/system-map/system-map-filters.tsx
@@ -7,117 +7,16 @@
* filter. Pure controlled components; state lives in the map.
*/
-import { useRef, useState, type KeyboardEvent as ReactKeyboardEvent } from "react";
import type { SystemEdgeKind } from "@repowise-dev/types";
+import { Segmented } from "../../shared/segmented";
import { EDGE_KIND_ORDER, SYSTEM_EDGE_KINDS } from "./edge-kinds";
+// Re-exported for the lens switch and existing imports; the control lives in shared.
+export { Segmented, type SegmentOption } from "../../shared/segmented";
+
export const MICRO_LABEL =
"font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]";
-export interface SegmentOption<T extends string> {
- value: T;
- label: string;
- /** Figure after the label, e.g. a finding count. */
- count?: string | undefined;
- /** Set to disable the option; the reason is its tooltip and accessible description. */
- disabledReason?: string | undefined;
- hint?: string | undefined;
-}
-
-/**
- * One axis, one control: a radiogroup of mutually exclusive options. A
- * disabled option stays visible with its reason rather than vanishing, so the
- * reader learns the lens exists and why it has nothing to show.
- */
-export function Segmented<T extends string>({
- label,
- value,
- options,
- onChange,
-}: {
- label: string;
- value: T;
- options: SegmentOption<T>[];
- onChange: (value: T) => void;
-}) {
- const refs = useRef<(HTMLButtonElement | null)[]>([]);
- const [reason, setReason] = useState<string | null>(null);
- // The roving tab stop: the active option, or the first enabled one when the
- // active option is disabled, so the group never drops out of the tab order.
- const activeIndex = options.findIndex((o) => o.value === value && !o.disabledReason);
- const tabStop = activeIndex >= 0 ? activeIndex : Math.max(options.findIndex((o) => !o.disabledReason), 0);
-
- // Arrows walk every option, disabled ones included, so a keyboard reader can
- // reach a disabled lens and hear why; only enabled ones are selected.
- const onKeyDown = (e: ReactKeyboardEvent) => {
- const i = refs.current.findIndex((el) => el === document.activeElement);
- const from = i >= 0 ? i : tabStop;
- let next: number;
- if (e.key === "ArrowRight" || e.key === "ArrowDown") next = (from + 1) % options.length;
- else if (e.key === "ArrowLeft" || e.key === "ArrowUp") next = (from - 1 + options.length) % options.length;
- else return;
- e.preventDefault();
- refs.current[next]?.focus();
- const target = options[next];
- if (target && !target.disabledReason) onChange(target.value);
- };
-
- return (
- <div className="flex min-w-0 flex-col gap-1">
- <div
- role="radiogroup"
- aria-label={label}
- onKeyDown={onKeyDown}
- className="inline-flex max-w-full flex-wrap self-start rounded-md border border-[var(--color-border-default)] p-0.5"
- >
- {options.map((o, i) => {
- const active = o.value === value && !o.disabledReason;
- const reasonId = o.disabledReason ? `sm-reason-${label}-${o.value}`.replace(/\s+/g, "-") : undefined;
- const show = o.disabledReason ? () => setReason(o.disabledReason ?? null) : undefined;
- return (
- <button
- key={o.value}
- ref={(el) => {
- refs.current[i] = el;
- }}
- type="button"
- role="radio"
- aria-checked={active}
- aria-disabled={o.disabledReason ? true : undefined}
- aria-describedby={reasonId}
- tabIndex={i === tabStop ? 0 : -1}
- title={o.disabledReason ?? o.hint}
- onClick={() => (o.disabledReason ? show?.() : onChange(o.value))}
- onMouseEnter={show}
- onFocus={show}
- onMouseLeave={o.disabledReason ? () => setReason(null) : undefined}
- onBlur={o.disabledReason ? () => setReason(null) : undefined}
- className={`inline-flex items-center gap-1.5 rounded px-2.5 py-1 text-xs transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)] ${
- active
- ? "bg-[var(--color-bg-elevated)] font-semibold text-[var(--color-text-primary)]"
- : o.disabledReason
- ? "cursor-not-allowed font-medium text-[var(--color-text-tertiary)]"
- : "font-medium text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)]"
- }`}
- >
- {o.label}
- {o.count !== undefined && (
- <span className="font-mono text-[10px] tabular-nums text-[var(--color-text-tertiary)]">{o.count}</span>
- )}
- {reasonId && (
- <span id={reasonId} className="sr-only">
- {o.disabledReason}
- </span>
- )}
- </button>
- );
- })}
- </div>
- {reason && <p className="text-xs text-[var(--color-text-tertiary)]">{reason}</p>}
- </div>
- );
-}
-
export interface SystemMapFiltersProps {
/** Edges per kind in the drawn shape (before the kind filter); only these kinds are offered. */
kindCounts: ReadonlyMap<SystemEdgeKind, number>;
diff --git a/packages/ui/src/workspace/workspace-next-actions.tsx b/packages/ui/src/workspace/workspace-next-actions.tsx
new file mode 100644
index 000000000..478e53956
--- /dev/null
+++ b/packages/ui/src/workspace/workspace-next-actions.tsx
@@ -0,0 +1,177 @@
+"use client";
+
+import { useState, type ElementType } from "react";
+import type {
+ ActionHorizonKey,
+ NextAction,
+ WorkspaceActionsResponse,
+ WorkspaceRepoActions,
+} from "@repowise-dev/types/actions";
+
+import { ActionDrawer } from "../overview/action-drawer";
+import { ActionRow, renderActionTitle } from "../overview/next-actions";
+import { OverviewSection } from "../overview/section";
+import { Segmented } from "../shared/segmented";
+
+export interface WorkspaceNextActionsProps {
+ data: WorkspaceActionsResponse;
+ /** Where one repository's action points, given that repository's id. */
+ hrefFor: (repoId: string, action: NextAction) => string | null;
+ /** The repository's own Overview, where its full list lives. */
+ repoHref: (repoId: string) => string;
+ /** A file's page in a given repository. */
+ fileHref?: ((repoId: string, path: string) => string | null) | undefined;
+ /** Where cross-repository contract changes are listed. */
+ contractsHref: string;
+ LinkComponent?: ElementType | undefined;
+}
+
+function work(repo: WorkspaceRepoActions, horizon: ActionHorizonKey): number {
+ return repo.horizons[horizon]?.total ?? 0;
+}
+
+function plural(n: number, noun: string): string {
+ return `${n.toLocaleString()} ${noun}${n === 1 ? "" : "s"}`;
+}
+
+/**
+ * "Do next" for the whole workspace: the cross-repository actions first, then
+ * each repository's lead actions under its name, most urgent repository first.
+ * Each repository's rows are the same actions its own Overview shows, trimmed
+ * to the two that lead, with a link to the rest.
+ */
+export function WorkspaceNextActions({
+ data,
+ hrefFor,
+ repoHref,
+ fileHref,
+ contractsHref,
+ LinkComponent,
+}: WorkspaceNextActionsProps) {
+ const [horizon, setHorizon] = useState<ActionHorizonKey>(
+ data.repos.some((r) => work(r, "week") > 0) ? "week" : "quarter",
+ );
+ const [opened, setOpened] = useState<{ action: NextAction; repo: string; repoId: string } | null>(
+ null,
+ );
+ const Link = LinkComponent ?? "a";
+
+ const available = data.repos.filter((r) => r.status === "available");
+ const withWork = available
+ .filter((r) => work(r, horizon) > 0)
+ .sort(
+ (a, b) =>
+ (b.horizons[horizon]?.by_tier.act_now ?? 0) - (a.horizons[horizon]?.by_tier.act_now ?? 0) ||
+ work(b, horizon) - work(a, horizon),
+ );
+ const total = withWork.reduce((n, r) => n + work(r, horizon), 0) + data.cross_repo.length;
+ const unavailable = data.repos.filter((r) => r.status === "unavailable");
+ const window = horizon === "week" ? "this week" : "this quarter";
+
+ const status =
+ total === 0
+ ? `Nothing stands out ${window} in ${available.length.toLocaleString()} ${
+ available.length === 1 ? "repository" : "repositories"
+ }.`
+ : `${plural(total, "thing")} worth doing ${window}, across ${plural(
+ withWork.length + (data.cross_repo.length ? 1 : 0),
+ "place",
+ )}.`;
+
+ return (
+ <OverviewSection
+ title="Do next"
+ description={status}
+ action={
+ <Segmented
+ label="Time frame"
+ value={horizon}
+ options={[
+ { value: "week", label: "This week", hint: "What each repository's last 7 days of commits changed" },
+ { value: "quarter", label: "This quarter", hint: "What 90 days say is worth planning" },
+ ]}
+ onChange={setHorizon}
+ />
+ }
+ >
+ <div className="flex flex-col gap-5">
+ {data.cross_repo.length > 0 && (
+ <div className="flex flex-col">
+ <h3 className="pb-1 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ Across repositories
+ </h3>
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
+ {data.cross_repo.map((c) => (
+ <li key={c.kind} className="py-3.5">
+ <p className="text-[15px] font-semibold leading-snug text-[var(--color-text-primary)]">
+ <Link
+ href={contractsHref}
+ className="rounded hover:text-[var(--color-accent-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {renderActionTitle(c.title)}
+ </Link>
+ </p>
+ <p className="mt-1 max-w-[72ch] text-xs leading-relaxed text-[var(--color-text-secondary)]">
+ {c.impact}
+ </p>
+ </li>
+ ))}
+ </ul>
+ </div>
+ )}
+
+ {withWork.map((repo) => {
+ const h = repo.horizons[horizon];
+ const repoId = repo.repo_id!;
+ return (
+ <div key={repo.alias} className="flex flex-col">
+ <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1 pb-1">
+ <h3 className="font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">
+ {repo.alias}
+ </h3>
+ <Link
+ href={repoHref(repoId)}
+ className="rounded text-xs text-[var(--color-accent-primary)] hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]"
+ >
+ {`All ${work(repo, horizon).toLocaleString()} in ${repo.alias}`}
+ </Link>
+ </div>
+ <ul className="flex flex-col divide-y divide-[var(--color-border-default)]">
+ {(h?.actions ?? []).map((action) => (
+ <ActionRow
+ key={action.id}
+ action={action}
+ selected={opened?.action.id === action.id && opened.repoId === repoId}
+ onOpen={() => setOpened({ action, repo: repo.alias, repoId })}
+ />
+ ))}
+ </ul>
+ </div>
+ );
+ })}
+
+ {total === 0 && (
+ <p className="text-sm text-[var(--color-text-secondary)]">
+ Each repository's own Overview lists what it checked and why nothing came up.
+ </p>
+ )}
+
+ {unavailable.length > 0 && (
+ <p className="text-xs text-[var(--color-text-tertiary)]">
+ {`Not included: ${unavailable.map((r) => `${r.alias} (${r.reason.replace(/\.$/, "").toLowerCase()})`).join(", ")}.`}
+ </p>
+ )}
+ </div>
+
+ <ActionDrawer
+ action={opened?.action ?? null}
+ onClose={() => setOpened(null)}
+ evidenceHref={opened ? hrefFor(opened.repoId, opened.action) : null}
+ fileHref={opened && fileHref ? (path) => fileHref(opened.repoId, path) : undefined}
+ repoName={opened?.repo}
+ LinkComponent={LinkComponent}
+ renderTitle={renderActionTitle}
+ />
+ </OverviewSection>
+ );
+}
diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.ts
index 2c2d841b4..5080705e8 100644
--- a/packages/ui/vitest.config.ts
+++ b/packages/ui/vitest.config.ts
@@ -39,6 +39,7 @@ export default defineConfig({
"@repowise-dev/types/owners": path.resolve(__dirname, "../types/src/owners.ts"),
"@repowise-dev/types/modules": path.resolve(__dirname, "../types/src/modules.ts"),
"@repowise-dev/types/overview": path.resolve(__dirname, "../types/src/overview.ts"),
+ "@repowise-dev/types/actions": path.resolve(__dirname, "../types/src/actions.ts"),
"@repowise-dev/types/files": path.resolve(__dirname, "../types/src/files.ts"),
"@repowise-dev/types/external-systems": path.resolve(
__dirname,
diff --git a/packages/web/src/app/repos/[id]/overview/page.tsx b/packages/web/src/app/repos/[id]/overview/page.tsx
index 2979f398a..7be8fd356 100644
--- a/packages/web/src/app/repos/[id]/overview/page.tsx
+++ b/packages/web/src/app/repos/[id]/overview/page.tsx
@@ -2,11 +2,13 @@ import type { Metadata } from "next";
import { notFound } from "next/navigation";
import Link from "next/link";
import { getOverviewSummary } from "@/lib/api/overview";
+import { getActions } from "@/lib/api/actions";
import { getProviders } from "@/lib/api/providers";
import { getCommitsPage } from "@/lib/api/git";
import { FirstIndexExperience } from "@/components/repos/first-index-experience";
import { QuickActionsWrapper } from "@/components/dashboard/quick-actions-wrapper";
import { AskAnythingRow } from "@/components/overview/ask-anything-row";
+import { NextActionsPanel } from "@/components/overview/next-actions-panel";
import {
OverviewBody,
RepoIdentityHeader,
@@ -54,10 +56,11 @@ export default async function OverviewPage({ params }: Props) {
// renders client-side: this is a static read, so a hydration boundary would
// only buy a slower first paint and worse indexability. The commits call
// replaces a client-side SWR fetch that used to waterfall in after paint.
- const [summary, providers, commitsPage] = await Promise.all([
+ const [summary, providers, commitsPage, actions] = await Promise.all([
safeFetch(() => getOverviewSummary(id)),
safeFetch(() => getProviders()),
safeFetch(() => getCommitsPage(id, { sort: "date", limit: COMMIT_LIMIT })),
+ safeFetch(() => getActions(id)),
]);
if (!summary) notFound();
@@ -132,7 +135,15 @@ export default async function OverviewPage({ params }: Props) {
commits={commitsPage?.items ?? []}
totalNloc={totalNloc}
LinkComponent={Link}
- slots={{ header, ask: <AskAnythingRow repoId={id} /> }}
+ slots={{
+ header,
+ ask: <AskAnythingRow repoId={id} />,
+ // A server that predates actions returns 404; the page then keeps the
+ // attention areas in their old place rather than showing an empty list.
+ actions: actions ? (
+ <NextActionsPanel repoId={id} repoName={repo.name} data={actions} />
+ ) : undefined,
+ }}
/>
);
}
diff --git a/packages/web/src/app/workspace/page.tsx b/packages/web/src/app/workspace/page.tsx
index d2246bcba..c1c5262c5 100644
--- a/packages/web/src/app/workspace/page.tsx
+++ b/packages/web/src/app/workspace/page.tsx
@@ -20,7 +20,9 @@ import { CoChangeTable } from "@repowise-dev/ui/workspace/co-change-table";
import { ContractTypeBadge } from "@repowise-dev/ui/workspace/contract-type-badge";
import { formatNumber } from "@repowise-dev/ui/lib/format";
import { getWorkspace, getWorkspaceCoChanges } from "@/lib/api/workspace";
+import { getWorkspaceActions } from "@/lib/api/actions";
import { RemoveWorkspaceRepoButton, SyncButton } from "./sync-buttons";
+import { WorkspaceNextActionsPanel } from "./workspace-next-actions-panel";
export const metadata: Metadata = { title: "Workspace" };
@@ -52,13 +54,16 @@ export default async function WorkspaceDashboardPage() {
// One wave, both on the server. The graph section that used to sit here was
// a client component fetching after mount, which waterfalled a second
// per-repo sqlite sweep in behind the paint.
- const [ws, cc] = await Promise.allSettled([
+ const [ws, cc, wa] = await Promise.allSettled([
getWorkspace(),
getWorkspaceCoChanges({ limit: COCHANGE_PREVIEW }),
+ getWorkspaceActions(),
]);
const workspace = ws.status === "fulfilled" ? ws.value : null;
const coChanges = cc.status === "fulfilled" ? cc.value : null;
+ // A server that predates actions 404s here; the page then reads as before.
+ const actions = wa.status === "fulfilled" ? wa.value : null;
const repos = workspace?.repos ?? [];
const crossRepo = workspace?.cross_repo_summary ?? null;
const contracts = workspace?.contract_summary ?? null;
@@ -168,6 +173,8 @@ export default async function WorkspaceDashboardPage() {
<StatRibbon stats={ribbon} LinkComponent={Link} />
+ {actions && <WorkspaceNextActionsPanel data={actions} />}
+
<OverviewSection
title="Repositories"
description="Ordered by what needs attention first — never indexed, then missing on disk, then by health score — rather than by name."
diff --git a/packages/web/src/app/workspace/workspace-next-actions-panel.tsx b/packages/web/src/app/workspace/workspace-next-actions-panel.tsx
new file mode 100644
index 000000000..d5860c0c1
--- /dev/null
+++ b/packages/web/src/app/workspace/workspace-next-actions-panel.tsx
@@ -0,0 +1,21 @@
+"use client";
+
+import Link from "next/link";
+import type { WorkspaceActionsResponse } from "@repowise-dev/types/actions";
+import { actionHref } from "@repowise-dev/ui/overview";
+import { fileEntityPath } from "@repowise-dev/ui/shared/entity";
+import { WorkspaceNextActions } from "@repowise-dev/ui/workspace/workspace-next-actions";
+
+/** The local app's routes for the workspace "Do next"; the list is shared. */
+export function WorkspaceNextActionsPanel({ data }: { data: WorkspaceActionsResponse }) {
+ return (
+ <WorkspaceNextActions
+ data={data}
+ LinkComponent={Link}
+ hrefFor={(repoId, action) => actionHref(action, `/repos/${repoId}`)}
+ repoHref={(repoId) => `/repos/${repoId}/overview`}
+ fileHref={(repoId, path) => fileEntityPath(`/repos/${repoId}`, path)}
+ contractsHref="/workspace/contracts"
+ />
+ );
+}
diff --git a/packages/web/src/components/overview/next-actions-panel.tsx b/packages/web/src/components/overview/next-actions-panel.tsx
new file mode 100644
index 000000000..c9b8e5f3b
--- /dev/null
+++ b/packages/web/src/components/overview/next-actions-panel.tsx
@@ -0,0 +1,39 @@
+"use client";
+
+import Link from "next/link";
+import type { ActionsResponse } from "@repowise-dev/types/actions";
+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 { 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,
+ repoName,
+ data,
+}: {
+ repoId: string;
+ repoName: string;
+ data: ActionsResponse;
+}) {
+ const base = `/repos/${repoId}`;
+ return (
+ <NextActions
+ data={data}
+ repoName={repoName}
+ LinkComponent={Link}
+ hrefFor={(action) => actionHref(action, base)}
+ fileHref={(path) => fileEntityPath(base, path)}
+ onSetState={async (action, state) => {
+ await setActionState(repoId, action.id, {
+ state,
+ fingerprint: action.fingerprint,
+ });
+ }}
+ />
+ );
+}
diff --git a/packages/web/src/lib/api/actions.ts b/packages/web/src/lib/api/actions.ts
new file mode 100644
index 000000000..36b3ed132
--- /dev/null
+++ b/packages/web/src/lib/api/actions.ts
@@ -0,0 +1,3 @@
+import "./client";
+
+export * from "@repowise-dev/api-client/actions";
diff --git a/tests/unit/analysis/test_actions_rules.py b/tests/unit/analysis/test_actions_rules.py
new file mode 100644
index 000000000..41d7b91de
--- /dev/null
+++ b/tests/unit/analysis/test_actions_rules.py
@@ -0,0 +1,611 @@
+"""Next-action rules over synthetic facts: when each fires, when it stays quiet,
+and what the engine does with the result. No store; the loader has its own
+tests.
+"""
+
+from __future__ import annotations
+
+from dataclasses import replace
+from datetime import datetime, timedelta
+
+from repowise.core.analysis.actions import ActionStateRecord, RepoFacts, compose_actions
+from repowise.core.analysis.actions.context import build_context
+from repowise.core.analysis.actions.engine import KEEP_PER_HORIZON
+from repowise.core.analysis.actions.facts import (
+ CoverageState,
+ DeadFacts,
+ DecisionFacts,
+ DriftFacts,
+ FileFacts,
+ LeadFinding,
+ PerfFacts,
+ RecentFinding,
+ SecretFacts,
+)
+from repowise.core.analysis.actions.model import TIER_RANK, Action
+from repowise.core.analysis.actions.rules import code, hygiene, signal
+
+ANCHOR = datetime(2026, 9, 28, 12, 0)
+NOW = ANCHOR + timedelta(days=1)
+
+
+def _file(path: str, **kw) -> FileFacts:
+ base = dict(
+ path=path,
+ is_test=False,
+ score=5.0,
+ max_ccn=10,
+ nloc=200,
+ line_coverage_pct=None,
+ commits_90d=10,
+ last_commit_at=ANCHOR - timedelta(days=30),
+ bug_magnet=True,
+ fix_commits_90d=5,
+ bus_factor=1,
+ owner_key=None,
+ owner_name=None,
+ owner_pct=None,
+ dependents=None,
+ )
+ base.update(kw)
+ return FileFacts(**base)
+
+
+def _facts(files: list[FileFacts] = (), **kw) -> RepoFacts:
+ kw.setdefault("fix_commits_90d", sum(f.fix_commits_90d for f in files))
+ return RepoFacts(anchor=kw.pop("anchor", ANCHOR), files={f.path: f for f in files}, **kw)
+
+
+def _run(rule, facts: RepoFacts, **ctx_overrides):
+ ctx = build_context(facts)
+ if ctx_overrides:
+ ctx = replace(ctx, **ctx_overrides)
+ return rule(facts, ctx)
+
+
+def _text(a: Action) -> str:
+ return " ".join([a.title, a.impact, a.done_when, *(w.value for w in a.why)]).lower()
+
+
+# ---------------------------------------------------------------------------
+# fragile_file
+# ---------------------------------------------------------------------------
+
+
+def test_fragile_without_coverage_says_add_tests_and_basis_unknown() -> None:
+ out = _run(code.fragile_file, _facts([_file("src/a.py")]))
+ (a,) = out.actions
+ assert a.title.startswith("Add tests around `src/a.py`")
+ cov = next(w for w in a.why if w.label == "line coverage")
+ assert cov.basis == "unknown"
+ assert a.confidence == "medium"
+ # Unknown is not zero: nothing may call it untested.
+ assert "untested" not in _text(a)
+
+
+def test_fragile_below_80_says_raise_coverage() -> None:
+ (a,) = _run(code.fragile_file, _facts([_file("src/a.py", line_coverage_pct=62.0)])).actions
+ assert a.title == "Raise test coverage on `src/a.py` from 62%"
+ assert next(w for w in a.why if w.label == "line coverage").basis == "measured"
+
+
+def test_fragile_covered_with_lead_says_simplify() -> None:
+ lead = LeadFinding("complex_method", "high", "build", 12, "ccn 20")
+ f = _file("src/a.py", line_coverage_pct=91.0, lead=lead)
+ (a,) = _run(code.fragile_file, _facts([f])).actions
+ assert a.title.startswith("Simplify `build` in `src/a.py`")
+ assert a.target_symbol == "build"
+ assert a.marker == "complex_method"
+
+
+def test_fragile_covered_without_lead_is_silent() -> None:
+ f = _file("src/a.py", line_coverage_pct=91.0)
+ assert _run(code.fragile_file, _facts([f])).actions == ()
+
+
+def test_fragile_skips_declaration_only_files() -> None:
+ f = _file("src/types.ts", max_ccn=1)
+ out = _run(code.fragile_file, _facts([f]))
+ assert out.status == "evaluated"
+ assert out.actions == ()
+
+
+def test_fragile_respects_repo_fix_threshold() -> None:
+ # Two files with fixes: the 95th percentile is the larger count, so the
+ # file with 3 fixes sits below the bar the repository sets.
+ files = [_file("src/hot.py", fix_commits_90d=10), _file("src/warm.py", fix_commits_90d=3)]
+ out = _run(code.fragile_file, _facts(files))
+ assert [a.target_path for a in out.actions] == ["src/hot.py"]
+
+
+def test_fragile_not_applicable_without_fixes() -> None:
+ out = _run(code.fragile_file, _facts([_file("src/a.py", fix_commits_90d=0)]))
+ assert out.status == "not_applicable"
+
+
+def test_fragile_week_horizon_only_for_top_five_touched_this_week() -> None:
+ this_week = ANCHOR - timedelta(days=1)
+ files = [_file(f"src/f{n}.py", fix_commits_90d=n, last_commit_at=this_week) for n in range(3, 10)]
+ files.append(_file("src/quiet.py", fix_commits_90d=20, last_commit_at=ANCHOR - timedelta(days=30)))
+ out = _run(code.fragile_file, _facts(files), busy_threshold=5, fix_threshold=3)
+ by_path = {a.target_path: a.horizons for a in out.actions}
+ assert {p for p, h in by_path.items() if "week" in h} == {f"src/f{n}.py" for n in range(5, 10)}
+ assert by_path["src/f3.py"] == ("quarter",)
+ assert by_path["src/f4.py"] == ("quarter",)
+ assert by_path["src/quiet.py"] == ("quarter",)
+
+
+# ---------------------------------------------------------------------------
+# fresh_regressions
+# ---------------------------------------------------------------------------
+
+
+def _recent(path: str, symbol: str | None = "fn", severity: str = "high", sha: str = "c1") -> RecentFinding:
+ return RecentFinding(
+ sha=sha,
+ subject="feat: thing",
+ committed_at=ANCHOR - timedelta(days=1),
+ file_path=path,
+ symbol=symbol,
+ biomarker="complex_method",
+ severity=severity,
+ change_kind="introduced",
+ line=10,
+ )
+
+
+def test_regressions_up_to_three_files_are_per_file() -> None:
+ found = (_recent("src/a.py", "build"), _recent("src/b.py", "x"), _recent("src/b.py", "y"))
+ out = _run(code.fresh_regressions, _facts(recent_findings=found))
+ assert {a.target_path for a in out.actions} == {"src/a.py", "src/b.py"}
+ a = next(a for a in out.actions if a.target_path == "src/a.py")
+ assert a.tier == "act_now"
+ assert a.horizons == ("week",)
+ assert a.target_kind == "symbol"
+ assert a.title == "Simplify `build` in `src/a.py` while the change is fresh"
+
+
+def test_regressions_over_three_files_roll_up() -> None:
+ found = (
+ *(_recent(f"src/f{i}.py") for i in range(4)),
+ _recent("src/worst.py", severity="critical"),
+ )
+ out = _run(code.fresh_regressions, _facts(recent_findings=found))
+ (a,) = out.actions
+ assert a.target_kind == "repo"
+ assert a.severity == "critical"
+ assert a.includes[0] == "src/worst.py"
+ assert set(a.includes) == {"src/worst.py", *(f"src/f{i}.py" for i in range(4))}
+
+
+def test_regressions_unavailable_store() -> None:
+ out = _run(code.fresh_regressions, _facts(unavailable={"commit_health": "missing"}))
+ assert out.status == "unavailable"
+ assert out.reason == "missing"
+
+
+# ---------------------------------------------------------------------------
+# fix_concentration
+# ---------------------------------------------------------------------------
+
+
+def _concentration_facts() -> RepoFacts:
+ """10 of 25 fixes in 4 of 100 files under `pkg/cli/update/` (lift 10); its
+ ancestor `pkg/cli/` also clears the bar (lift 5.2) but is broader."""
+ update_shas = [
+ {"u0", "u1", "u2", "u3"},
+ {"u3", "u4", "u5", "u6"},
+ {"u6", "u7", "u8", "u9"},
+ {"u0", "u2", "u5", "u9"},
+ ]
+ files: list[FileFacts] = []
+ fix_shas: dict[str, frozenset[str]] = {}
+ for i, shas in enumerate(update_shas):
+ p = f"pkg/cli/update/a{i}.py"
+ files.append(_file(p, fix_commits_90d=len(shas)))
+ fix_shas[p] = frozenset(shas)
+ for i in range(6):
+ p = f"pkg/cli/misc/b{i}.py"
+ fixes = 3 if i < 2 else 0
+ files.append(_file(p, fix_commits_90d=fixes, bug_magnet=False))
+ if fixes:
+ fix_shas[p] = frozenset({"m0", "m1", "m2"})
+ for i in range(90):
+ p = f"lib/l{i}.py"
+ fixes = 1 if i < 12 else 0
+ files.append(_file(p, fix_commits_90d=fixes, commits_90d=1, bug_magnet=False))
+ if fixes:
+ fix_shas[p] = frozenset({f"l{i}"})
+ return _facts(files, fix_shas_by_file=fix_shas, fix_commits_90d=25)
+
+
+def test_concentration_needs_twenty_fixes() -> None:
+ out = _run(code.fix_concentration, _facts([_file("src/a.py")], fix_commits_90d=19))
+ assert out.status == "not_applicable"
+
+
+def test_concentration_picks_the_narrow_high_lift_folder() -> None:
+ out = _run(code.fix_concentration, _concentration_facts())
+ (a,) = out.actions
+ assert a.target_path == "pkg/cli/update"
+ assert a.target_kind == "folder"
+ assert set(a.includes) == {f"pkg/cli/update/a{i}.py" for i in range(4)}
+
+
+def test_engine_drops_fragile_rows_a_folder_absorbed() -> None:
+ facts = _concentration_facts()
+ # Sanity: on their own, the folder's files are fragile.
+ fragile = _run(code.fragile_file, facts).actions
+ assert {a.target_path for a in fragile} >= {f"pkg/cli/update/a{i}.py" for i in range(4)}
+
+ view = compose_actions(facts, now=NOW)
+ quarter = view["horizons"]["quarter"]["actions"]
+ assert not any(
+ a["rule"] == "fragile_file" and a["target"]["path"].startswith("pkg/cli/update/")
+ for a in quarter
+ )
+ folder = next(a for a in quarter if a["rule"] == "fix_concentration")
+ assert len(folder["includes"]) == 4
+
+
+# ---------------------------------------------------------------------------
+# hot_path_perf
+# ---------------------------------------------------------------------------
+
+
+def _perf(**kw) -> PerfFacts:
+ base = dict(
+ opportunity_id="op1",
+ biomarker="n_plus_one",
+ boundary="db",
+ file_path="src/repo.py",
+ symbol="src/repo.py::Repo.load",
+ call_sites=1,
+ files=1,
+ actionability="plan_ready",
+ exposure="entry_reachable",
+ loop_magnitude="grows_with_data",
+ effort="S",
+ )
+ base.update(kw)
+ return PerfFacts(**base)
+
+
+def test_perf_fires_when_reachable_and_growing() -> None:
+ (a,) = _run(code.hot_path_perf, _facts(perf=(_perf(),))).actions
+ assert a.title == "Move the database call in `Repo.load` out of its loop"
+ assert a.target_symbol == "src/repo.py::Repo.load"
+ assert a.confidence == "high"
+
+
+def test_perf_fires_on_three_call_sites_without_growth() -> None:
+ (a,) = _run(
+ code.hot_path_perf,
+ _facts(perf=(_perf(loop_magnitude=None, call_sites=3, actionability="advisory"),)),
+ ).actions
+ assert a.title == "Batch the database calls loops make through `Repo.load`"
+ assert a.confidence == "medium"
+
+
+def test_perf_gates() -> None:
+ quiet = (
+ _perf(loop_magnitude=None, call_sites=2),
+ _perf(exposure="internal"),
+ _perf(exposure=None),
+ _perf(actionability="investigate"),
+ )
+ for p in quiet:
+ assert _run(code.hot_path_perf, _facts(perf=(p,))).actions == (), p
+
+
+# ---------------------------------------------------------------------------
+# live_secret
+# ---------------------------------------------------------------------------
+
+
+def test_secret_in_code_is_act_now_critical() -> None:
+ s = SecretFacts("src/config.py", "hardcoded_secret", 4, 'API_KEY = "sk_live_abc"')
+ (a,) = _run(hygiene.live_secret, _facts(secrets=(s,))).actions
+ assert (a.tier, a.severity) == ("act_now", "critical")
+ assert a.title == "Rotate the hard-coded secret in `src/config.py`"
+
+
+def test_public_env_secret_is_plan() -> None:
+ s = SecretFacts("web/env.ts", "public_env_secret", 2, "NEXT_PUBLIC_SECRET = process.env.X")
+ (a,) = _run(hygiene.live_secret, _facts(secrets=(s,))).actions
+ assert (a.tier, a.severity) == ("plan", "high")
+
+
+def test_secret_ignores_docs_comments_and_quotes() -> None:
+ quiet = (
+ SecretFacts("README.md", "hardcoded_secret", 3, 'API_KEY = "abc"'),
+ SecretFacts("docs/setup.py", "hardcoded_secret", 3, 'API_KEY = "abc"'),
+ SecretFacts("src/a.py", "hardcoded_password", 3, '# password = "hunter2"'),
+ SecretFacts("src/b.py", "hardcoded_password", 3, '"password": "example"'),
+ SecretFacts("src/c.py", "os_system", 3, "os.system(cmd)"),
+ )
+ assert _run(hygiene.live_secret, _facts(secrets=quiet)).actions == ()
+
+
+# ---------------------------------------------------------------------------
+# broken_doc_refs
+# ---------------------------------------------------------------------------
+
+
+def _drift(**kw) -> DriftFacts:
+ base = dict(
+ document="docs/guide.md",
+ kind="path",
+ target="src/old.py",
+ raw="src/old.py",
+ line=3,
+ reason="gone",
+ confidence=0.9,
+ target_known=True,
+ )
+ base.update(kw)
+ return DriftFacts(**base)
+
+
+def test_doc_path_ref_needs_a_known_target() -> None:
+ assert _run(hygiene.broken_doc_refs, _facts(drift=(_drift(target_known=False),))).actions == ()
+ (a,) = _run(hygiene.broken_doc_refs, _facts(drift=(_drift(),))).actions
+ assert a.title == "Fix 1 broken reference in `docs/guide.md`"
+
+
+def test_doc_anchor_ignores_site_root_links() -> None:
+ site = _drift(kind="anchor", raw="/#install", target="docs/guide.md#install")
+ local = _drift(kind="anchor", raw="#usage", target="docs/guide.md#usage")
+ (a,) = _run(hygiene.broken_doc_refs, _facts(drift=(site, local))).actions
+ assert a.why[1].value == "docs/guide.md#usage"
+
+
+def test_doc_low_confidence_ignored() -> None:
+ assert _run(hygiene.broken_doc_refs, _facts(drift=(_drift(confidence=0.5),))).actions == ()
+
+
+# ---------------------------------------------------------------------------
+# dead_code_batch
+# ---------------------------------------------------------------------------
+
+
+def test_dead_code_below_floor_is_silent() -> None:
+ dead = (DeadFacts("d1", "src/a.py", "f", 10), DeadFacts("d2", "src/a.py", "g", 10))
+ out = _run(hygiene.dead_code_batch, _facts(dead=dead))
+ assert out.status == "evaluated"
+ assert out.actions == ()
+
+
+def test_dead_code_excludes_standalone_dirs() -> None:
+ standalone = tuple(
+ DeadFacts(f"s{i}", path, "f", 50)
+ for i, path in enumerate(("docs_src/tut.py", "examples/demo.py", "scripts/run.py"))
+ )
+ assert _run(hygiene.dead_code_batch, _facts(dead=standalone)).actions == ()
+ real = tuple(DeadFacts(f"d{i}", "src/a.py", f"f{i}", 5) for i in range(3))
+ (a,) = _run(hygiene.dead_code_batch, _facts(dead=standalone + real)).actions
+ assert a.evidence_total == 3
+ assert a.title == "Delete 3 unused symbols and files (15 lines)"
+
+
+# ---------------------------------------------------------------------------
+# knowledge_loss, stale_decision
+# ---------------------------------------------------------------------------
+
+
+def _owned() -> FileFacts:
+ return _file("src/a.py", owner_key="k", owner_name="Ada", owner_pct=0.9)
+
+
+def test_knowledge_loss_needs_a_team() -> None:
+ facts = _facts(
+ [_owned()],
+ active_authors_90d=2,
+ author_last_commit={"k": ANCHOR - timedelta(days=100)},
+ )
+ assert _run(hygiene.knowledge_loss, facts).status == "not_applicable"
+
+
+def test_knowledge_loss_fires_for_a_quiet_owner() -> None:
+ facts = _facts(
+ [_owned()],
+ active_authors_90d=3,
+ author_last_commit={"k": ANCHOR - timedelta(days=100)},
+ )
+ (a,) = _run(hygiene.knowledge_loss, facts).actions
+ assert a.title == "Share what Ada knew about `src/a.py`"
+
+
+def test_stale_decision_needs_accepted_decisions() -> None:
+ d = (DecisionFacts("dec1", "Use SQLite"),)
+ assert _run(hygiene.stale_decision, _facts(stale_decisions=d)).status == "not_applicable"
+ (a,) = _run(hygiene.stale_decision, _facts(stale_decisions=d, accepted_decisions=1)).actions
+ assert a.tier == "plan"
+
+
+# ---------------------------------------------------------------------------
+# improve_signal rules
+# ---------------------------------------------------------------------------
+
+
+def _many_files(n: int = 25) -> list[FileFacts]:
+ return [_file(f"src/f{i}.py", fix_commits_90d=0, bug_magnet=False) for i in range(n)]
+
+
+def test_coverage_missing_is_improve_signal() -> None:
+ (a,) = _run(signal.coverage_missing, _facts(_many_files())).actions
+ assert a.tier == "improve_signal"
+ assert _run(signal.coverage_missing, _facts(_many_files(5))).status == "not_applicable"
+
+
+def test_coverage_stale_is_improve_signal() -> None:
+ cov = CoverageState("stale", ANCHOR - timedelta(days=30), 40)
+ (a,) = _run(signal.coverage_stale, _facts(coverage=cov)).actions
+ assert a.tier == "improve_signal"
+ recent = CoverageState("stale", ANCHOR - timedelta(days=3), 40)
+ assert _run(signal.coverage_stale, _facts(coverage=recent)).actions == ()
+
+
+def test_decisions_unreviewed_is_improve_signal() -> None:
+ (a,) = _run(signal.decisions_unreviewed, _facts(proposed_decisions=6)).actions
+ assert a.tier == "improve_signal"
+ assert (
+ _run(signal.decisions_unreviewed, _facts(proposed_decisions=6, accepted_decisions=1)).actions
+ == ()
+ )
+
+
+# ---------------------------------------------------------------------------
+# engine
+# ---------------------------------------------------------------------------
+
+
+def _docs(n: int) -> tuple[DriftFacts, ...]:
+ return tuple(_drift(document=f"docs/d{i}.md", target=f"src/gone{i}.py") for i in range(n))
+
+
+def _mixed() -> RepoFacts:
+ return _facts(
+ _many_files(),
+ secrets=(SecretFacts("src/config.py", "hardcoded_secret", 4, 'KEY = "sk_live_a1b2c3"'),),
+ drift=_docs(4),
+ dead=tuple(DeadFacts(f"d{i}", "src/a.py", f"f{i}", 20) for i in range(3)),
+ )
+
+
+def test_engine_orders_by_tier() -> None:
+ quarter = compose_actions(_mixed(), now=NOW)["horizons"]["quarter"]["actions"]
+ ranks = [TIER_RANK[a["tier"]] for a in quarter]
+ assert ranks == sorted(ranks)
+ assert quarter[0]["rule"] == "live_secret"
+ assert quarter[-1]["tier"] == "improve_signal"
+
+
+def test_engine_caps_each_rule_in_the_tier_head() -> None:
+ quarter = compose_actions(_mixed(), now=NOW)["horizons"]["quarter"]["actions"]
+ plan = [a["rule"] for a in quarter if a["tier"] == "plan"]
+ assert plan == [
+ "broken_doc_refs",
+ "broken_doc_refs",
+ "dead_code_batch",
+ "broken_doc_refs",
+ "broken_doc_refs",
+ ]
+
+
+def test_engine_reports_totals_and_every_rule() -> None:
+ view = compose_actions(_mixed(), now=NOW)
+ quarter = view["horizons"]["quarter"]
+ assert quarter["total"] == len(quarter["actions"]) == 7
+ assert quarter["hidden"] == 0
+ assert quarter["by_tier"] == {"act_now": 1, "plan": 5, "improve_signal": 1}
+ assert len(view["rules"]) == 12
+ # The week sees the secret and the coverage prompt, not the quarter's plan work.
+ assert view["horizons"]["week"]["total"] == 2
+
+
+def test_engine_keeps_the_full_total_past_the_cap() -> None:
+ view = compose_actions(_facts(drift=_docs(KEEP_PER_HORIZON + 5)), now=NOW)
+ quarter = view["horizons"]["quarter"]
+ assert len(quarter["actions"]) == KEEP_PER_HORIZON
+ assert quarter["total"] == KEEP_PER_HORIZON + 5
+
+
+def _secret_action(view) -> dict:
+ return next(a for a in view["horizons"]["quarter"]["actions"] if a["rule"] == "live_secret")
+
+
+def test_dismissal_holds_only_while_the_fingerprint_matches() -> None:
+ facts = _mixed()
+ action = _secret_action(compose_actions(facts, now=NOW))
+ same = {action["id"]: ActionStateRecord("dismissed", action["fingerprint"])}
+ view = compose_actions(facts, same, now=NOW)
+ assert not any(a["id"] == action["id"] for a in view["horizons"]["quarter"]["actions"])
+ assert view["horizons"]["quarter"]["hidden"] == 1
+ assert view["horizons"]["quarter"]["total"] == 6
+
+ changed = {action["id"]: ActionStateRecord("dismissed", "stale-fingerprint")}
+ view = compose_actions(facts, changed, now=NOW)
+ assert _secret_action(view)["id"] == action["id"]
+ assert view["horizons"]["quarter"]["hidden"] == 0
+
+
+def test_snooze_hides_until_it_expires() -> None:
+ facts = _mixed()
+ action = _secret_action(compose_actions(facts, now=NOW))
+ later = {action["id"]: ActionStateRecord("snoozed", "", NOW + timedelta(days=3))}
+ view = compose_actions(facts, later, now=NOW)
+ assert view["horizons"]["quarter"]["hidden"] == 1
+ expired = {action["id"]: ActionStateRecord("snoozed", "", NOW - timedelta(days=1))}
+ assert _secret_action(compose_actions(facts, expired, now=NOW))
+
+
+def test_action_id_is_stable_for_rule_and_target() -> None:
+ (a,) = _run(hygiene.broken_doc_refs, _facts(drift=(_drift(),))).actions
+ (b,) = _run(
+ hygiene.broken_doc_refs, _facts(drift=(_drift(target="src/other.py"), _drift()))
+ ).actions
+ assert a.action_id == b.action_id
+ assert a.title != b.title
+ (c,) = _run(hygiene.broken_doc_refs, _facts(drift=(_drift(document="docs/x.md"),))).actions
+ assert c.action_id != a.action_id
+ assert a.action_id.startswith("act_")
+
+
+# ---------------------------------------------------------------------------
+# Review regressions
+# ---------------------------------------------------------------------------
+
+
+def test_week_rollup_does_not_hide_a_fragile_file_from_the_quarter() -> None:
+ fragile = _file("src/f0.py", fix_commits_90d=9, commits_90d=20)
+ found = tuple(_recent(f"src/f{i}.py") for i in range(4))
+ view = compose_actions(_facts([fragile], recent_findings=found), now=ANCHOR)
+ quarter = [a["target"]["path"] for a in view["horizons"]["quarter"]["actions"]]
+ assert "src/f0.py" in quarter
+
+
+def test_two_perf_opportunities_on_one_symbol_keep_distinct_ids() -> None:
+ one = _perf(opportunity_id="op1", boundary="db")
+ two = _perf(opportunity_id="op2", boundary="network")
+ ids = {a.action_id for a in _run(code.hot_path_perf, _facts(perf=(one, two))).actions}
+ assert len(ids) == 2
+
+
+def test_fragile_id_survives_a_change_of_lead_function() -> None:
+ lead = LeadFinding("complex_method", "high", "a", 1, "")
+ before = _file("src/x.py", fix_commits_90d=9, commits_90d=20, line_coverage_pct=90.0, lead=lead)
+ after = replace(before, lead=replace(lead, function="b"))
+ ctx = dict(busy_threshold=5, fix_threshold=3)
+ (a,) = _run(code.fragile_file, _facts([before]), **ctx).actions
+ (b,) = _run(code.fragile_file, _facts([after]), **ctx).actions
+ assert a.action_id == b.action_id
+
+
+def test_secret_ignores_placeholder_examples_in_code() -> None:
+ examples = (
+ SecretFacts("src/embed.py", "hardcoded_secret", 15, 'embedder = Embedder(api_key="AIza...")'),
+ SecretFacts("src/p.py", "hardcoded_secret", 12, 'p = get("openai", api_key="sk-...", model="gpt")'),
+ SecretFacts("src/q.py", "hardcoded_secret", 3, 'token = "your-token-here"'),
+ )
+ assert _run(hygiene.live_secret, _facts(secrets=examples)).actions == ()
+ real = SecretFacts("src/r.py", "hardcoded_secret", 3, 'API_KEY = "sk-live-a****"')
+ assert len(_run(hygiene.live_secret, _facts(secrets=(real,))).actions) == 1
+
+
+def test_secret_ignores_a_dummy_word_value() -> None:
+ dummy = SecretFacts("src/ollama.py", "hardcoded_secret", 3, 'OpenAI(api_key="ollama", base_url=u)')
+ assert _run(hygiene.live_secret, _facts(secrets=(dummy,))).actions == ()
+
+
+def test_rollup_carries_evidence_starting_with_the_worst_file_and_commands() -> None:
+ found = (
+ *(_recent(f"src/f{i}.py", sha=f"s{i}") for i in range(4)),
+ _recent("src/worst.py", severity="critical", sha="w1"),
+ )
+ (a,) = _run(code.fresh_regressions, _facts(recent_findings=found)).actions
+ assert a.details[0].path == "src/worst.py" == a.includes[0]
+ assert a.details_total == 5
+ mcp = [c.mcp for c in a.commands]
+ assert any(m and m.startswith('get_health(targets=["src/worst.py"') for m in mcp)
+ assert 'get_change_risk(revspec="w1")' in mcp
diff --git a/tests/unit/cli/test_lazy_commands.py b/tests/unit/cli/test_lazy_commands.py
index cc6995910..f6a0db6aa 100644
--- a/tests/unit/cli/test_lazy_commands.py
+++ b/tests/unit/cli/test_lazy_commands.py
@@ -37,7 +37,7 @@ _EXPECTED_NAMES = frozenset(
"dead-code", "decision", "delete", "distill", "doc-drift", "doctor",
"expand",
"export", "generate", "generate-claude-md", "health", "hook",
- "impacted-tests", "init", "login", "logout", "mcp", "overlap", "reindex",
+ "impacted-tests", "init", "login", "logout", "mcp", "next", "overlap", "reindex",
"restyle",
"risk", "saved", "savings", "search", "security", "serve", "status", "symbol",
"telemetry", "uninstall", "update", "watch", "whats-new", "whoami", "why",
diff --git a/tests/unit/cli/test_next_cmd.py b/tests/unit/cli/test_next_cmd.py
new file mode 100644
index 000000000..77fe6b48a
--- /dev/null
+++ b/tests/unit/cli/test_next_cmd.py
@@ -0,0 +1,231 @@
+"""``repowise next``, and the "Next" block ``repowise status`` prints.
+
+Rendering is checked over a canned view; one test builds a real index so the
+command's read path (store, repository lookup, loader) runs end to end.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import datetime
+import json
+from pathlib import Path
+from typing import Any
+
+import pytest
+from click.testing import CliRunner
+
+from repowise.cli.commands import next_cmd, status_cmd
+from repowise.cli.commands.next_cmd import next_command
+
+
+def _action(n: int, tier: str, title: str, **extra: Any) -> dict[str, Any]:
+ return {
+ "id": f"act_{n}",
+ "rule": "fragile_file",
+ "tier": tier,
+ "horizons": ["week", "quarter"],
+ "severity": "high",
+ "title": title,
+ "impact": f"Impact {n}.",
+ "why": [{"label": "bug-fix commits", "value": str(n), "basis": "measured"}],
+ "target": {"kind": "file", "path": f"src/f{n}.py", "symbol": None},
+ "surface": "file",
+ "effort": "M",
+ "confidence": "high",
+ "done_when": f"Done {n}.",
+ "command": None,
+ **extra,
+ }
+
+
+def _horizon(actions: list[dict[str, Any]], total: int | None = None) -> dict[str, Any]:
+ by_tier: dict[str, int] = {}
+ for a in actions:
+ by_tier[a["tier"]] = by_tier.get(a["tier"], 0) + 1
+ return {
+ "actions": actions,
+ "total": len(actions) if total is None else total,
+ "hidden": 0,
+ "by_tier": by_tier,
+ }
+
+
+def _view(week: list[dict], quarter: list[dict], **extra: Any) -> dict[str, Any]:
+ return {
+ "status": "available",
+ "anchor": "2026-09-28T12:00:00",
+ "week_start": "2026-09-21T12:00:00",
+ "context": {},
+ "horizons": {"week": _horizon(week), "quarter": _horizon(quarter)},
+ "rules": [],
+ "unavailable": {},
+ **extra,
+ }
+
+
+def canned(monkeypatch: pytest.MonkeyPatch):
+ def install(view: dict[str, Any] | None) -> None:
+ monkeypatch.setattr(next_cmd, "load_view", lambda root: view)
+
+ return install
+
+
+def _run(*args: str) -> Any:
+ return CliRunner().invoke(next_command, [*args, "--no-workspace"], catch_exceptions=False)
+
+
+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`"),
+ _action(2, "plan", "Add tests around `src/core.py`", command="repowise coverage add x"),
+ _action(3, "improve_signal", "Add a test coverage report"),
+ ]
+ canned(_view(week, week))
+
+ out = _run(str(tmp_path)).output
+
+ assert out.startswith("2 things worth doing in the week to Sep 28, the last indexed commit")
+ assert "1 of them now" in out
+ assert out.index("Now") < out.index("Worth planning") < out.index("Improve what Repowise")
+ # Backticks are markup, not text.
+ assert "Rotate the key in src/settings.py" in out
+ assert "`" not in out
+ assert "bug-fix commits: 2" in out
+ assert "Done when: Done 2." in out
+ assert "$ repowise coverage add x" in out
+
+
+def test_falls_back_to_the_quarter_when_the_week_holds_no_work(canned, tmp_path: Path) -> None:
+ canned(
+ _view(
+ [_action(1, "improve_signal", "Add a test coverage report")],
+ [_action(2, "plan", "Delete 9 unused symbols")],
+ )
+ )
+
+ out = _run(str(tmp_path)).output
+ assert out.startswith("1 thing worth doing this quarter.")
+ assert "Delete 9 unused symbols" in out
+
+ # Asking for the week by name keeps it, and the sentence points at the quarter.
+ out = _run(str(tmp_path), "--horizon", "week").output
+ assert out.startswith("Nothing needs you in the week to Sep 28")
+ assert "1 thing is worth planning this quarter." in out
+ assert "Delete 9 unused symbols" not in out
+
+
+def test_all_widens_the_preview(canned, tmp_path: Path) -> None:
+ rows = [_action(i, "plan", f"Task number {i}") for i in range(8)]
+ canned(_view(rows, rows))
+
+ out = _run(str(tmp_path)).output
+ assert "Task number 4" in out and "Task number 5" not in out
+ assert "Showing 5 of 8. --all shows up to 20." in out
+
+ out = _run(str(tmp_path), "--all").output
+ assert "Task number 7" in out
+ assert "Showing" not in out
+
+
+def test_json_dumps_the_raw_view(canned, tmp_path: Path) -> None:
+ view = _view([_action(1, "act_now", "Fix `a`")], [], unavailable={"performance": "x"})
+ canned(view)
+
+ for flag in (("--json",), ("--format", "json")):
+ result = _run(str(tmp_path), *flag)
+ assert json.loads(result.stdout) == view
+
+
+def test_names_stores_the_index_predates(canned, tmp_path: Path) -> None:
+ canned(_view([_action(1, "plan", "Do it")], [], unavailable={"security": "x", "performance": "y"}))
+
+ out = _run(str(tmp_path)).output
+ assert "Not in this index yet: performance, security." in out
+
+
+def test_no_index_is_a_message_not_a_crash(tmp_path: Path) -> None:
+ result = _run(str(tmp_path))
+ assert result.exit_code == 0
+ assert "No readable index here" in result.output
+
+ result = _run(str(tmp_path), "--format", "json")
+ assert json.loads(result.stdout) == {"repo": str(tmp_path.resolve()), "status": "unavailable"}
+
+
+def test_status_carries_a_next_block_and_json_counts() -> None:
+ view = _view(
+ [_action(1, "improve_signal", "Add a report")],
+ [_action(2, "plan", "Split `src/big.py`"), _action(3, "improve_signal", "Add a report")],
+ )
+
+ lines = status_cmd._next_actions_lines(view)
+ assert lines[0].endswith("1 thing is worth planning this quarter.")
+ assert "src/big.py" in lines[1]
+ assert status_cmd._next_actions_lines(None) == []
+
+ summary = status_cmd._next_actions_summary(view)
+ assert summary["week"] == {"total": 1, "by_tier": {"improve_signal": 1}}
+ assert summary["quarter"]["by_tier"] == {"plan": 1, "improve_signal": 1}
+ assert "actions" not in summary["quarter"]
+ assert status_cmd._next_actions_summary(None) is None
+
+
+def test_status_never_fails_on_the_actions_read(monkeypatch: pytest.MonkeyPatch) -> None:
+ def boom(root: Path) -> None:
+ raise RuntimeError("no such table")
+
+ monkeypatch.setattr(next_cmd, "load_view", boom)
+ assert status_cmd._load_actions(Path("/nowhere")) is None
+
+
+async def _build_index(repo_path: Path) -> None:
+ import git as gitpython
+
+ from repowise.core.persistence import create_engine, create_session_factory, get_session
+ from repowise.core.persistence.crud import upsert_repository
+ from repowise.core.persistence.database import init_db
+ from repowise.core.persistence.models import DeadCodeFinding, GitCommit
+
+ gitpython.Repo.init(repo_path)
+ repowise_dir = repo_path / ".repowise"
+ repowise_dir.mkdir()
+ engine = create_engine(f"sqlite+aiosqlite:///{repowise_dir / 'wiki.db'}")
+ await init_db(engine)
+ sf = create_session_factory(engine)
+ try:
+ async with get_session(sf) as session:
+ repo = await upsert_repository(
+ session, name="repo", local_path=str(repo_path), url="https://example.test/r"
+ )
+ anchor = datetime.datetime(2026, 9, 28, 12, 0, tzinfo=datetime.UTC)
+ session.add(
+ GitCommit(repository_id=repo.id, sha="head", author_name="Ada",
+ author_email="[email protected]", committed_at=anchor, subject="chore: head")
+ ) # fmt: skip
+ session.add_all(
+ DeadCodeFinding(repository_id=repo.id, kind="unused_export",
+ file_path="src/dead.py", symbol_name=f"f{i}", lines=10,
+ safe_to_delete=True)
+ for i in range(3)
+ ) # fmt: skip
+ await session.commit()
+ finally:
+ await engine.dispose()
+
+
+def test_reads_a_real_index(tmp_path: Path) -> None:
+ repo_path = (tmp_path / "repo").resolve()
+ repo_path.mkdir()
+ asyncio.run(_build_index(repo_path))
+
+ result = _run(str(repo_path), "--format", "json")
+ view = json.loads(result.stdout)
+ assert view["status"] == "available"
+ rules = {a["rule"] for a in view["horizons"]["quarter"]["actions"]}
+ assert "dead_code_batch" in rules
+
+ out = _run(str(repo_path), "--horizon", "quarter").output
+ assert "Worth planning" in out
+ assert "unused" in out
diff --git a/tests/unit/health/test_primary_and_magnitude.py b/tests/unit/health/test_primary_and_magnitude.py
index 3c8db8538..07348d4d8 100644
--- a/tests/unit/health/test_primary_and_magnitude.py
+++ b/tests/unit/health/test_primary_and_magnitude.py
@@ -76,3 +76,14 @@ def test_plain_dicts_fold_like_rows() -> None:
from repowise.core.analysis.health.aggregation import primary_and_magnitude_by_file
assert primary_and_magnitude_by_file([vars(f) for f in FINDINGS]) == GOLDEN
+
+
+def test_primary_finding_prefers_code_shape_over_history() -> None:
+ """A history marker names context, not an edit; a code-shape finding leads
+ even when the history one deducts more, and history leads only alone."""
+ from repowise.core.analysis.health.models import primary_finding
+
+ shaped = _f("e.py", "complex_method", 0.4, "ccn 14")
+ history = _f("e.py", "change_entropy", 2.5, "changed with 25 files")
+ assert primary_finding([history, shaped]) is shaped
+ assert primary_finding([history]) is history
diff --git a/tests/unit/persistence/test_actions_loader.py b/tests/unit/persistence/test_actions_loader.py
new file mode 100644
index 000000000..ac3e99959
--- /dev/null
+++ b/tests/unit/persistence/test_actions_loader.py
@@ -0,0 +1,289 @@
+"""The next-actions loader over a real (in-memory) store.
+
+Seeds one small repository across the stores the rules read, then checks the
+composed view, a missing store degrading to ``unavailable``, and the
+per-person state round trip.
+"""
+
+from __future__ import annotations
+
+import json
+from datetime import UTC, datetime, timedelta
+
+from sqlalchemy import select, text
+
+from repowise.core.persistence.crud.analysis.actions import (
+ get_action_states,
+ load_actions_view,
+ set_action_state,
+)
+from repowise.core.persistence.models import (
+ ActionState,
+ DeadCodeFinding,
+ DocDriftFinding,
+ FixEvent,
+ GitCommit,
+ GitCommitFile,
+ GitCommitHealthFinding,
+ GitMetadata,
+ HealthFileMetric,
+ HealthFinding,
+ PerformanceOpportunity,
+ SecurityFinding,
+)
+from tests.unit.persistence.helpers import insert_repo
+
+ANCHOR = datetime(2026, 9, 28, 12, 0, tzinfo=UTC)
+NOW = ANCHOR + timedelta(days=1)
+
+
+async def _seed(session) -> str:
+ repo = await insert_repo(session)
+ rid = repo.id
+ add = session.add_all
+
+ # Three active authors, the newest commit is the anchor.
+ add(
+ [
+ GitCommit(repository_id=rid, sha="head", author_name="Ada", author_email="[email protected]",
+ committed_at=ANCHOR, subject="chore: head"),
+ GitCommit(repository_id=rid, sha="recent", author_name="Bob", author_email="[email protected]",
+ committed_at=ANCHOR - timedelta(days=2), subject="feat: build step"),
+ GitCommit(repository_id=rid, sha="older", author_name="Cy", author_email="[email protected]",
+ committed_at=ANCHOR - timedelta(days=20), subject="fix: things"),
+ ]
+ )
+ add([GitCommitFile(repository_id=rid, sha="older", file_path="src/old.py")])
+
+ # A busy bug magnet with four fixes and a code-shape lead beside a
+ # higher-impact history marker.
+ add(
+ [
+ GitMetadata(repository_id=rid, file_path="src/core.py", commit_count_90d=12,
+ last_commit_at=ANCHOR - timedelta(days=1), bug_magnet=True),
+ HealthFileMetric(repository_id=rid, file_path="src/core.py", max_ccn=12, nloc=300,
+ is_test=False),
+ HealthFinding(repository_id=rid, file_path="src/core.py", biomarker_type="change_entropy",
+ severity="high", health_impact=3.0),
+ HealthFinding(repository_id=rid, file_path="src/core.py", biomarker_type="complex_method",
+ severity="high", function_name="run", health_impact=1.0),
+ ]
+ )
+ add(
+ [
+ FixEvent(repository_id=rid, fix_sha=f"fix{i}", file_path="src/core.py",
+ shape_kind="code_fix", attribution="exact",
+ committed_at=ANCHOR - timedelta(days=10 + i))
+ for i in range(4)
+ ]
+ )
+
+ # This week's commit wrote an open finding; two siblings must not count.
+ add(
+ [
+ GitCommitHealthFinding(repository_id=rid, sha="recent", change_finding_id="c1",
+ change_kind="introduced", dimension="defect",
+ biomarker_type="complex_method", severity="high",
+ file_path="src/new.py", symbol="build",
+ attribution_basis="added_lines"),
+ GitCommitHealthFinding(repository_id=rid, sha="recent", change_finding_id="c2",
+ change_kind="introduced", dimension="defect",
+ biomarker_type="long_method", severity="high",
+ file_path="src/touched.py", symbol="x",
+ attribution_basis="file_change"),
+ GitCommitHealthFinding(repository_id=rid, sha="recent", change_finding_id="c3",
+ change_kind="introduced", dimension="defect",
+ biomarker_type="change_entropy", severity="high",
+ file_path="src/hist.py", symbol=None,
+ attribution_basis="added_lines"),
+ HealthFinding(repository_id=rid, file_path="src/new.py", biomarker_type="complex_method",
+ severity="high", function_name="build", health_impact=1.0),
+ HealthFinding(repository_id=rid, file_path="src/touched.py", biomarker_type="long_method",
+ severity="high", function_name="x", health_impact=1.0),
+ ]
+ )
+
+ add(
+ [
+ PerformanceOpportunity(
+ repository_id=rid, opportunity_id="perf1", status="open",
+ execution_context="production", actionability_state="plan_ready",
+ boundary_kind="db", biomarker_type="n_plus_one", file_path="src/repo.py",
+ intervention_symbol="src/repo.py::Repo.load", affected_call_sites_total=4,
+ affected_files_total=2,
+ details_json=json.dumps(
+ {"facets": {"exposure": "entry_reachable", "loop_magnitude": "grows_with_data"},
+ "plan": {"effort_bucket": "S"}}
+ ),
+ ),
+ PerformanceOpportunity(
+ repository_id=rid, opportunity_id="perf2", status="open",
+ execution_context="production", actionability_state="plan_ready",
+ boundary_kind="db", file_path="src/other.py", affected_call_sites_total=9,
+ details_json=json.dumps({"facets": {"exposure": "internal"}}),
+ ),
+ ]
+ )
+
+ add(
+ [
+ SecurityFinding(repository_id=rid, file_path="src/settings.py", kind="hardcoded_secret",
+ severity="high", snippet='TOKEN = "sk_live_123"', line_number=4,
+ commit_sha=""),
+ SecurityFinding(repository_id=rid, file_path="tests/test_x.py", kind="hardcoded_secret",
+ severity="high", snippet='TOKEN = "fake"', line_number=4, commit_sha=""),
+ ]
+ )
+
+ add(
+ [
+ DocDriftFinding(repository_id=rid, file_path="README.md", kind="anchor", line_number=3,
+ target="README.md#setup", raw="#setup", confidence=0.9),
+ DocDriftFinding(repository_id=rid, file_path="docs/guide.md", kind="path", line_number=5,
+ target="src/old.py", raw="src/old.py", confidence=0.9),
+ DocDriftFinding(repository_id=rid, file_path="docs/other.md", kind="path", line_number=5,
+ target="elsewhere/never.py", raw="elsewhere/never.py", confidence=0.9),
+ ]
+ )
+
+ add(
+ [
+ DeadCodeFinding(repository_id=rid, kind="unused_export", file_path="src/dead.py",
+ symbol_name=f"f{i}", lines=10, safe_to_delete=True)
+ for i in range(3)
+ ]
+ )
+ await session.commit()
+ return rid
+
+
+def _quarter(view) -> list[dict]:
+ return view["horizons"]["quarter"]["actions"]
+
+
+def _by_rule(view, horizon: str = "quarter") -> dict[str, list[dict]]:
+ out: dict[str, list[dict]] = {}
+ for a in view["horizons"][horizon]["actions"]:
+ out.setdefault(a["rule"], []).append(a)
+ return out
+
+
+async def test_load_actions_view_composes_every_store(async_session) -> None:
+ rid = await _seed(async_session)
+ view = await load_actions_view(async_session, rid, now=NOW)
+
+ assert view["unavailable"] == {}
+ assert view["context"]["active_authors_90d"] == 3
+ assert view["context"]["fix_commits_90d"] == 4
+ rules = _by_rule(view)
+
+ (fragile,) = rules["fragile_file"]
+ assert fragile["target"]["path"] == "src/core.py"
+ assert fragile["title"].startswith("Add tests around `src/core.py`")
+ # The code-shape finding leads, not the higher-impact history marker.
+ assert fragile["marker"] == "complex_method"
+
+ (perf,) = rules["hot_path_perf"]
+ assert perf["title"] == "Batch the database calls loops make through `Repo.load`"
+ assert perf["effort"] == "S"
+
+ (secret,) = rules["live_secret"]
+ assert secret["target"]["path"] == "src/settings.py"
+
+ assert {a["target"]["path"] for a in rules["broken_doc_refs"]} == {"README.md", "docs/guide.md"}
+ (dead,) = rules["dead_code_batch"]
+ assert dead["evidence_total"] == 3
+
+ week = _by_rule(view, "week")
+ (fresh,) = week["fresh_regressions"]
+ assert fresh["title"] == "Simplify `build` in `src/new.py` while the change is fresh"
+ assert fresh["evidence_ids"] == ["recent"]
+
+
+async def test_a_missing_store_is_reported_and_the_rest_still_load(async_session) -> None:
+ rid = await _seed(async_session)
+ await async_session.execute(text("DROP TABLE performance_opportunities"))
+ await async_session.commit()
+
+ view = await load_actions_view(async_session, rid, now=NOW)
+ assert set(view["unavailable"]) == {"performance"}
+ status = {r["rule"]: r["status"] for r in view["rules"]}
+ assert status["hot_path_perf"] == "unavailable"
+ assert status["live_secret"] == "evaluated"
+ rules = _by_rule(view)
+ assert "hot_path_perf" not in rules
+ assert {"fragile_file", "live_secret", "broken_doc_refs"} <= set(rules)
+
+
+async def test_action_state_round_trip(async_session) -> None:
+ rid = await _seed(async_session)
+
+ await set_action_state(async_session, rid, "act_x", state="dismissed", fingerprint="fp1")
+ await async_session.commit()
+ assert (await get_action_states(async_session, rid))["act_x"].state == "dismissed"
+
+ until = NOW + timedelta(days=7)
+ await set_action_state(async_session, rid, "act_x", state="snoozed", until=until)
+ await async_session.commit()
+ rec = (await get_action_states(async_session, rid))["act_x"]
+ assert (rec.state, rec.fingerprint) == ("snoozed", "")
+ assert rec.until.replace(tzinfo=None) == until.replace(tzinfo=None)
+ rows = (await async_session.execute(select(ActionState))).scalars().all()
+ assert len(rows) == 1
+
+ await set_action_state(async_session, rid, "act_x", state=None)
+ await async_session.commit()
+ assert await get_action_states(async_session, rid) == {}
+
+
+async def test_dismissed_action_returns_when_its_fingerprint_changes(async_session) -> None:
+ rid = await _seed(async_session)
+ view = await load_actions_view(async_session, rid, now=NOW)
+ (secret,) = _by_rule(view)["live_secret"]
+
+ await set_action_state(
+ async_session, rid, secret["id"], state="dismissed", fingerprint=secret["fingerprint"]
+ )
+ await async_session.commit()
+ view = await load_actions_view(async_session, rid, now=NOW)
+ assert "live_secret" not in _by_rule(view)
+ assert view["horizons"]["quarter"]["hidden"] == 1
+
+ # A second secret in the same file changes the facts behind the action.
+ async_session.add(
+ SecurityFinding(repository_id=rid, file_path="src/settings.py", kind="hardcoded_secret",
+ severity="high", snippet='OTHER = "sk_live_456"', line_number=9,
+ commit_sha="")
+ )
+ await async_session.commit()
+ view = await load_actions_view(async_session, rid, now=NOW)
+ (back,) = _by_rule(view)["live_secret"]
+ assert back["id"] == secret["id"]
+ assert back["fingerprint"] != secret["fingerprint"]
+
+
+async def test_coverage_state_reads_the_ingest_record(async_session) -> None:
+ from repowise.core.persistence.crud.analysis.actions import _coverage
+ from repowise.core.persistence.models import CoverageFile, CoverageIngest
+
+ rid = await _seed(async_session)
+ async_session.add(
+ CoverageFile(
+ repository_id=rid,
+ file_path="src/core.py",
+ source_format="lcov",
+ line_coverage_pct=50.0,
+ covered_lines_json="[]",
+ total_coverable_lines=10,
+ ingested_commit_sha="zzzz-row",
+ )
+ )
+ async_session.add(
+ CoverageIngest(repository_id=rid, ingested_commit_sha="head", mapping_partial=True)
+ )
+ await async_session.flush()
+
+ state = (await _coverage(async_session, rid, "head"))["coverage"]
+ # The row's sha sorts after "head", which `max()` over rows would have picked.
+ assert (state.status, state.partial, state.files_measured) == ("measured", True, 1)
+ assert (await _coverage(async_session, rid, "newer"))["coverage"].status == "stale"
diff --git a/tests/unit/persistence/test_models.py b/tests/unit/persistence/test_models.py
index b9291290c..feb9f63ed 100644
--- a/tests/unit/persistence/test_models.py
+++ b/tests/unit/persistence/test_models.py
@@ -333,6 +333,7 @@ def test_base_includes_all_models():
"performance_summaries",
"coverage_files",
"coverage_ingests",
+ "action_states",
"test_coverage",
"pipeline_jobs",
"graph_metrics",
diff --git a/tests/unit/server/mcp/test_overview_next_actions.py b/tests/unit/server/mcp/test_overview_next_actions.py
new file mode 100644
index 000000000..ba6993c8d
--- /dev/null
+++ b/tests/unit/server/mcp/test_overview_next_actions.py
@@ -0,0 +1,105 @@
+"""``get_overview``'s ``next_actions``: the stored actions, compacted, never fatal."""
+
+from __future__ import annotations
+
+from datetime import UTC, datetime
+
+import pytest
+
+from repowise.server.mcp_server.tool_overview.actions import compact_actions_view
+
+
+async def _seed(session, rid: str) -> None:
+ from repowise.core.persistence.models import DeadCodeFinding, GitCommit, SecurityFinding
+
+ session.add(
+ GitCommit(repository_id=rid, sha="head", author_name="Ada", author_email="[email protected]",
+ committed_at=datetime(2026, 9, 28, 12, tzinfo=UTC), subject="chore: head")
+ ) # fmt: skip
+ session.add_all(
+ DeadCodeFinding(repository_id=rid, kind="unused_export", file_path="src/dead.py",
+ symbol_name=f"f{i}", lines=10, safe_to_delete=True)
+ for i in range(3)
+ ) # fmt: skip
+ session.add(
+ SecurityFinding(repository_id=rid, file_path="src/settings.py", kind="hardcoded_secret",
+ severity="high", snippet='TOKEN = "sk_live_123"', line_number=4,
+ commit_sha="")
+ ) # fmt: skip
+ await session.commit()
+
+
+async def test_overview_carries_the_stored_actions(setup_mcp, session):
+ from repowise.core.persistence.crud.analysis.actions import load_actions_view
+ from repowise.server.mcp_server import get_overview
+
+ await _seed(session, setup_mcp)
+ result = await get_overview()
+
+ block = result["next_actions"]
+ assert "next_actions_reason" not in result
+ view = await load_actions_view(session, setup_mcp)
+ for horizon in ("week", "quarter"):
+ full = view["horizons"][horizon]
+ assert block[horizon]["total"] == full["total"]
+ assert block[horizon]["by_tier"] == full["by_tier"]
+ # Same rows, same order, as the UI reads.
+ assert [a["id"] for a in block[horizon]["actions"]] == [
+ a["id"] for a in full["actions"][:3]
+ ]
+ assert block["quarter"]["actions"], "the seed should produce actions"
+ for row in block["quarter"]["actions"]:
+ assert set(row) == {"id", "tier", "title", "impact", "done_when", "target"}
+ assert None not in row["target"].values()
+
+
+async def test_a_failed_read_is_omitted_with_a_reason(setup_mcp, monkeypatch):
+ from repowise.server.mcp_server import get_overview
+ from repowise.server.mcp_server.tool_overview import actions as mod
+
+ async def boom(session, repo_id):
+ raise RuntimeError("no such table: action_states")
+
+ monkeypatch.setattr(mod, "load_actions_view", boom)
+ result = await get_overview()
+
+ assert "next_actions" not in result
+ assert "RuntimeError" in result["next_actions_reason"]
+ # The rest of the overview is untouched.
+ assert result["title"] == "Test Repo Overview"
+ assert result["key_modules"]
+
+
+def test_compact_view_keeps_three_rows_and_names_unavailable_stores():
+ rows = [
+ {"id": f"act_{i}", "tier": "plan", "title": f"T{i}", "impact": "i", "done_when": "d",
+ "target": {"kind": "file", "path": f"a{i}.py", "symbol": None}, "why": [], "rule": "x"}
+ for i in range(5)
+ ] # fmt: skip
+ view = {
+ "anchor": "2026-09-28T12:00:00",
+ "horizons": {
+ "week": {"actions": rows, "total": 9, "hidden": 0, "by_tier": {"plan": 9}},
+ "quarter": {"actions": [], "total": 0, "hidden": 0, "by_tier": {}},
+ },
+ "unavailable": {"security": "why", "performance": "why"},
+ }
+
+ block = compact_actions_view(view)
+
+ assert [a["id"] for a in block["week"]["actions"]] == ["act_0", "act_1", "act_2"]
+ assert block["week"]["total"] == 9
+ assert block["week"]["actions"][0]["target"] == {"kind": "file", "path": "a0.py"}
+ assert block["quarter"] == {"total": 0, "by_tier": {}, "actions": []}
+ assert block["unavailable"] == ["performance", "security"]
+
+
+def test_budget_sheds_the_block_before_the_protected_ones():
+ from repowise.server.mcp_server._budget.contracts import _CONTRACTS
+
+ contract = _CONTRACTS["get_overview"]
+ order = contract.shed_order
+ assert order.index("next_actions.quarter.actions[]") < order.index("next_actions")
+ assert "next_actions" not in contract.protected
diff --git a/tests/unit/server/test_actions_route.py b/tests/unit/server/test_actions_route.py
new file mode 100644
index 000000000..d7cbb88fa
--- /dev/null
+++ b/tests/unit/server/test_actions_route.py
@@ -0,0 +1,94 @@
+"""/api/repos/{repo_id}/actions: the response shape and the state round trip."""
+
+from __future__ import annotations
+
+import pytest
+from httpx import AsyncClient
+
+from repowise.core.persistence.database import get_session
+from repowise.core.persistence.models import SecurityFinding
+from repowise.server.routers import actions
+from repowise.server.schemas.actions import ActionsResponse
+from tests.unit.server.conftest import create_test_repo
+
+
+async def actions_client(app, client: AsyncClient) -> AsyncClient:
+ app.include_router(actions.router)
+ return client
+
+
+async def _seed_secret(session_factory, repo_id: str) -> None:
+ async with get_session(session_factory) as session:
+ session.add(
+ SecurityFinding(
+ repository_id=repo_id,
+ file_path="src/settings.py",
+ kind="hardcoded_secret",
+ severity="high",
+ snippet='TOKEN = "sk_live_123"',
+ line_number=4,
+ commit_sha="",
+ )
+ )
+
+
+async def test_get_returns_the_actions_shape(actions_client: AsyncClient, session_factory) -> None:
+ repo = await create_test_repo(actions_client)
+ await _seed_secret(session_factory, repo["id"])
+
+ resp = await actions_client.get(f"/api/repos/{repo['id']}/actions")
+ assert resp.status_code == 200
+ body = ActionsResponse.model_validate(resp.json())
+ assert set(body.horizons) == {"week", "quarter"}
+ (secret,) = [a for a in body.horizons["quarter"].actions if a.rule == "live_secret"]
+ assert secret.tier == "act_now"
+ assert len(body.rules) == 12
+
+
+async def test_put_state_hides_the_action(actions_client: AsyncClient, session_factory) -> None:
+ repo = await create_test_repo(actions_client)
+ await _seed_secret(session_factory, repo["id"])
+ url = f"/api/repos/{repo['id']}/actions"
+ secret = next(
+ a
+ for a in (await actions_client.get(url)).json()["horizons"]["quarter"]["actions"]
+ if a["rule"] == "live_secret"
+ )
+
+ resp = await actions_client.put(
+ f"{url}/{secret['id']}/state",
+ json={"state": "dismissed", "fingerprint": secret["fingerprint"]},
+ )
+ assert resp.status_code == 200
+ assert resp.json() == {"action_id": secret["id"], "state": "dismissed", "until": None}
+
+ quarter = (await actions_client.get(url)).json()["horizons"]["quarter"]
+ assert quarter["hidden"] == 1
+ assert all(a["id"] != secret["id"] for a in quarter["actions"])
+
+ snoozed = await actions_client.put(f"{url}/{secret['id']}/state", json={"state": "snoozed"})
+ assert snoozed.json()["until"] is not None
+ assert (await actions_client.get(url)).json()["horizons"]["quarter"]["hidden"] == 1
+
+ cleared = await actions_client.put(f"{url}/{secret['id']}/state", json={"state": None})
+ assert cleared.status_code == 200
+ assert (await actions_client.get(url)).json()["horizons"]["quarter"]["hidden"] == 0
+
+
+async def test_unknown_repository_is_404(actions_client: AsyncClient) -> None:
+ assert (await actions_client.get("/api/repos/nope/actions")).status_code == 404
+ resp = await actions_client.put(
+ "/api/repos/nope/actions/act_0123456789abcdef/state", json={"state": "dismissed"}
+ )
+ assert resp.status_code == 404
+
+
+async def test_overlong_action_id_is_rejected(actions_client: AsyncClient) -> None:
+ repo = await create_test_repo(actions_client)
+ resp = await actions_client.put(
+ f"/api/repos/{repo['id']}/actions/{'x' * 40}/state", json={"state": "dismissed"}
+ )
+ assert resp.status_code == 422
diff --git a/tests/unit/server/test_wire_vocabulary_parity.py b/tests/unit/server/test_wire_vocabulary_parity.py
index 2902b1c6a..24a844573 100644
--- a/tests/unit/server/test_wire_vocabulary_parity.py
+++ b/tests/unit/server/test_wire_vocabulary_parity.py
@@ -57,3 +57,29 @@ def test_attention_vocabularies_match_python() -> None:
assert ui == set(ATTENTION_ITEM_TYPES)
assert _union_members("OverviewAttentionType", "overview.ts") == set(ATTENTION_ITEM_TYPES)
assert _union_members("OverviewAttentionArea", "overview.ts") == set(AREA_ORDER)
+
+
+def test_action_vocabularies_match_python() -> None:
+ from repowise.core.analysis.actions import (
+ ACTION_RULES,
+ ACTION_STATES,
+ ACTION_SURFACES,
+ ACTION_TIERS,
+ FACT_BASES,
+ HORIZONS,
+ RULE_STATUSES,
+ TARGET_KINDS,
+ )
+
+ pairs = {
+ "ActionRule": ACTION_RULES,
+ "ActionTier": ACTION_TIERS,
+ "ActionFactBasis": FACT_BASES,
+ "ActionSurface": ACTION_SURFACES,
+ "ActionTargetKind": TARGET_KINDS,
+ "ActionRuleStatus": RULE_STATUSES,
+ "ActionStateValue": ACTION_STATES,
+ "ActionHorizonKey": HORIZONS,
+ }
+ for alias, values in pairs.items():
+ assert _union_members(alias, "actions.ts") == set(values), alias