Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(chat): server-built tables and charts from tool results via show_view (#3743)
Raghav Chamadiya45f2f7a8c23a
diff --git a/packages/server/src/repowise/server/chat_artifacts.py b/packages/server/src/repowise/server/chat_artifacts.pyindex 744f25b6d..8c31efef9 100644--- a/packages/server/src/repowise/server/chat_artifacts.py+++ b/packages/server/src/repowise/server/chat_artifacts.py@@ -2,12 +2,19 @@from __future__ import annotations+import refrom datetime import UTC, datetimefrom typing import Anyfrom uuid import NAMESPACE_URL, uuid4, uuid5ARTIFACT_ENVELOPE_VERSION = 1+#: Key a chat turn stamps on the model's copy of a tool result so the model can+#: name it in ``show_view``. Stored data never carries the stamp.+ARTIFACT_ID_FIELD = "artifact_id"++_ARTIFACT_ID = re.compile(r"[0-9a-f]{32}")+_LEGACY_ARTIFACT_TYPE_BY_TOOL = {"get_overview": "overview","get_context": "context",@@ -89,7 +96,15 @@ def create_artifact_envelope(pinned: bool = False,evidence_basis: str = "unknown",) -> dict[str, Any]:- """Create the one durable payload stored for a completed tool call."""+ """Create the one durable payload stored for a completed tool call.++ The id is the server's (``artifact_id``) or a fresh one, never a key of+ ``data``: tool output is stored exactly as the tool returned it.+ """+ if artifact_id is not None and not (+ isinstance(artifact_id, str) and _ARTIFACT_ID.fullmatch(artifact_id)+ ):+ raise ValueError(f"artifact_id must be 32 lowercase hex characters, got {artifact_id!r}")return {"id": artifact_id or uuid4().hex,"version": ARTIFACT_ENVELOPE_VERSION,diff --git a/packages/server/src/repowise/server/chat_grounding.py b/packages/server/src/repowise/server/chat_grounding.pyindex 8640f70e9..ea4fdfbbb 100644--- a/packages/server/src/repowise/server/chat_grounding.py+++ b/packages/server/src/repowise/server/chat_grounding.py@@ -129,8 +129,18 @@ def plan_grounding()-async def run_grounding(plan: GroundingPlan | None, execute: ToolExecutor) -> Grounding | None:- """Run the planned prefetch; a failed read is dropped, never shown."""+async def run_grounding(+ plan: GroundingPlan | None,+ execute: ToolExecutor,+ *,+ unstamp: Callable[[dict[str, Any]], tuple[str | None, dict[str, Any]]] | None = None,+) -> Grounding | None:+ """Run the planned prefetch; a failed read is dropped, never shown.++ ``unstamp`` splits an executor's model-facing result into the server's+ artifact id and the tool's own data, so the stored artifact never carries+ the stamp while the model still sees it.+ """if plan is None:return Nonetry:@@ -142,12 +152,14 @@ async def run_grounding(plan: GroundingPlan | None, execute: ToolExecutor) -> Grlogger.info("chat_grounding_skipped", extra={"tool": plan.tool_name})return None+ artifact_id, data = unstamp(result) if unstamp else (None, result)artifact = create_artifact_envelope(tool_name=plan.tool_name,artifact_type=plan.entry.artifact_type,presentation=plan.entry.presentation,- data=result,+ data=data,title=plan.target,+ artifact_id=artifact_id,evidence_basis=plan.entry.evidence_basis,)return Grounding(diff --git a/packages/server/src/repowise/server/chat_views.py b/packages/server/src/repowise/server/chat_views.pynew file mode 100644index 000000000..d514c36c9--- /dev/null+++ b/packages/server/src/repowise/server/chat_views.py@@ -0,0 +1,710 @@+"""Deterministic chat views: tables and charts built from a turn's tool results.++The model never writes a number into a view. It calls the chat-only+``show_view`` tool naming a tool result already in the turn (by the+``artifact_id`` stamped on it) and a view; a registered builder makes the part+from that result, and ``build_view`` adds provenance, applies the guards and+validates it as a ``ViewPart``. Builders are pure functions registered on the+``chat-view`` seam, so a plugin adds one without editing this module.++Guards every builder passes through: no column or axis keyed by a person, no+risk score as a chart series, and an attribution figure below+``ATTRIBUTION_COVERAGE_FLOOR`` (or without coverage) is refused with its+coverage value instead of drawn.+"""++from __future__ import annotations++import hashlib+import json+import logging+import re+from collections.abc import Callable, Mapping+from dataclasses import dataclass+from typing import Any+from uuid import uuid4++from pydantic import TypeAdapter, ValidationError++from repowise.core.registry.plugins import SeamRegistry, load_plugins+from repowise.server.chat_artifacts import ARTIFACT_ID_FIELD+from repowise.server.schemas.evidence import MAX_WIRE_NUMBER+from repowise.server.schemas.views import (+ VIEW_LIMITS,+ VIEW_SCHEMA_VERSION,+ ViewPart,+ ViewPartList,+)++logger = logging.getLogger(__name__)++SHOW_VIEW_TOOL = "show_view"+ATTRIBUTION_COVERAGE_FLOOR = 0.30++_PART = TypeAdapter(ViewPart)+_SHA = re.compile(r"^[0-9a-f]{7,64}$")+_PERSON = re.compile(+ r"(^|_)(authors?|owners?|ownership|committers?|emails?|users?|username|login|assignees?"+ r"|reviewers?|maintainers?|contributors?|person|people|knowledge_map)(_|$)"+)+_RISK_SCORE = re.compile(r"risk|impact_score|hotspot_score")+_DEFAULT_ROWS = 50+++class ViewError(ValueError):+ """A refusal the model sees as the ``show_view`` result."""++ def __init__(self, message: str, code: str = "view_unavailable", **extra: Any) -> None:+ super().__init__(message)+ self.code = code+ self.extra = extra++ def payload(self) -> dict[str, Any]:+ return {"error": str(self), "error_code": self.code, **self.extra}+++@dataclass(frozen=True)+class ViewArtifact:+ """One tool result of this turn, as builders read it."""++ artifact_id: str+ tool_name: str+ artifact_type: str+ evidence_basis: str+ arguments: dict[str, Any]+ data: dict[str, Any]+++@dataclass(frozen=True)+class ViewBuilder:+ """A pure function from an artifact and options to a part without provenance ids.++ The function returns ``kind``, ``title``, ``basis`` and the kind's fields;+ ``build_view`` adds ``schema_version``, ``id``, ``source``, ``stale`` and+ ``as_of``. ``artifact_types`` None means any artifact.+ """++ build: Callable[[ViewArtifact, Mapping[str, Any]], dict[str, Any]]+ description: str+ artifact_types: frozenset[str] | None = None+ options: frozenset[str] = frozenset({"limit"})+ coverage_metric: str | None = None+++view_builders: SeamRegistry[ViewBuilder] = SeamRegistry("chat-view")+++def register_view_builder(+ name: str,+ *,+ description: str,+ artifact_types: set[str] | frozenset[str] | None = None,+ options: set[str] | frozenset[str] = frozenset({"limit"}),+ coverage_metric: str | None = None,+) -> Callable[[Callable[..., dict[str, Any]]], Callable[..., dict[str, Any]]]:+ """Register a builder as view *name*; the decorated function is returned unchanged."""++ def decorate(fn: Callable[..., dict[str, Any]]) -> Callable[..., dict[str, Any]]:+ view_builders.register(+ name,+ ViewBuilder(+ build=fn,+ description=description,+ artifact_types=frozenset(artifact_types) if artifact_types is not None else None,+ options=frozenset(options),+ coverage_metric=coverage_metric,+ ),+ )+ return fn++ return decorate+++def _view_names() -> list[str]:+ """Registered view names, plugins included (``names`` alone does not load them)."""+ load_plugins()+ return view_builders.names+++def views_for(artifact_type: str) -> list[str]:+ """View names that accept an artifact of *artifact_type*."""+ return [+ name+ for name in _view_names()+ if (types := view_builders.get(name).artifact_types) is None or artifact_type in types+ ]+++def args_hash(arguments: Mapping[str, Any]) -> str:+ canonical = json.dumps(arguments, sort_keys=True, separators=(",", ":"), default=str)+ return hashlib.sha256(canonical.encode("utf-8")).hexdigest()[:16]+++def _meta(data: Mapping[str, Any]) -> Mapping[str, Any]:+ meta = data.get("_meta")+ return meta if isinstance(meta, Mapping) else {}+++def _guard(part: dict[str, Any], spec: ViewBuilder) -> None:+ data = part.get("data", part)+ for column in data.get("columns", []):+ if _PERSON.search(str(column.get("key", ""))):+ raise ViewError(+ f"views never group by person (column {column.get('key')!r})",+ code="person_grouping",+ )+ if part.get("kind") == "chart":+ for key in part.get("series", []):+ if _RISK_SCORE.search(key):+ raise ViewError(+ f"a risk score is never a chart series ({key!r}); show it in a table",+ code="risk_score_series",+ )+ if spec.coverage_metric == "attribution":+ coverage = part.get("coverage")+ ratio = coverage.get("ratio") if isinstance(coverage, Mapping) else None+ if not isinstance(ratio, (int, float)) or ratio < ATTRIBUTION_COVERAGE_FLOOR:+ raise ViewError(+ "insufficient coverage for an attribution figure "+ f"(floor {ATTRIBUTION_COVERAGE_FLOOR})",+ code="insufficient_coverage",+ coverage=ratio,+ )+++def build_view(+ artifact: ViewArtifact,+ view: str,+ options: Mapping[str, Any] | None = None,+ *,+ part_id: str,+) -> dict[str, Any]:+ """Build and validate one view part, or raise ``ViewError``."""+ if view not in _view_names():+ raise ViewError(+ f"unknown view {view!r}; views for this artifact: {views_for(artifact.artifact_type)}",+ code="unknown_view",+ )+ spec = view_builders.get(view)+ if spec.artifact_types is not None and artifact.artifact_type not in spec.artifact_types:+ raise ViewError(+ f"view {view!r} does not apply to a {artifact.artifact_type} result; "+ f"views for it: {views_for(artifact.artifact_type)}",+ code="view_not_applicable",+ )+ if "error" in artifact.data:+ raise ViewError("the artifact is a failed tool call", code="artifact_failed")+ options = dict(options or {})+ if unknown := sorted(set(options) - spec.options):+ raise ViewError(f"unknown options {unknown}; {view!r} takes {sorted(spec.options)}")++ part = spec.build(artifact, options)+ meta = _meta(artifact.data)+ commit = meta.get("indexed_commit")+ part.update(+ schema_version=VIEW_SCHEMA_VERSION,+ id=part_id,+ source={+ "artifact_id": artifact.artifact_id,+ "tool_name": artifact.tool_name,+ "args_hash": args_hash(artifact.arguments),+ },+ stale=bool(meta.get("stale_warning")),+ as_of=commit if isinstance(commit, str) and _SHA.match(commit) else None,+ )+ _guard(part, spec)+ try:+ model = _PART.validate_python(part)+ except ValidationError as exc:+ raise ViewError(+ f"view {view!r} could not be built from this result: {exc.errors()[0]['msg']}",+ code="invalid_view",+ ) from None+ return _PART.dump_python(model, mode="json", exclude_unset=True)+++class TurnViews:+ """The views of one chat turn and the tool results they may be built from.++ ``record`` stamps each tool result with its artifact id before the model+ sees it; ``unstamp`` gives the stored side the server's id and the tool's+ own data back. ``show`` is the ``show_view`` tool. ``parts`` holds the+ validated views in order.+ """++ def __init__(self) -> None:+ self._artifacts: dict[str, ViewArtifact] = {}+ # The exact stamped dicts handed out, so a tool's own ``artifact_id``+ # field is never mistaken for a stamp.+ self._stamped: dict[str, dict[str, Any]] = {}+ self.parts: list[dict[str, Any]] = []++ def record(+ self,+ tool_name: str,+ arguments: Mapping[str, Any],+ result: Any,+ *,+ artifact_type: str = "generic",+ evidence_basis: str = "unknown",+ ) -> Any:+ """Remember *result* and return it stamped with ``artifact_id``."""+ if not isinstance(result, dict):+ return result+ artifact_id = uuid4().hex+ self._artifacts[artifact_id] = ViewArtifact(+ artifact_id=artifact_id,+ tool_name=tool_name,+ artifact_type=artifact_type,+ evidence_basis=evidence_basis,+ arguments=dict(arguments),+ data=result,+ )+ stamped = {**result, ARTIFACT_ID_FIELD: artifact_id}+ self._stamped[artifact_id] = stamped+ return stamped++ def unstamp(self, result: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:+ """The server's id and unstamped data for a ``record`` result; else ``(None, result)``."""+ artifact_id = result.get(ARTIFACT_ID_FIELD)+ if isinstance(artifact_id, str) and self._stamped.get(artifact_id) is result:+ return artifact_id, self._artifacts[artifact_id].data+ return None, result++ def show(self, arguments: Mapping[str, Any]) -> dict[str, Any]:+ """Run ``show_view``: a short receipt on success, an error payload otherwise."""+ try:+ part = self._build(arguments)+ except ViewError as exc:+ return exc.payload()+ except Exception:+ # A builder bug (or a plugin's) is the model's error to see, not the turn's end.+ logger.exception("chat_view_builder_failed", extra={"view": arguments.get("view")})+ return ViewError("the view builder failed", code="builder_failed").payload()+ self.parts.append(part)+ receipt = {"view_id": part["id"], "kind": part["kind"], "title": part["title"]}+ if "summary" in part:+ receipt["summary"] = part["summary"]+ return receipt++ def _build(self, arguments: Mapping[str, Any]) -> dict[str, Any]:+ artifact_id = arguments.get("artifact_id")+ view = arguments.get("view")+ options = arguments.get("options") or {}+ artifact = self._artifacts.get(artifact_id) if isinstance(artifact_id, str) else None+ if artifact is None:+ raise ViewError(+ f"no tool result with artifact_id {artifact_id!r} in this turn; "+ "call the tool again and use the artifact_id on its result",+ code="unknown_artifact",+ )+ if not isinstance(view, str) or not isinstance(options, Mapping):+ raise ViewError("view must be a string and options an object", code="bad_arguments")+ part = build_view(artifact, view, options, part_id=f"v{len(self.parts) + 1}")+ try:+ ViewPartList.model_validate([*self.parts, part])+ except ValidationError:+ raise ViewError(+ f"a turn holds at most {VIEW_LIMITS['parts']} views", code="view_limit"+ ) from None+ return part++ def event(self, tool_id: str, result: Mapping[str, Any]) -> dict[str, Any] | None:+ """The SSE ``view`` payload for a successful ``show_view`` result."""+ view_id = result.get("view_id")+ part = next((p for p in self.parts if p["id"] == view_id), None)+ return None if part is None else {"type": "view", "tool_id": tool_id, "view": part}+++def show_view_schema(artifact_types: list[str] | None = None) -> dict[str, Any]:+ """OpenAI-format definition of the chat-only ``show_view`` tool."""+ names = sorted(+ {n for t in artifact_types for n in views_for(t)} if artifact_types else _view_names()+ )+ return {+ "type": "function",+ "function": {+ "name": SHOW_VIEW_TOOL,+ "description": (+ "Show a table or chart built by the server from a tool result already "+ "returned in this turn. Pass that result's artifact_id. Never restate the "+ "numbers yourself; the view carries them. Views: " + ", ".join(names) + ". "+ "`table` takes options path (dotted path to a list or map in the result), "+ "columns and limit."+ ),+ "parameters": {+ "type": "object",+ "properties": {+ "artifact_id": {"type": "string"},+ "view": {"type": "string", "enum": names},+ "options": {"type": "object"},+ },+ "required": ["artifact_id", "view"],+ },+ },+ }+++# ---------------------------------------------------------------------------+# Builders+# ---------------------------------------------------------------------------+++def _basis(kind: str, source: str) -> dict[str, str]:+ return {"kind": kind, "source": source}+++def _tool_basis(artifact: ViewArtifact) -> dict[str, str]:+ declared = artifact.data.get("evidence_kind") or artifact.data.get("basis")+ kind = declared if declared in ("measured", "inferred", "declared") else artifact.evidence_basis+ if kind not in ("measured", "inferred", "declared"):+ return _basis("unresolved", f"{artifact.tool_name} declares no basis")+ return _basis(kind, artifact.tool_name)+++def _limit(options: Mapping[str, Any], default: int = _DEFAULT_ROWS, cap: int | None = None) -> int:+ cap = cap or VIEW_LIMITS["rows"]+ value = options.get("limit", default)+ if isinstance(value, bool) or not isinstance(value, int) or value < 1:+ raise ViewError("limit must be a positive integer", code="bad_arguments")+ return min(value, cap)+++def _wire(value: Any) -> Any:+ """A source value as a cell, or ``...`` when it cannot be one."""+ if value is None or isinstance(value, str):+ return value+ if isinstance(value, bool):+ return "true" if value else "false"+ if isinstance(value, (int, float)) and abs(value) <= MAX_WIRE_NUMBER and value == value:+ return value+ return ...+++def _cell(key: str, value: Any) -> Any:+ if key in ("file_path", "path") and isinstance(value, str) and value:+ return {"type": "file", "id": value}+ return _wire(value)+++def _label(key: str) -> str:+ return key.replace("_", " ").capitalize()+++def _node(data: Any, path: str) -> Any:+ node = data+ for segment in path.split("."):+ if isinstance(node, Mapping) and segment in node:+ node = node[segment]+ elif isinstance(node, list) and segment.isdigit() and int(segment) < len(node):+ node = node[int(segment)]+ else:+ raise ViewError(f"no {path!r} in the artifact", code="bad_path")+ return node+++def _tabular(node: Any) -> list[dict[str, Any]] | None:+ """Rows from a list of objects, or a map of objects keyed by id."""+ if isinstance(node, list) and node and all(isinstance(row, Mapping) for row in node):+ return [dict(row) for row in node]+ if isinstance(node, Mapping) and node and all(isinstance(v, Mapping) for v in node.values()):+ return [{"id": key, **value} for key, value in node.items()]+ return None+++def _table_paths(data: Mapping[str, Any], prefix: str = "", depth: int = 0) -> list[str]:+ paths: list[str] = []+ for key, value in data.items():+ if key == "_meta" or _PERSON.search(key):+ continue+ path = f"{prefix}{key}"+ if _tabular(value) is not None:+ paths.append(path)+ elif isinstance(value, Mapping) and depth < 2:+ paths.extend(_table_paths(value, f"{path}.", depth + 1))+ return paths+++@register_view_builder(+ "table",+ description="Any list or map of objects in a result, as a table.",+ options={"path", "columns", "limit"},+)+def table_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ path = options.get("path")+ if path is None:+ candidates = _table_paths(artifact.data)+ if len(candidates) != 1:+ raise ViewError(+ f"pass options.path; tables in this result: {candidates}", code="bad_path"+ )+ path = candidates[0]+ if not isinstance(path, str) or any(_PERSON.search(seg) for seg in path.split(".")):+ raise ViewError(f"views never group by person ({path!r})", code="person_grouping")+ node = _node(artifact.data, path)+ rows = _tabular(node)+ if rows is None:+ raise ViewError(f"{path!r} is not a list or map of objects", code="bad_path")++ wanted = options.get("columns")+ if wanted is not None and not (+ isinstance(wanted, list) and all(isinstance(k, str) for k in wanted)+ ):+ raise ViewError("columns must be a list of keys", code="bad_arguments")+ keys = list(dict.fromkeys(k for row in rows for k in row))+ # A column is a key whose every value is a cell; nested values and people are left out.+ keys = [+ k+ for k in keys+ if not _PERSON.search(k)+ and re.fullmatch(r"[a-z][a-z0-9_]{0,63}", k)+ and all(_cell(k, row.get(k)) is not ... for row in rows)+ ]+ if wanted is not None:+ if missing := [k for k in wanted if k not in keys]:+ raise ViewError(f"columns not available as cells: {missing}", code="bad_arguments")+ keys = list(dict.fromkeys(wanted))+ keys = keys[: VIEW_LIMITS["columns"]]+ if not keys:+ raise ViewError(f"{path!r} has no scalar fields to show", code="bad_path")++ shown = rows[: _limit(options)]+ parent_path, _, leaf = path.rpartition(".")+ parent = _node(artifact.data, parent_path) if parent_path else artifact.data+ total = parent.get(f"{leaf}_total") if isinstance(parent, Mapping) else None+ total_rows = total if isinstance(total, int) and total >= len(rows) else len(rows)+ return {+ "kind": "table",+ "title": f"{artifact.tool_name}: {path}",+ "summary": f"{len(shown)} of {total_rows} rows.",+ "basis": _tool_basis(artifact),+ "columns": [{"key": k, "label": _label(k)} for k in keys],+ "rows": [{k: _cell(k, row.get(k)) for k in keys} for row in shown],+ "total_rows": total_rows,+ "truncated": total_rows > len(shown),+ }+++def _chart(+ *,+ title: str,+ summary: str,+ basis: dict[str, str],+ x: tuple[str, str],+ series: list[tuple[str, str]],+ unit: str,+ rows: list[dict[str, Any]],+ total_rows: int | None = None,+ chart_type: str = "bar",+) -> dict[str, Any]:+ if not rows:+ raise ViewError("this result has nothing to chart", code="no_data")+ total = len(rows) if total_rows is None else max(total_rows, len(rows))+ return {+ "kind": "chart",+ "chart_type": chart_type,+ "title": title,+ "summary": summary,+ "basis": basis,+ "x": x[0],+ "series": [key for key, _ in series],+ "data": {+ "columns": [+ {"key": x[0], "label": x[1]},+ *({"key": key, "label": label, "unit": unit} for key, label in series),+ ],+ "rows": rows,+ "total_rows": total,+ "truncated": total > len(rows),+ },+ }+++_HEALTH_BANDS = ("at_risk", "needs_work", "fair", "good", "excellent")+++@register_view_builder(+ "health.bands",+ description="Files per health band.",+ artifact_types={"health", "overview"},+ options=frozenset(),+)+def health_bands_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ data = artifact.data+ distribution = data.get("distribution") or (data.get("code_health") or {}).get("distribution")+ bands = distribution.get("bands") if isinstance(distribution, Mapping) else None+ if not isinstance(bands, Mapping):+ raise ViewError("this result has no health distribution; call get_health with no targets")+ rows = [+ {"band": band.replace("_", " "), "files": bands[band]["files"]}+ for band in _HEALTH_BANDS+ if isinstance(bands.get(band), Mapping) and isinstance(bands[band].get("files"), int)+ ]+ total = sum(row["files"] for row in rows)+ return _chart(+ title="Files by health band",+ summary=f"{total} files across {len(rows)} health bands.",+ basis=_basis("inferred", "health engine"),+ x=("band", "Health band"),+ series=[("files", "Files")],+ unit="files",+ rows=rows,+ )+++@register_view_builder(+ "health.trend",+ description="Average and hotspot health over recent snapshots.",+ artifact_types={"health"},+ options=frozenset(),+)+def health_trend_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ trend = artifact.data.get("trend")+ recent = trend.get("recent") if isinstance(trend, Mapping) else None+ if not isinstance(recent, list) or not recent:+ raise ViewError('this result has no trend; call get_health(include=["trend"])')+ snapshots = sorted(+ (s for s in recent if isinstance(s, Mapping) and isinstance(s.get("taken_at"), str)),+ key=lambda s: s["taken_at"],+ )+ rows = [+ {+ "taken_at": s["taken_at"],+ "average_health": _wire(s.get("average_health")),+ "hotspot_health": _wire(s.get("hotspot_health")),+ }+ for s in snapshots+ ]+ total = trend.get("recent_total")+ return _chart(+ chart_type="line",+ title="Health over recent snapshots",+ summary=f"{len(rows)} health snapshots, oldest first.",+ basis=_basis("inferred", "health snapshots"),+ x=("taken_at", "Snapshot"),+ series=[("average_health", "Average health"), ("hotspot_health", "Hotspot health")],+ unit="score",+ rows=rows,+ total_rows=total if isinstance(total, int) else None,+ )+++@register_view_builder(+ "health.test_coverage",+ description="Measured line coverage per file, from the ingested coverage report.",+ artifact_types={"health"},+)+def health_test_coverage_view(+ artifact: ViewArtifact, options: Mapping[str, Any]+) -> dict[str, Any]:+ coverage = artifact.data.get("coverage")+ files = coverage.get("files") if isinstance(coverage, Mapping) else None+ if not isinstance(files, list):+ raise ViewError('this result has no coverage; call get_health(include=["coverage"])')+ usable = [f for f in files if isinstance(f, Mapping) and f.get("file_path")]+ shown = usable[: _limit(options, cap=100)]+ rows = [+ {+ "file": {"type": "file", "id": f["file_path"]},+ "line_coverage": _wire(f.get("line_coverage_pct")),+ }+ for f in shown+ ]+ summary_pct = (coverage.get("summary") or {}).get("line_coverage_pct")+ total = coverage.get("files_total")+ total = max(total, len(usable)) if isinstance(total, int) else len(usable)+ part = _chart(+ title="Line coverage by file",+ summary=f"{len(rows)} files from the coverage report.",+ basis=_basis("measured", "coverage report"),+ x=("file", "File"),+ series=[("line_coverage", "Line coverage")],+ unit="%",+ rows=rows,+ total_rows=total,+ )+ if isinstance(summary_pct, (int, float)) and 0 <= summary_pct <= 100:+ # Rounded so the percentage converts without float noise (88.84 -> 0.8884).+ part["coverage"] = {"metric": "test_reach", "ratio": round(summary_pct / 100, 6)}+ return part+++@register_view_builder(+ "dead_code.by_tier",+ description="Dead-code findings per confidence tier.",+ artifact_types={"dead_code"},+ options=frozenset(),+)+def dead_code_by_tier_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ tiers = artifact.data.get("tiers")+ if not isinstance(tiers, Mapping):+ raise ViewError("this result has no confidence tiers")+ rows = [+ {"tier": tier, "findings": tiers[tier]["count"]}+ for tier in ("high", "medium", "low")+ if isinstance(tiers.get(tier), Mapping) and isinstance(tiers[tier].get("count"), int)+ ]+ return _chart(+ title="Dead-code findings by tier",+ summary=f"{sum(r['findings'] for r in rows)} findings kept by the call's filters.",+ basis=_basis("inferred", "reachability graph"),+ x=("tier", "Confidence tier"),+ series=[("findings", "Findings")],+ unit="findings",+ rows=rows,+ )+++@register_view_builder(+ "dead_code.by_kind",+ description="Open dead-code findings per kind.",+ artifact_types={"dead_code"},+ options=frozenset(),+)+def dead_code_by_kind_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ by_kind = (artifact.data.get("summary") or {}).get("by_kind")+ if not isinstance(by_kind, Mapping) or not by_kind:+ raise ViewError("this result has no findings by kind")+ rows = [+ {"kind": kind, "findings": count}+ for kind, count in by_kind.items()+ if isinstance(count, int) and not isinstance(count, bool)+ ]+ return _chart(+ title="Dead-code findings by kind",+ summary=f"{sum(r['findings'] for r in rows)} open findings.",+ basis=_basis("inferred", "reachability graph"),+ x=("kind", "Kind"),+ series=[("findings", "Findings")],+ unit="findings",+ rows=rows,+ )+++@register_view_builder(+ "risk.hotspots",+ description="Bug-fix commits on the repository's top hotspots.",+ artifact_types={"risk"},+)+def risk_hotspots_view(artifact: ViewArtifact, options: Mapping[str, Any]) -> dict[str, Any]:+ hotspots = artifact.data.get("global_hotspots")+ if not isinstance(hotspots, list) or not hotspots:+ raise ViewError("this result has no global hotspots")+ usable = [h for h in hotspots if isinstance(h, Mapping) and h.get("file_path")]+ shown = usable[: _limit(options, cap=100)]+ rows = [+ {"file": {"type": "file", "id": h["file_path"]}, "fix_count": _wire(h.get("fix_count"))}+ for h in shown+ ]+ total = artifact.data.get("global_hotspots_total")+ total = max(total, len(usable)) if isinstance(total, int) else len(usable)+ return _chart(+ title="Bug fixes on top hotspots",+ summary=f"Bug-fix commits on {len(rows)} hotspot files.",+ basis=_basis("measured", "git history"),+ x=("file", "File"),+ series=[("fix_count", "Bug-fix commits")],+ unit="commits",+ rows=rows,+ total_rows=total,+ )diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 7842c46a5..bfa9e65b2 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -45,6 +45,7 @@ from repowise.server.chat_tools import (get_tool_catalog,get_tool_schemas_for_llm,)+from repowise.server.chat_views import SHOW_VIEW_TOOL, TurnViews, show_view_schemafrom repowise.server.deps import (get_db_session,request_principal,@@ -209,10 +210,13 @@ class _AgentTurn:self.tool_calls: list[dict[str, Any]] = []self.aborted = Falseself.truncated = False+ self.views = TurnViews()async def execute(self, name: str, args: dict) -> dict:"""Run one tool scoped to this repo; also handed to providers that loop internally."""- return await execute_tool(+ if name == SHOW_VIEW_TOOL:+ return self.views.show(args)+ result = await execute_tool(name,args,repo_path=self.repo_path,@@ -220,6 +224,13 @@ class _AgentTurn:principal=self.principal,repo_id=self.repo_id,)+ return self.views.record(+ name,+ args,+ result,+ artifact_type=get_artifact_type(name, self.repo_path),+ evidence_basis=get_artifact_evidence_basis(name, self.repo_path),+ )async def ground(self, page_context: Any, tool_catalog: list) -> str | None:"""Make the one read the page already justifies, before the first model turn.@@ -229,7 +240,7 @@ class _AgentTurn:plan = plan_grounding(page_context, (tool.entry for tool in tool_catalog))if plan is not None and _history_has_call(self.llm_messages, plan.tool_name, plan.arguments):plan = None- grounding = await run_grounding(plan, self.execute)+ grounding = await run_grounding(plan, self.execute, unstamp=self.views.unstamp)if grounding is None:return Noneself.llm_messages.extend(grounding.llm_messages())@@ -270,6 +281,8 @@ class _AgentTurn:}if self.truncated:content["truncated"] = True+ if self.views.parts:+ content["views"] = self.views.parts# A turn that read nothing, or read only failures, has no next# step to propose.follow_ups = follow_up_suggestions(self.tool_calls)@@ -350,17 +363,19 @@ class _AgentTurn:) -> str:"""Record one tool result as a stored call and return its SSE event."""artifact_type = get_artifact_type(name, self.repo_path)- summary = _build_tool_summary(name, result)+ artifact_id, data = self.views.unstamp(result)+ summary = _build_tool_summary(name, data)artifact = create_artifact_envelope(tool_name=name,artifact_type=artifact_type,presentation=get_artifact_presentation(name, self.repo_path),- data=result,+ data=data,title=summary,+ artifact_id=artifact_id,evidence_basis=get_artifact_evidence_basis(name, self.repo_path),)self.tool_calls.append(_stored_tool_call(tool_id, name, arguments, summary, artifact))- return _sse_event(+ sse = _sse_event("data",{"type": "tool_result",@@ -370,6 +385,8 @@ class _AgentTurn:"artifact": artifact,},)+ view = self.views.event(tool_id, result) if name == SHOW_VIEW_TOOL else None+ return sse if view is None else sse + _sse_event("data", view)@router.post("/api/repos/{repo_id}/chat/messages")@@ -421,6 +438,10 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):tool_catalog = get_tool_catalog(repo_path, principal)system_prompt = _build_system_prompt(repo_name, repo_path, tool_catalog, body.context)tool_schemas = get_tool_schemas_for_llm(repo_path, principal)+ if tool_catalog:+ tool_schemas.append(+ show_view_schema([tool.entry.artifact_type for tool in tool_catalog])+ )turn = _AgentTurn(repo_path, repo_alias, provider, llm_messages, principal=principal, repo_id=repo_iddiff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex ed4179870..9755609d6 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -12,6 +12,7 @@ import type { Hotspot } from "./git.js";import type { DeadCodeFinding } from "./dead-code.js";import type { DecisionRecord } from "./decisions.js";import type { EvidenceCard } from "./cards.js";+import type { ViewPart } from "./views.js";// ---------------------------------------------------------------------------// Product context surrounding a chat composer@@ -127,6 +128,8 @@ export interface ChatMessage {follow_ups?: ChatSuggestion[];/** Evidence cards for this turn, unvalidated until parsed. */cards?: unknown[];+ /** View parts `show_view` built this turn, unvalidated until parsed. */+ views?: unknown[];};created_at: string;}@@ -692,6 +695,9 @@ export type ChatSSEEvent =artifact: ChatArtifact;citations?: ChatCitation[];}+ /** A table or chart the server built from a tool result of this turn,+ * sent right after the `show_view` call's `tool_result`. */+ | { type: "view"; tool_id: string; view: ViewPart }/** Every turn ended in a tool call; `done` still follows. */| { type: "truncated"; loops: number }/** Next steps for the turn that just finished, sent just before `done`.diff --git a/packages/types/src/views.ts b/packages/types/src/views.tsindex 7e7686cfc..f197bfab5 100644--- a/packages/types/src/views.ts+++ b/packages/types/src/views.ts@@ -22,6 +22,9 @@ import type { CardBasis, CardRef } from "./evidence.js";export const VIEW_SCHEMA_VERSION = 1 as const;+/** The chat-only tool that builds views. Its call is plumbing, not evidence. */+export const SHOW_VIEW_TOOL = "show_view";+/** Chart forms. A new form is added with its builder, never as a general grammar. */export const CHART_TYPES = ["bar", "stacked_bar", "line", "donut"] as const;export type ChartType = (typeof CHART_TYPES)[number];diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts b/packages/web/src/lib/chat/to-chat-ui-messages.test.tsindex 19ca0b23c..b8ba33a50 100644--- a/packages/web/src/lib/chat/to-chat-ui-messages.test.ts+++ b/packages/web/src/lib/chat/to-chat-ui-messages.test.ts@@ -3,6 +3,28 @@ import type { ChatMessageResponse } from "@/lib/api/types";import { toChatUiMessages } from "./to-chat-ui-messages";describe("toChatUiMessages", () => {+ it("hides a stored show_view call and tolerates stored views", () => {+ const stored: ChatMessageResponse[] = [+ {+ id: "m1",+ conversation_id: "c1",+ role: "assistant",+ content: {+ tool_calls: [+ { id: "t1", name: "get_risk", result: { score: 1 } },+ { id: "t2", name: "show_view", result: { view_id: "v1" } },+ ],+ views: [{ id: "v1", kind: "table" }],+ },+ created_at: "2026-10-14T00:00:00Z",+ },+ ];++ expect(toChatUiMessages(stored)[0]?.toolCalls.map((call) => call.name)).toEqual([+ "get_risk",+ ]);+ });+it.each([["an errored read", { error: "no git metadata available" }, "error"],["a good read", { score: 8.4 }, "done"],diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.tsindex d9c654afa..e730704df 100644--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts@@ -2,6 +2,7 @@ import type { ChatMessageResponse } from "@/lib/api/types";import type { ChatUIMessage } from "@repowise-dev/types/chat";import { getLegacyChatArtifactType } from "@repowise-dev/ui/chat";import { parseEvidenceCards } from "@repowise-dev/api-client/cards";+import { SHOW_VIEW_TOOL } from "@repowise-dev/types/views";/** Stored cards are untrusted wire data; only the ones that validate render. */function storedCards(message: ChatMessageResponse): Pick<ChatUIMessage, "cards"> {@@ -18,44 +19,47 @@ export function toChatUiMessages(serverId: message.id,role: message.role,text: message.content.text ?? "",- toolCalls: (message.content.tool_calls ?? []).map((toolCall) => ({- id: toolCall.id,- name: toolCall.name,- arguments: toolCall.arguments ?? {},- result: toolCall.result,- summary: toolCall.summary,- ...(toolCall.artifact- ? { artifact: toolCall.artifact }- : toolCall.result- ? {- artifact: {- id: `legacy-${message.id}-${toolCall.id}`,- version: 1 as const,- type:- toolCall.artifact_type ??- getLegacyChatArtifactType(toolCall.name),- tool_name: toolCall.name,- title: toolCall.summary ?? toolCall.name,- presentation:- toolCall.artifact_type ??- getLegacyChatArtifactType(toolCall.name),- evidence: { basis: "unknown" },- pinned: false,- data: toolCall.result,- },- }- : {}),- // The wire never persists a status, so reload it from the same `error`- // key the live stream reads. Without this a failed read comes back from- // storage looking like a good one, and is cited as evidence again.- status:- typeof toolCall.result === "object" &&- toolCall.result !== null &&- "error" in toolCall.result- ? ("error" as const)- : ("done" as const),- ...(toolCall.origin ? { origin: toolCall.origin } : {}),- })),+ // A show_view call is plumbing for a view, not a read; it is not shown.+ toolCalls: (message.content.tool_calls ?? [])+ .filter((toolCall) => toolCall.name !== SHOW_VIEW_TOOL)+ .map((toolCall) => ({+ id: toolCall.id,+ name: toolCall.name,+ arguments: toolCall.arguments ?? {},+ result: toolCall.result,+ summary: toolCall.summary,+ ...(toolCall.artifact+ ? { artifact: toolCall.artifact }+ : toolCall.result+ ? {+ artifact: {+ id: `legacy-${message.id}-${toolCall.id}`,+ version: 1 as const,+ type:+ toolCall.artifact_type ??+ getLegacyChatArtifactType(toolCall.name),+ tool_name: toolCall.name,+ title: toolCall.summary ?? toolCall.name,+ presentation:+ toolCall.artifact_type ??+ getLegacyChatArtifactType(toolCall.name),+ evidence: { basis: "unknown" },+ pinned: false,+ data: toolCall.result,+ },+ }+ : {}),+ // The wire never persists a status, so reload it from the same `error`+ // key the live stream reads. Without this a failed read comes back from+ // storage looking like a good one, and is cited as evidence again.+ status:+ typeof toolCall.result === "object" &&+ toolCall.result !== null &&+ "error" in toolCall.result+ ? ("error" as const)+ : ("done" as const),+ ...(toolCall.origin ? { origin: toolCall.origin } : {}),+ })),isStreaming: false,...(message.content.provider ? { provider: message.content.provider } : {}),...(message.content.model ? { model: message.content.model } : {}),diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsxindex 53a9cb9fb..27b150657 100644--- a/packages/web/src/lib/hooks/use-chat.test.tsx+++ b/packages/web/src/lib/hooks/use-chat.test.tsx@@ -393,4 +393,30 @@ describe("useChat grounding and truncation events", () => {expect(result.current.messages.at(-1)?.isStreaming).toBe(false);expect(result.current.error).toBeNull();});++ it("shows no step for a show_view call and ignores its view event", async () => {+ const push = streamed([+ { type: "tool_start", tool_id: "t2", tool_name: "show_view", input: {} },+ {+ type: "tool_result",+ tool_id: "t2",+ tool_name: "show_view",+ summary: "show_view",+ artifact: { ...artifact, id: "art-2", tool_name: "show_view", data: { view_id: "v1" } },+ },+ { type: "view", tool_id: "t2", view: { id: "v1", kind: "table" } },+ { type: "done", conversation_id: "c1", message_id: "m1" },+ ]);+ const { result } = renderHook(() => useChat("r1"));++ await act(async () => {+ const sending = result.current.sendMessage("chart it");+ await push();+ await sending;+ });++ expect(result.current.messages.at(-1)?.toolCalls).toEqual([]);+ expect(result.current.messages.at(-1)?.isStreaming).toBe(false);+ expect(result.current.error).toBeNull();+ });});diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.tsindex 0fcea23db..a9b8c03fb 100644--- a/packages/web/src/lib/hooks/use-chat.ts+++ b/packages/web/src/lib/hooks/use-chat.ts@@ -9,6 +9,7 @@ import type {ChatUIToolCall as ChatToolCall,ChatUIMessage as ChatMessage,} from "@repowise-dev/types/chat";+import { SHOW_VIEW_TOOL } from "@repowise-dev/types/views";import { toFriendlyMessage } from "@repowise-dev/ui/lib/errors";import { toChatUiMessages } from "@/lib/chat/to-chat-ui-messages";@@ -244,6 +245,9 @@ export function useChat(repoId: string) {};case "tool_start":+ // Views have no renderer yet; without a row here the+ // matching tool_result and view events are no-ops too.+ if (ev.tool_name === SHOW_VIEW_TOOL) return m;return {...m,toolCalls: [diff --git a/tests/unit/server/test_chat_router.py b/tests/unit/server/test_chat_router.pyindex d6232b043..44f57e362 100644--- a/tests/unit/server/test_chat_router.py+++ b/tests/unit/server/test_chat_router.py@@ -155,7 +155,11 @@ async def test_file_page_grounds_before_the_first_model_turn():assert [message["role"] for message in sent[-3:]] == ["user", "assistant", "tool"]assert sent[-2]["tool_calls"][0]["id"] == grounding["tool_id"]assert sent[-1]["tool_call_id"] == grounding["tool_id"]- assert json.loads(sent[-1]["content"]) == _CONTEXT_RESULT+ # The model sees the result stamped with the id show_view takes; the artifact does not.+ assert json.loads(sent[-1]["content"]) == {+ **_CONTEXT_RESULT,+ "artifact_id": grounding["artifact"]["id"],+ }assert "file page" in provider.calls[0]["system_prompt"]stored = await _stored_messages(app, events[-1]["conversation_id"])diff --git a/tests/unit/server/test_chat_views.py b/tests/unit/server/test_chat_views.pynew file mode 100644index 000000000..693f007fd--- /dev/null+++ b/tests/unit/server/test_chat_views.py@@ -0,0 +1,534 @@+"""Chat view builders: exact source numbers, guards, ``show_view`` errors and the SSE event."""++from __future__ import annotations++import json+from pathlib import Path+from typing import Any+from unittest.mock import AsyncMock, patch++import pytest++from repowise.core.providers.llm.base import ChatStreamEvent, ChatToolCall+from repowise.server.chat_artifacts import ARTIFACT_ID_FIELD, create_artifact_envelope+from repowise.server.chat_tools import get_tool_catalog+from repowise.server.chat_views import (+ SHOW_VIEW_TOOL,+ TurnViews,+ ViewArtifact,+ ViewError,+ args_hash,+ build_view,+ register_view_builder,+ show_view_schema,+ view_builders,+)+from repowise.server.mcp_server._tool_selection import get_registered_tool+from repowise.server.schemas.views import ViewPartList+from tests.unit.server.test_chat_router import _PROVIDER, _ScriptedProvider, _stored_messages+from tests.unit.server.test_chat_stream_terminal_event import _data_events, _make_app, _post++_FIXTURE = (+ Path(__file__).resolve().parents[3] / "packages" / "types" / "fixtures" / "views.conformance.json"+)+FIELDS: dict[str, list[str]] = json.loads(_FIXTURE.read_text(encoding="utf-8"))["fields"]++_META = {"indexed_commit": "4c1e31fe3a9b", "stale_warning": "Index is behind live HEAD."}++HEALTH = {+ "distribution": {+ "total_files": 5034,+ "bands": {+ "at_risk": {"files": 168, "nloc": 101306, "pct": 11.3},+ "needs_work": {"files": 128, "nloc": 53535, "pct": 6},+ "fair": {"files": 268, "nloc": 87572, "pct": 9.8},+ "good": {"files": 504, "nloc": 124420, "pct": 13.9},+ "excellent": {"files": 3966, "nloc": 527275, "pct": 59},+ },+ },+ "trend": {+ "recent": [+ {"taken_at": "2026-10-11T17:11:16", "hotspot_health": 6.47, "average_health": 7.88},+ {"taken_at": "2026-10-11T04:34:21", "hotspot_health": 6.16, "average_health": 7.74},+ {"taken_at": "2026-10-10T18:36:12", "hotspot_health": 6.71, "average_health": 8.02},+ ],+ "recent_total": 10,+ },+ "coverage": {+ "summary": {"line_coverage_pct": 88.84},+ "files": [+ {"file_path": "a.py", "line_coverage_pct": 100, "covered_line_count": 9},+ {"file_path": "b.py", "line_coverage_pct": 96.36, "covered_line_count": 53},+ ],+ "files_total": 1382,+ },+ "high_leverage_files": [+ {"file_path": "cmd.py", "score": 1, "max_ccn": 279, "primary_owner": "Someone"},+ {"file_path": "init.py", "score": 1.01, "max_ccn": 160, "primary_owner": "Someone"},+ ],+ "high_leverage_files_total": 770,+ "_meta": _META,+}++DEAD_CODE = {+ "summary": {"total_findings": 15, "by_kind": {"unreachable_file": 4, "unused_export": 11}},+ "tiers": {+ "high": {"count": 0, "lines": 0, "findings": []},+ "medium": {+ "count": 15,+ "lines": 545,+ "findings": [+ {"file_path": "x.py", "confidence": 0.4, "primary_owner": "Someone", "lines": 307}+ ],+ },+ "low": {"count": 0, "lines": 0, "findings": []},+ },+ "_meta": {"indexed_commit": "4c1e31fe3a9b"},+}++RISK = {+ "targets": {+ "src/a.py": {"dependents_count": 12, "hotspot_score": 0.9458, "primary_owner": "Someone"},+ "src/b.py": {"dependents_count": 6, "hotspot_score": 0.6087, "primary_owner": "Someone"},+ },+ "global_hotspots": [+ {"file_path": "analyzer.py", "hotspot_score": 0.9998, "fix_count": 56, "primary_owner": "S"},+ {"file_path": "parser.py", "hotspot_score": 0.9992, "fix_count": 48, "primary_owner": "S"},+ ],+ "global_hotspots_total": 1037,+ "_meta": _META,+}+++def _artifact(data: dict, artifact_type: str, tool: str, basis: str = "inferred") -> ViewArtifact:+ return ViewArtifact(+ artifact_id="a1",+ tool_name=tool,+ artifact_type=artifact_type,+ evidence_basis=basis,+ arguments={"limit": 2},+ data=data,+ )+++def _build(data: dict, artifact_type: str, tool: str, view: str, **options: Any) -> dict:+ part = build_view(_artifact(data, artifact_type, tool), view, options, part_id="v1")+ ViewPartList.model_validate([part])+ kind = "TableView" if part["kind"] == "table" else "ChartView"+ assert set(part) <= set(FIELDS[kind])+ return part+++def _series(part: dict, key: str) -> list:+ return [row[key] for row in part["data"]["rows"]]+++# ---------------------------------------------------------------------------+# Builders: every number is the source number+# ---------------------------------------------------------------------------+++def test_health_bands_plots_each_band_file_count():+ part = _build(HEALTH, "health", "get_health", "health.bands")+ bands = HEALTH["distribution"]["bands"]+ assert _series(part, "files") == [bands[b]["files"] for b in bands]+ assert part["source"] == {+ "artifact_id": "a1",+ "tool_name": "get_health",+ "args_hash": args_hash({"limit": 2}),+ }+ assert part["stale"] is True+ assert part["as_of"] == "4c1e31fe3a9b"+++def test_health_bands_reads_the_overview_distribution_too():+ overview = {"code_health": {"distribution": HEALTH["distribution"]}}+ part = _build(overview, "overview", "get_overview", "health.bands")+ assert sum(_series(part, "files")) == 5034+ assert part["as_of"] is None+ assert part["stale"] is False+++def test_health_trend_is_oldest_first_with_source_values():+ part = _build(HEALTH, "health", "get_health", "health.trend")+ recent = sorted(HEALTH["trend"]["recent"], key=lambda s: s["taken_at"])+ assert part["chart_type"] == "line"+ assert _series(part, "average_health") == [s["average_health"] for s in recent]+ assert _series(part, "hotspot_health") == [s["hotspot_health"] for s in recent]+ assert part["data"]["total_rows"] == 10+ assert part["data"]["truncated"] is True+++def test_test_coverage_carries_the_report_reach_as_coverage():+ part = _build(HEALTH, "health", "get_health", "health.test_coverage")+ assert _series(part, "line_coverage") == [100, 96.36]+ assert part["coverage"] == {"metric": "test_reach", "ratio": 0.8884}+ assert part["basis"]["kind"] == "measured"+ assert part["data"]["total_rows"] == 1382+++def test_a_limit_cut_without_a_reported_total_is_still_truncated():+ data = {"global_hotspots": [{"file_path": f"f{i}.py", "fix_count": i} for i in range(5)]}+ part = _build(data, "risk", "get_risk", "risk.hotspots", limit=2)+ assert part["data"]["total_rows"] == 5+ assert part["data"]["truncated"] is True+++def test_an_empty_chart_source_is_refused():+ with pytest.raises(ViewError) as err:+ _build({"summary": {"by_kind": {"x": "n/a"}}}, "dead_code", "get_dead_code", "dead_code.by_kind")+ assert err.value.code == "no_data"+++def test_dead_code_by_tier_and_by_kind():+ tiers = _build(DEAD_CODE, "dead_code", "get_dead_code", "dead_code.by_tier")+ assert _series(tiers, "findings") == [0, 15, 0]+ kinds = _build(DEAD_CODE, "dead_code", "get_dead_code", "dead_code.by_kind")+ assert dict(zip(_series(kinds, "kind"), _series(kinds, "findings"), strict=True)) == {+ "unreachable_file": 4,+ "unused_export": 11,+ }+++def test_risk_hotspots_plot_fix_counts_not_scores():+ part = _build(RISK, "risk", "get_risk", "risk.hotspots", limit=1)+ assert part["series"] == ["fix_count"]+ assert _series(part, "fix_count") == [56]+ assert part["data"]["total_rows"] == 1037+ assert part["data"]["truncated"] is True+++def test_generic_table_over_a_list_keeps_values_and_the_total():+ part = _build(HEALTH, "health", "get_health", "table", path="high_leverage_files")+ assert [c["key"] for c in part["columns"]] == ["file_path", "score", "max_ccn"]+ assert part["rows"][1] == {+ "file_path": {"type": "file", "id": "init.py"},+ "score": 1.01,+ "max_ccn": 160,+ }+ assert part["total_rows"] == 770+ assert part["truncated"] is True+++def test_generic_table_over_a_map_keys_rows_by_id():+ part = _build(RISK, "risk", "get_risk", "table", path="targets")+ assert part["rows"] == [+ {"id": "src/a.py", "dependents_count": 12, "hotspot_score": 0.9458},+ {"id": "src/b.py", "dependents_count": 6, "hotspot_score": 0.6087},+ ]+++def test_generic_table_picks_the_only_table_and_honours_columns_and_limit():+ data = {"rows": [{"a": 1, "b": "x"}, {"a": 2, "b": "y"}], "_meta": _META}+ part = _build(data, "generic", "get_x", "table", columns=["b"], limit=1)+ assert part["rows"] == [{"b": "x"}]+ assert part["total_rows"] == 2+ assert part["basis"] == {"kind": "inferred", "source": "get_x"}+++# ---------------------------------------------------------------------------+# Guards+# ---------------------------------------------------------------------------+++def test_no_builder_output_has_a_person_column():+ cases = [+ (HEALTH, "health", "get_health"),+ (DEAD_CODE, "dead_code", "get_dead_code"),+ (RISK, "risk", "get_risk"),+ ]+ for data, artifact_type, tool in cases:+ for view in view_builders.names:+ try:+ part = build_view(_artifact(data, artifact_type, tool), view, {}, part_id="v1")+ except ViewError:+ continue+ columns = part.get("columns") or part["data"]["columns"]+ assert not any("owner" in c["key"] or "author" in c["key"] for c in columns), view+ part = _build(DEAD_CODE, "dead_code", "get_dead_code", "table", path="tiers.medium.findings")+ assert "primary_owner" not in part["rows"][0]+++def test_a_person_path_or_column_is_refused():+ data = {"by_owner": [{"owner": "someone", "count": 3}]}+ with pytest.raises(ViewError) as exc:+ build_view(_artifact(data, "dead_code", "get_dead_code"), "table", {"path": "by_owner"}, part_id="v1")+ assert exc.value.code == "person_grouping"++ @register_view_builder("test.by_author", description="never allowed")+ def _by_author(artifact, options):+ return {+ "kind": "table",+ "title": "By author",+ "basis": {"kind": "measured", "source": "git"},+ "columns": [{"key": "author", "label": "Author"}],+ "rows": [{"author": "x"}],+ "total_rows": 1,+ "truncated": False,+ }++ try:+ with pytest.raises(ViewError) as exc:+ build_view(_artifact({}, "risk", "get_risk"), "test.by_author", {}, part_id="v1")+ assert exc.value.code == "person_grouping"+ finally:+ view_builders._impls.pop("test.by_author")+++def _attribution_builder(ratio: float | None):+ def build(artifact, options):+ part = {+ "kind": "chart",+ "chart_type": "bar",+ "title": "Agent share",+ "summary": "Agent-authored share by component.",+ "basis": {"kind": "measured", "source": "git markers"},+ "x": "component",+ "series": ["share"],+ "data": {+ "columns": [+ {"key": "component", "label": "Component"},+ {"key": "share", "label": "Share", "unit": "%"},+ ],+ "rows": [{"component": "payments", "share": 40}],+ "total_rows": 1,+ "truncated": False,+ },+ }+ if ratio is not None:+ part["coverage"] = {"metric": "attribution", "ratio": ratio}+ return part++ return build++[email protected](("ratio", "refused"), [(0.2, True), (None, True), (0.3, False), (0.9, False)])+def test_attribution_below_the_floor_is_refused_with_its_coverage(ratio, refused):+ register_view_builder(+ "test.agent_share", description="test", options=frozenset(), coverage_metric="attribution"+ )(_attribution_builder(ratio))+ try:+ turn = TurnViews()+ stamped = turn.record("get_x", {}, {"ok": 1})+ result = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "test.agent_share"})+ finally:+ view_builders._impls.pop("test.agent_share")+ if refused:+ assert result["error_code"] == "insufficient_coverage"+ assert result["coverage"] == ratio+ assert turn.parts == []+ else:+ assert result["view_id"] == "v1"+ assert turn.parts[0]["coverage"]["ratio"] == ratio+++def test_a_risk_score_is_never_a_chart_series():+ @register_view_builder("test.risk_chart", description="never allowed", options=frozenset())+ def _risk_chart(artifact, options):+ return {+ "kind": "chart",+ "chart_type": "bar",+ "title": "Risk",+ "summary": "Risk.",+ "basis": {"kind": "inferred", "source": "x"},+ "x": "file",+ "series": ["hotspot_score"],+ "data": {+ "columns": [{"key": "file", "label": "File"}, {"key": "hotspot_score", "label": "S"}],+ "rows": [{"file": "a", "hotspot_score": 0.9}],+ "total_rows": 1,+ "truncated": False,+ },+ }++ try:+ with pytest.raises(ViewError) as exc:+ build_view(_artifact(RISK, "risk", "get_risk"), "test.risk_chart", {}, part_id="v1")+ assert exc.value.code == "risk_score_series"+ finally:+ view_builders._impls.pop("test.risk_chart")+++# ---------------------------------------------------------------------------+# Registry and show_view+# ---------------------------------------------------------------------------+++def test_registering_one_function_adds_a_view():+ @register_view_builder("test.count", description="Rows counted", artifact_types={"risk"})+ def _count(artifact, options):+ return {+ "kind": "table",+ "title": "Targets",+ "basis": {"kind": "measured", "source": "test"},+ "columns": [{"key": "targets", "label": "Targets"}],+ "rows": [{"targets": len(artifact.data["targets"])}],+ "total_rows": 1,+ "truncated": False,+ }++ try:+ turn = TurnViews()+ stamped = turn.record("get_risk", {}, RISK, artifact_type="risk")+ receipt = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "test.count"})+ assert receipt == {"view_id": "v1", "kind": "table", "title": "Targets"}+ assert turn.parts[0]["rows"] == [{"targets": 2}]+ assert "test.count" in show_view_schema(["risk"])["function"]["parameters"]["properties"][+ "view"+ ]["enum"]+ assert "test.count" not in show_view_schema(["health"])["function"]["description"]+ finally:+ view_builders._impls.pop("test.count")+++ ("arguments", "code"),+ [+ ({"artifact_id": "nope", "view": "table"}, "unknown_artifact"),+ ({"view": "table"}, "unknown_artifact"),+ ({"artifact_id": "@", "view": "pie.chart"}, "unknown_view"),+ ({"artifact_id": "@", "view": "dead_code.by_tier"}, "view_not_applicable"),+ ({"artifact_id": "@", "view": "health.bands", "options": {"color": "red"}}, "view_unavailable"),+ ({"artifact_id": "@", "view": "table", "options": {"path": "missing"}}, "bad_path"),+ ({"artifact_id": "@", "view": "table", "options": {"limit": 0}}, "bad_arguments"),+ ({"artifact_id": "@", "view": "table", "options": "x"}, "bad_arguments"),+ ({"artifact_id": "@", "view": "health.trend"}, "view_unavailable"),+ ],+)+def test_show_view_errors_reach_the_model(arguments, code):+ turn = TurnViews()+ stamped = turn.record("get_health", {}, {"distribution": HEALTH["distribution"]}, artifact_type="health")+ if arguments.get("artifact_id") == "@":+ arguments = {**arguments, "artifact_id": stamped[ARTIFACT_ID_FIELD]}+ result = turn.show(arguments)+ assert result["error_code"] == code+ assert result["error"]+ assert turn.parts == []+++def test_a_builder_that_raises_is_an_error_the_model_sees():+ register_view_builder("test.broken", description="raises", options=frozenset())(+ lambda artifact, options: {}["missing"]+ )+ try:+ turn = TurnViews()+ stamped = turn.record("get_x", {}, {"ok": 1})+ result = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "test.broken"})+ finally:+ view_builders._impls.pop("test.broken")+ assert result["error_code"] == "builder_failed"+++def test_a_failed_tool_result_is_not_viewable():+ turn = TurnViews()+ stamped = turn.record("get_health", {}, {"error": "boom"}, artifact_type="health")+ result = turn.show({"artifact_id": stamped[ARTIFACT_ID_FIELD], "view": "table"})+ assert result["error_code"] == "artifact_failed"+++def test_show_view_is_chat_only():+ assert get_registered_tool(SHOW_VIEW_TOOL) is None+ assert SHOW_VIEW_TOOL not in {tool.entry.name for tool in get_tool_catalog(None)}+++def test_the_envelope_takes_the_stamped_id_and_keeps_data_unchanged():+ turn = TurnViews()+ stamped = turn.record("get_risk", {}, RISK, artifact_type="risk")+ artifact_id, data = turn.unstamp(stamped)+ envelope = create_artifact_envelope(+ tool_name="get_risk",+ artifact_type="risk",+ presentation="risk",+ data=data,+ artifact_id=artifact_id,+ )+ assert envelope["id"] == stamped[ARTIFACT_ID_FIELD]+ assert envelope["data"] == RISK+++def test_a_tools_own_artifact_id_field_is_data_not_an_id():+ tool_data = {"artifact_id": "a" * 32, "score": 1}+ turn = TurnViews()+ # Never recorded: the field is not a stamp.+ assert turn.unstamp(tool_data) == (None, tool_data)+ envelope = create_artifact_envelope(+ tool_name="get_risk", artifact_type="risk", presentation="risk", data=tool_data+ )+ assert envelope["id"] != tool_data["artifact_id"]+ assert envelope["data"] == {"artifact_id": "a" * 32, "score": 1}++ # Recorded: the stamp wins on the model's copy, the stored data keeps the tool's value.+ stamped = turn.record("get_risk", {}, tool_data, artifact_type="risk")+ artifact_id, data = turn.unstamp(stamped)+ assert artifact_id == stamped[ARTIFACT_ID_FIELD] != tool_data["artifact_id"]+ assert data == {"artifact_id": "a" * 32, "score": 1}+ # An equal copy that was not the dict handed out is not a stamp either.+ assert turn.unstamp(dict(stamped)) == (None, dict(stamped))++[email protected]("bad", ["", "x" * 32, "A" * 32, 7, "a" * 31])+def test_the_envelope_refuses_a_malformed_id(bad):+ with pytest.raises(ValueError):+ create_artifact_envelope(+ tool_name="t", artifact_type="generic", presentation="generic", data={}, artifact_id=bad+ )+++# ---------------------------------------------------------------------------+# The chat stream+# ---------------------------------------------------------------------------+++def _call(tool_id: str, name: str, arguments: dict) -> ChatStreamEvent:+ return ChatStreamEvent(+ type="tool_start", tool_call=ChatToolCall(id=tool_id, name=name, arguments=arguments)+ )+++async def test_show_view_streams_a_view_event_and_stores_the_view():+ app = await _make_app()++ def turns(index: int) -> list[ChatStreamEvent]:+ if index == 0:+ return [_call("t1", "get_dead_code", {})]+ if index == 1:+ tool_message = provider.calls[1]["messages"][-1]+ artifact_id = json.loads(tool_message["content"])[ARTIFACT_ID_FIELD]+ return [_call("t2", SHOW_VIEW_TOOL, {"artifact_id": artifact_id, "view": "dead_code.by_tier"})]+ return [ChatStreamEvent(type="text_delta", text="Most findings are medium.")]++ provider = _ScriptedProvider(turns)+ execute = AsyncMock(return_value=DEAD_CODE)++ with patch(_PROVIDER, return_value=provider), patch(+ "repowise.server.routers.chat.execute_tool", execute+ ):+ events = _data_events(await _post(app, {"message": "Show dead code by tier"}))++ types = [event["type"] for event in events]+ assert types[:5] == ["tool_start", "tool_result", "tool_start", "tool_result", "view"]+ assert types[-1] == "done"+ execute.assert_awaited_once()+ view = events[4]+ assert view["tool_id"] == "t2"+ artifact = events[1]["artifact"]+ assert view["view"]["source"]["artifact_id"] == artifact["id"]+ assert ARTIFACT_ID_FIELD not in artifact["data"]+ assert [row["findings"] for row in view["view"]["data"]["rows"]] == [0, 15, 0]++ stored = await _stored_messages(app, events[-1]["conversation_id"])+ assert stored[-1]["content"]["views"] == [view["view"]]+++async def test_a_turn_without_show_view_stores_no_views():+ app = await _make_app()+ provider = _ScriptedProvider([[_call("t1", "get_risk", {})], [ChatStreamEvent(type="text_delta", text="ok")]])+ with patch(_PROVIDER, return_value=provider), patch(+ "repowise.server.routers.chat.execute_tool", AsyncMock(return_value=RISK)+ ):+ events = _data_events(await _post(app, {"message": "risk?"}))+ assert "view" not in [event["type"] for event in events]+ stored = await _stored_messages(app, events[-1]["conversation_id"])+ assert "views" not in stored[-1]["content"]diff --git a/tests/unit/test_no_hotspot_health_copies.py b/tests/unit/test_no_hotspot_health_copies.pyindex 4b0613682..b80183f07 100644--- a/tests/unit/test_no_hotspot_health_copies.py+++ b/tests/unit/test_no_hotspot_health_copies.py@@ -59,6 +59,7 @@ _PLUMBING: dict[str, str] = {"repowise/cli/commands/health_cmd/command.py": "prints the KPI dict it was handed","repowise/core/generation/editor_files/data.py": "the CodeHealthBlock field","repowise/server/routers/_repo_summary.py": "serves the latest snapshot column on /repos/summary",+ "repowise/server/chat_views.py": "charts the trend snapshots get_health already returned",}