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): add durable artifact workspace (#1964)
Raghav Chamadiyae29fd737d4a9
diff --git a/packages/api-client/src/chat.test.ts b/packages/api-client/src/chat.test.tsindex b4044a8cb..f7bfa35cb 100644--- a/packages/api-client/src/chat.test.ts+++ b/packages/api-client/src/chat.test.ts@@ -3,11 +3,14 @@ import { describe, expect, it, vi, beforeEach } from "vitest";vi.mock("./client", () => ({apiGet: vi.fn(),apiDelete: vi.fn(),+ apiPatch: vi.fn(),+ apiPost: vi.fn(),BASE_URL: "http://localhost:7337",buildHeaders: () => new Headers(),}));-import { postChatMessage } from "./chat";+import { apiGet, apiPatch } from "./client";+import { getConversationArtifact, postChatMessage, setConversationArtifactPinned } from "./chat";function okStream(): Response {return new Response("retry: 3000\n\n", {@@ -63,3 +66,14 @@ describe("postChatMessage", () => {});});});++describe("conversation artifacts", () => {+ it("uses repository-scoped deep-link and pin endpoints", async () => {+ vi.mocked(apiGet).mockResolvedValueOnce({ id: "a1" });+ vi.mocked(apiPatch).mockResolvedValueOnce({ id: "a1", pinned: true });+ await getConversationArtifact("r1", "c1", "a1");+ await setConversationArtifactPinned("r1", "c1", "a1", true);+ expect(apiGet).toHaveBeenCalledWith("/api/repos/r1/chat/conversations/c1/artifacts/a1");+ expect(apiPatch).toHaveBeenCalledWith("/api/repos/r1/chat/conversations/c1/artifacts/a1", { pinned: true });+ });+});diff --git a/packages/api-client/src/chat.ts b/packages/api-client/src/chat.tsindex 93b216475..db1f14ce3 100644--- a/packages/api-client/src/chat.ts+++ b/packages/api-client/src/chat.ts@@ -4,7 +4,7 @@import { apiGet, apiDelete, apiPatch, apiPost, BASE_URL, buildHeaders } from "./client";import type { ConversationResponse, ChatMessageResponse } from "./types";-import type { ChatContext } from "@repowise-dev/types/chat";+import type { ChatArtifact, ChatContext } from "@repowise-dev/types/chat";export async function listConversations(repoId: string,@@ -54,6 +54,28 @@ export async function forkConversation(});}+export async function getConversationArtifact(+ repoId: string,+ conversationId: string,+ artifactId: string,+): Promise<ChatArtifact> {+ return apiGet(+ `/api/repos/${repoId}/chat/conversations/${conversationId}/artifacts/${artifactId}`,+ );+}++export async function setConversationArtifactPinned(+ repoId: string,+ conversationId: string,+ artifactId: string,+ pinned: boolean,+): Promise<ChatArtifact> {+ return apiPatch(+ `/api/repos/${repoId}/chat/conversations/${conversationId}/artifacts/${artifactId}`,+ { pinned },+ );+}+/*** POST a chat message and return the raw Response for SSE streaming.* The caller reads response.body as a ReadableStream.diff --git a/packages/api-client/src/types/chat.ts b/packages/api-client/src/types/chat.tsindex ee7ca9420..6a124a462 100644--- a/packages/api-client/src/types/chat.ts+++ b/packages/api-client/src/types/chat.ts@@ -2,6 +2,8 @@// Chat// ---------------------------------------------------------------------------+import type { ChatArtifact } from "@repowise-dev/types/chat";+export interface ConversationResponse {id: string;repository_id: string;@@ -25,6 +27,7 @@ export interface ChatMessageResponse {result?: Record<string, unknown>;summary?: string;artifact_type?: string;+ artifact?: ChatArtifact;}>;provider?: string;model?: string;@@ -45,7 +48,7 @@ export type ChatSSEEvent =tool_id: string;tool_name: string;summary: string;- artifact: { type: string; data: Record<string, unknown> };+ artifact: ChatArtifact;}| { type: "done"; conversation_id: string; message_id: string; user_message_id?: string; provider?: string; model?: string }| { type: "error"; message: string };diff --git a/packages/api-client/src/types/mcp.ts b/packages/api-client/src/types/mcp.tsindex 01de3de7f..63fe70484 100644--- a/packages/api-client/src/types/mcp.ts+++ b/packages/api-client/src/types/mcp.ts@@ -8,6 +8,17 @@ export interface McpToolInfo {default: boolean;requires_workspace: boolean;enabled: boolean;+ tier: string;+ default_single_repo: boolean;+ default_workspace: boolean;+ eligible: boolean;+ eligible_single_repo: boolean;+ eligible_workspace: boolean;+ recipes: Array<{ name: string; call: string; requires: string[] }>;+ artifact_type: string;+ presentation: string;+ safety: "read_only" | "generative" | "mutating" | string;+ evidence_basis: "measured" | "inferred" | "unknown";}export interface McpToolSurface {diff --git a/packages/core/src/repowise/core/persistence/crud/chat.py b/packages/core/src/repowise/core/persistence/crud/chat.pyindex 991936dbb..e8f878cef 100644--- a/packages/core/src/repowise/core/persistence/crud/chat.py+++ b/packages/core/src/repowise/core/persistence/crud/chat.py@@ -160,6 +160,20 @@ async def list_chat_messages(session: AsyncSession, conversation_id: str) -> lisreturn list(result.scalars().all())+async def update_chat_message_content(+ session: AsyncSession,+ message_id: str,+ content: dict,+) -> ChatMessage | None:+ """Replace one message envelope after an artifact metadata mutation."""+ message = await session.get(ChatMessage, message_id)+ if message is None:+ return None+ message.content_json = json.dumps(content)+ await session.flush()+ return message++async def count_chat_messages(session: AsyncSession, conversation_id: str) -> int:result = await session.execute(select(func.count())diff --git a/packages/core/src/repowise/core/registry/__init__.py b/packages/core/src/repowise/core/registry/__init__.pyindex 27fd54965..3cd8f338f 100644--- a/packages/core/src/repowise/core/registry/__init__.py+++ b/packages/core/src/repowise/core/registry/__init__.py@@ -26,6 +26,7 @@ from .cli_registry import (register_lazy_command,)from .mcp_tool_registry import (+ TOOL_SAFETY_KINDS,TOOL_TIERS,MCPToolRegistry,ToolEntry,@@ -41,6 +42,7 @@ from .pipeline_hooks import ()__all__ = [+ "TOOL_SAFETY_KINDS","TOOL_TIERS","CLIRegistry","HookPhase",diff --git a/packages/core/src/repowise/core/registry/mcp_tool_registry.py b/packages/core/src/repowise/core/registry/mcp_tool_registry.pyindex e79a8af57..051d1ec28 100644--- a/packages/core/src/repowise/core/registry/mcp_tool_registry.py+++ b/packages/core/src/repowise/core/registry/mcp_tool_registry.py@@ -36,6 +36,7 @@ from dataclasses import dataclassfrom typing import AnyTOOL_TIERS = frozenset({"canonical", "utility", "specialist"})+TOOL_SAFETY_KINDS = frozenset({"read_only", "generative", "mutating"})@dataclass(frozen=True)@@ -66,6 +67,10 @@ class ToolEntry:surface_order: int = 1000trust_kind: str | None = Nonerecipes: tuple[ToolRecipe, ...] = ()+ artifact_type: str = "generic"+ presentation: str = "generic"+ safety: str = "read_only"+ evidence_basis: str = "unknown"class MCPToolRegistry:@@ -84,6 +89,10 @@ class MCPToolRegistry:surface_order: int = 1000,trust_kind: str | None = None,recipes: tuple[ToolRecipe, ...] = (),+ artifact_type: str = "generic",+ presentation: str = "generic",+ safety: str = "read_only",+ evidence_basis: str = "unknown",**kwargs: Any,) -> Callable[[Callable[..., Any]], Callable[..., Any]] | Callable[..., Any]:"""Decorator that schedules a function for FastMCP registration.@@ -113,6 +122,13 @@ class MCPToolRegistry:raise ValueError("canonical MCP tools must be default and single-repo eligible")if resolved_tier == "specialist" and default:raise ValueError("specialist MCP tools must be opt-in (default=False)")+ if safety not in TOOL_SAFETY_KINDS:+ raise ValueError(+ f"unknown MCP tool safety {safety!r}; "+ f"expected one of {sorted(TOOL_SAFETY_KINDS)}"+ )+ if evidence_basis not in {"measured", "inferred", "unknown"}:+ raise ValueError("artifact evidence_basis must be measured, inferred, or unknown")self._entries.append(ToolEntry(fn=fn,@@ -123,6 +139,10 @@ class MCPToolRegistry:surface_order=surface_order,trust_kind=trust_kind,recipes=recipes,+ artifact_type=artifact_type,+ presentation=presentation,+ safety=safety,+ evidence_basis=evidence_basis,))fn.__dict__["__repowise_trust_kind__"] = trust_kind@@ -184,4 +204,11 @@ mcp_tool_registry = MCPToolRegistry()"""Process-wide default registry used by the OSS MCP server."""-__all__ = ["TOOL_TIERS", "MCPToolRegistry", "ToolEntry", "ToolRecipe", "mcp_tool_registry"]+__all__ = [+ "TOOL_SAFETY_KINDS",+ "TOOL_TIERS",+ "MCPToolRegistry",+ "ToolEntry",+ "ToolRecipe",+ "mcp_tool_registry",+]diff --git a/packages/server/src/repowise/server/chat_artifacts.py b/packages/server/src/repowise/server/chat_artifacts.pynew file mode 100644index 000000000..744f25b6d--- /dev/null+++ b/packages/server/src/repowise/server/chat_artifacts.py@@ -0,0 +1,202 @@+"""Versioned artifact envelopes stored inside existing chat message JSON."""++from __future__ import annotations++from datetime import UTC, datetime+from typing import Any+from uuid import NAMESPACE_URL, uuid4, uuid5++ARTIFACT_ENVELOPE_VERSION = 1++_LEGACY_ARTIFACT_TYPE_BY_TOOL = {+ "get_overview": "overview",+ "get_context": "context",+ "get_symbol": "source",+ "get_risk": "risk",+ "get_change_risk": "change_risk",+ "get_why": "decisions",+ "search_codebase": "search_results",+ "get_health": "health",+ "get_dead_code": "dead_code",+ "get_dependency_path": "dependency_path",+ "get_execution_flows": "call_path",+ "get_architecture_diagram": "diagram",+}+++def _legacy_artifact_id(message_id: str, tool_id: str, index: int) -> str:+ return uuid5(+ NAMESPACE_URL,+ f"repowise:chat-artifact:{message_id}:{tool_id}:{index}",+ ).hex+++def _evidence_qualifiers(data: dict[str, Any]) -> dict[str, Any]:+ meta = data.get("_meta") if isinstance(data.get("_meta"), dict) else {}+ state = meta.get("state") if isinstance(meta.get("state"), dict) else {}+ evidence: dict[str, Any] = {+ "basis": data.get("evidence_kind") or data.get("basis") or "unknown",+ }+ confidence = data.get("confidence")+ if confidence is not None:+ evidence["confidence"] = confidence+ coverage = data.get("coverage")+ if coverage is not None:+ if isinstance(coverage, dict):+ evidence["coverage"] = {+ "available": bool(coverage.get("available"))+ if "available" in coverage+ else "summary" in coverage or "files" in coverage+ }+ else:+ evidence["coverage"] = {"available": bool(coverage)}+ if state.get("truncated") or meta.get("omitted") or data.get("truncated"):+ evidence["truncated"] = True+ stale_warning = meta.get("stale_warning") or data.get("stale_warning")+ if stale_warning:+ evidence["stale"] = str(stale_warning)+ collections: list[dict[str, Any]] = []+ for key, total in data.items():+ if not key.endswith("_total"):+ continue+ prefix = key.removesuffix("_total")+ emitted = data.get(f"{prefix}_emitted")+ if emitted is None and isinstance(data.get(prefix), list):+ emitted = len(data[prefix])+ if emitted is not None:+ collections.append(+ {"name": prefix.replace("_", " "), "total": total, "emitted": emitted}+ )+ coverage_data = data.get("coverage")+ if isinstance(coverage_data, dict):+ total = coverage_data.get("files_total")+ emitted = coverage_data.get("files_emitted")+ if total is not None and emitted is not None:+ collections.append({"name": "coverage files", "total": total, "emitted": emitted})+ if collections:+ evidence["limits"] = {"collections": collections}+ return evidence+++def create_artifact_envelope(+ *,+ tool_name: str,+ artifact_type: str,+ presentation: str,+ data: dict[str, Any],+ title: str | None = None,+ artifact_id: str | None = None,+ pinned: bool = False,+ evidence_basis: str = "unknown",+) -> dict[str, Any]:+ """Create the one durable payload stored for a completed tool call."""+ return {+ "id": artifact_id or uuid4().hex,+ "version": ARTIFACT_ENVELOPE_VERSION,+ "type": artifact_type,+ "tool_name": tool_name,+ "title": title or tool_name,+ "presentation": presentation,+ "data": data,+ "evidence": {+ **_evidence_qualifiers(data),+ "basis": data.get("evidence_kind") or data.get("basis") or evidence_basis,+ },+ "pinned": pinned,+ "created_at": datetime.now(UTC).isoformat(),+ }+++def normalize_message_artifacts(+ content: dict[str, Any],+ *,+ message_id: str,+) -> dict[str, Any]:+ """Return a single-payload envelope view for new and historical rows."""+ normalized = dict(content)+ raw_calls = content.get("tool_calls")+ if not isinstance(raw_calls, list):+ return normalized++ calls: list[Any] = []+ for index, raw_call in enumerate(raw_calls):+ if not isinstance(raw_call, dict):+ calls.append(raw_call)+ continue+ call = dict(raw_call)+ artifact = call.get("artifact")+ result = call.get("result")+ if isinstance(artifact, dict) and isinstance(artifact.get("data"), dict):+ envelope = dict(artifact)+ envelope.setdefault(+ "id",+ _legacy_artifact_id(message_id, str(call.get("id", "tool")), index),+ )+ envelope.setdefault("version", ARTIFACT_ENVELOPE_VERSION)+ envelope.setdefault("type", call.get("artifact_type") or "generic")+ envelope.setdefault("tool_name", str(call.get("name", "unknown")))+ envelope.setdefault("presentation", envelope["type"])+ envelope.setdefault("title", call.get("summary") or envelope["tool_name"])+ envelope.setdefault("evidence", _evidence_qualifiers(envelope["data"]))+ envelope.setdefault("pinned", False)+ call["artifact"] = envelope+ call.pop("result", None)+ call.pop("artifact_type", None)+ elif isinstance(result, dict):+ tool_name = str(call.get("name", "unknown"))+ artifact_type = str(+ call.get("artifact_type") or _LEGACY_ARTIFACT_TYPE_BY_TOOL.get(tool_name, "generic")+ )+ call["artifact"] = create_artifact_envelope(+ tool_name=tool_name,+ artifact_type=artifact_type,+ presentation=artifact_type,+ data=result,+ title=str(call.get("summary") or tool_name),+ artifact_id=_legacy_artifact_id(+ message_id,+ str(call.get("id", "tool")),+ index,+ ),+ )+ call.pop("result", None)+ call.pop("artifact_type", None)+ calls.append(call)+ normalized["tool_calls"] = calls+ return normalized+++def find_artifact(+ content: dict[str, Any],+ *,+ message_id: str,+ artifact_id: str,+) -> dict[str, Any] | None:+ normalized = normalize_message_artifacts(content, message_id=message_id)+ for call in normalized.get("tool_calls", []):+ if not isinstance(call, dict):+ continue+ artifact = call.get("artifact")+ if isinstance(artifact, dict) and artifact.get("id") == artifact_id:+ return artifact+ return None+++def set_artifact_pinned(+ content: dict[str, Any],+ *,+ message_id: str,+ artifact_id: str,+ pinned: bool,+) -> tuple[dict[str, Any], bool]:+ normalized = normalize_message_artifacts(content, message_id=message_id)+ found = False+ for call in normalized.get("tool_calls", []):+ if not isinstance(call, dict):+ continue+ artifact = call.get("artifact")+ if isinstance(artifact, dict) and artifact.get("id") == artifact_id:+ artifact["pinned"] = pinned+ found = True+ break+ return normalized, founddiff --git a/packages/server/src/repowise/server/chat_tools.py b/packages/server/src/repowise/server/chat_tools.pyindex 505cb5829..149f2f868 100644--- a/packages/server/src/repowise/server/chat_tools.py+++ b/packages/server/src/repowise/server/chat_tools.py@@ -1,322 +1,68 @@-"""Chat tool registry — single source of truth for tool schemas and execution.--Imports the 7 MCP tool functions directly and exposes them as a callable registry-for the agentic chat loop. Also provides OpenAI-format tool definitions for the LLM.-"""+"""Thin chat adapter over the canonical MCP registry and selected surface."""from __future__ import annotations+import inspectimport logging-from collections.abc import Awaitable, Callablefrom dataclasses import dataclassfrom typing import Any-from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE+from repowise.core.registry import ToolEntry+from repowise.server.mcp_server._tool_selection import (+ get_registered_tool,+ selected_tool_entries,+)logger = logging.getLogger(__name__)-@dataclass-class ToolDef:- """A tool definition with schema and callable."""+@dataclass(frozen=True)+class ChatToolContract:+ """One request-scoped projection of a canonical MCP entry."""- name: str+ entry: ToolEntrydescription: str- parameters: dict[str, Any] # JSON Schema- function: Callable[..., Awaitable[dict[str, Any]]]- artifact_type: str # For the frontend artifact panel---# ----------------------------------------------------------------------------# Tool schemas (matching FastMCP's auto-generated schemas from function sigs)-# -----------------------------------------------------------------------------_TOOL_SCHEMAS: list[dict[str, Any]] = [- {- "name": "get_overview",- "description": "Get a high-level overview of the repository: architecture, key modules, entry points.",- "parameters": {- "type": "object",- "properties": {- "repo": {- "type": "string",- "description": "Repository path, name, or ID. Omit if only one repo.",- },- },- "required": [],- },- "artifact_type": "overview",- },- {- "name": "get_context",- "description": (- "Triage card for files/modules/symbols: docs, freshness, hotspot bit, "- "signatures. Opt into full_doc, ownership, last_change, callers/callees, "- "metrics, community, decisions, health, or skeleton (body-elided source)."- ),- "parameters": {- "type": "object",- "properties": {- "targets": {- "type": "array",- "items": {"type": "string"},- "description": "File paths, module paths, or symbol names to look up.",- },- "include": {- "type": "array",- "items": {- "type": "string",- "enum": [- "full_doc",- "ownership",- "last_change",- "callers",- "callees",- "metrics",- "community",- "decisions",- "health",- "skeleton",- ],- },- "description": (- "Opt-in blocks (docs + freshness are always on): "- "full_doc | ownership | last_change | callers | callees | "- "metrics | community | decisions | health | skeleton."- ),- },- "compact": {- "type": "boolean",- "description": (- "Default true. False adds structure, imports, and docstrings "- "to the triage card."- ),- "default": True,- },- "repo": {"type": "string", "description": "Repository identifier."},- },- "required": ["targets"],- },- "artifact_type": "wiki_page",- },- {- "name": "get_risk",- "description": "Assess modification risk with trend analysis: hotspot score + velocity (increasing/stable/decreasing), risk type (churn-heavy/bug-prone/high-coupling), impact surface (top 3 modules that would break), dependents, co-change partners, ownership.",- "parameters": {- "type": "object",- "properties": {- "targets": {- "type": "array",- "items": {"type": "string"},- "description": "File paths to assess risk for.",- },- "repo": {"type": "string", "description": "Repository identifier."},- },- "required": ["targets"],- },- "artifact_type": "risk_report",- },- {- "name": "get_change_risk",- "description": "Rank a live commit or branch range against recent repository changes. The percentile/classification is authoritative; the 0-10 diff-shape score is supporting, not a probability. Use get_risk for indexed file history and structural reach.",- "parameters": {- "type": "object",- "properties": {- "revspec": {- "type": "string",- "description": "Commit or base..head range to score. Defaults to HEAD.",- "default": "HEAD",- },- "repo": {"type": "string", "description": "Repository identifier."},- "extensions": {- "type": "array",- "items": {"type": "string"},- "description": "File suffixes to count, for example .py or .ts.",- },- "exclude_patterns": {- "type": "array",- "items": {"type": "string"},- "description": "Gitignore-style paths to omit from the score and baseline.",- },- "baseline": {- "type": "integer",- "minimum": 0,- "default": 200,- "description": "Recent commits used for percentile ranking; 0 disables it.",- },- },- "required": [],- },- "artifact_type": "risk_report",- },- {- "name": "get_why",- "description": "Intent archaeology: understand why code was built a certain way. Path lookup returns origin story (who, when, key commits linked to decisions) and alignment score. Natural language search scores across all decision fields. Use targets to anchor search to specific files.",- "parameters": {- "type": "object",- "properties": {- "query": {- "type": "string",- "description": "Natural language question, file/module path, or omit for health dashboard.",- },- "targets": {- "type": "array",- "items": {"type": "string"},- "description": "File paths to anchor the search. Decisions governing these files are prioritized.",- },- "repo": {"type": "string", "description": "Repository identifier."},- },- "required": [],- },- "artifact_type": "decisions",- },- {- "name": "search_codebase",- "description": "Semantic and full-text search across all wiki documentation pages.",- "parameters": {- "type": "object",- "properties": {- "query": {"type": "string", "description": "Natural language search query."},- "limit": {- "type": "integer",- "description": "Max results (default 5).",- "default": 5,- },- "page_type": {- "type": "string",- "description": "Filter by page type (e.g., file_page, module_page).",- },- "repo": {"type": "string", "description": "Repository identifier."},- },- "required": ["query"],- },- "artifact_type": "search_results",- },- {- "name": "get_dead_code",- "description": "Get a tiered refactor plan for dead code. Returns findings in high/medium/low confidence tiers with per-directory rollups, ownership hotspots, and impact estimates. Use group_by for rollup views, tier to focus on one band.",- "parameters": {- "type": "object",- "properties": {- "repo": {"type": "string", "description": "Repository identifier."},- "kind": {- "type": "string",- "description": "Filter: unreachable_file, unused_export, unused_internal, zombie_package.",- },- "min_confidence": {- "type": "number",- "description": (- f"Minimum confidence threshold (default {RISK_CAP_CONFIDENCE}; "- "matches RISK_CAP_CONFIDENCE)."- ),- "default": RISK_CAP_CONFIDENCE,- },- "safe_only": {- "type": "boolean",- "description": "Only return safe-to-delete findings.",- "default": False,- },- "limit": {- "type": "integer",- "description": "Max findings per tier (default 20).",- "default": 20,- },- "tier": {- "type": "string",- "description": "Focus on one tier: high (>=0.8), medium (0.5-0.8), or low (<0.5).",- },- "directory": {- "type": "string",- "description": "Filter to a directory prefix (e.g. src/legacy).",- },- "owner": {"type": "string", "description": "Filter by primary owner name."},- "group_by": {- "type": "string",- "description": "Rollup view: 'directory' or 'owner'.",- },- },- "required": [],- },- "artifact_type": "dead_code",- },-]---def _build_registry() -> dict[str, ToolDef]:- """Build the tool registry by importing MCP tool functions."""- from repowise.server.mcp_server import (- get_change_risk,- get_context,- get_dead_code,- get_overview,- get_risk,- get_why,- search_codebase,- )-- async def _search_concept(query: str, **kwargs):- # Chat surfaces wiki documentation pages (see the schema/artifact_type- # below), so pin the concept branch — the symbol/path modes return- # symbol/file shapes the chat artifact renderer doesn't expect.- kwargs["mode"] = "concept"- return await search_codebase(query, **kwargs)-- func_map: dict[str, Callable] = {- "get_overview": get_overview,- "get_context": get_context,- "get_change_risk": get_change_risk,- "get_risk": get_risk,- "get_why": get_why,- "search_codebase": _search_concept,- "get_dead_code": get_dead_code,- }-- registry: dict[str, ToolDef] = {}- for schema in _TOOL_SCHEMAS:- name = schema["name"]- registry[name] = ToolDef(- name=name,- description=schema["description"],- parameters=schema["parameters"],- function=func_map[name],- artifact_type=schema["artifact_type"],+ parameters: dict[str, Any]+++def get_tool_catalog(repo_path: str | None) -> list[ChatToolContract]:+ """Return the repository's configured MCP surface with generated schemas."""+ catalog: list[ChatToolContract] = []+ for entry in selected_tool_entries(repo_path):+ registered = get_registered_tool(entry.name)+ if registered is None:+ logger.error("Registered MCP entry has no FastMCP contract: %s", entry.name)+ continue+ catalog.append(+ ChatToolContract(+ entry=entry,+ description=str(registered.description or ""),+ parameters=dict(registered.parameters),+ ))- return registry---# Lazy singleton-_registry: dict[str, ToolDef] | None = None---def get_tool_registry() -> dict[str, ToolDef]:- """Get the tool registry (lazy-initialized)."""- global _registry- if _registry is None:- _registry = _build_registry()- return _registry+ return catalog-def get_tool_schemas_for_llm() -> list[dict[str, Any]]:- """Return OpenAI-format tool definitions for the LLM."""+def get_tool_schemas_for_llm(repo_path: str | None) -> list[dict[str, Any]]:+ """Return OpenAI-format definitions from FastMCP's canonical schemas."""return [{"type": "function","function": {- "name": schema["name"],- "description": schema["description"],- "parameters": schema["parameters"],+ "name": tool.entry.name,+ "description": tool.description,+ "parameters": tool.parameters,},}- for schema in _TOOL_SCHEMAS+ for tool in get_tool_catalog(repo_path)]def _make_json_serializable(obj: Any) -> Any:- """Recursively ensure an object is JSON-serializable."""if obj is None or isinstance(obj, (bool, int, float, str)):return objif isinstance(obj, dict):- return {str(k): _make_json_serializable(v) for k, v in obj.items()}+ return {str(key): _make_json_serializable(value) for key, value in obj.items()}if isinstance(obj, (list, tuple)):return [_make_json_serializable(item) for item in obj]if hasattr(obj, "__dict__"):@@ -324,15 +70,9 @@ def _make_json_serializable(obj: Any) -> Any:return str(obj)-def _scope_repo_arg(tool_def: ToolDef, arguments: dict[str, Any], repo: str | None) -> None:- """Point a tool call at the repo the chat page is on.-- The model only sees the repo *name* in the system prompt, so left to- itself it passes a string that may not be a workspace alias at all. We- keep its value when it names a real repo (so "compare with gateway"- still works) and otherwise substitute the caller's alias.- """- if not repo or "repo" not in tool_def.parameters.get("properties", {}):+def _scope_repo_arg(entry: ToolEntry, arguments: dict[str, Any], repo: str | None) -> None:+ """Backstop a model-supplied repo value with the active workspace alias."""+ if not repo or "repo" not in inspect.signature(entry.fn).parameters:returnimport repowise.server.mcp_server as mcp_mod@@ -347,34 +87,86 @@ def _scope_repo_arg(tool_def: ToolDef, arguments: dict[str, Any], repo: str | Noarguments["repo"] = repo-async def execute_tool(- name: str, arguments: dict[str, Any], repo: str | None = None+async def execute_entry(+ entry: ToolEntry,+ arguments: dict[str, Any],+ *,+ repo: str | None = None,+ confirmed: bool = False,) -> dict[str, Any]:- """Execute a tool by name and return JSON-serializable result.-- ``repo`` is the alias of the repo the request is scoped to (workspace- mode). It backstops the ``repo`` argument the model supplies.- """- registry = get_tool_registry()- tool_def = registry.get(name)- if not tool_def:- return {"error": f"Unknown tool: {name}"}+ """Execute one selected registry entry under its safety contract."""+ if entry.safety == "mutating" and not confirmed:+ return {+ "error": f"{entry.name} requires explicit confirmation before it can run",+ "error_code": "confirmation_required",+ "requires_confirmation": True,+ "tool_name": entry.name,+ }try:- arguments = dict(arguments)- _scope_repo_arg(tool_def, arguments, repo)- result = await tool_def.function(**arguments)- return _make_json_serializable(result)+ scoped_arguments = dict(arguments)+ _scope_repo_arg(entry, scoped_arguments, repo)+ return _make_json_serializable(await entry.fn(**scoped_arguments))except Exception as exc:- logger.exception("Tool execution failed: %s", name)- return {"error": f"{type(exc).__name__}: {exc}"}+ logger.exception("Tool execution failed: %s", entry.name)+ return {"error": f"{type(exc).__name__}: {exc}", "error_code": "tool_failed"}-def get_artifact_type(tool_name: str) -> str:- """Get the artifact type for a tool's results."""- registry = get_tool_registry()- tool_def = registry.get(tool_name)- return tool_def.artifact_type if tool_def else "unknown"+async def execute_tool(+ name: str,+ arguments: dict[str, Any],+ *,+ repo_path: str | None = None,+ repo: str | None = None,+ confirmed: bool = False,+) -> dict[str, Any]:+ """Execute a tool only when it belongs to the configured MCP surface."""+ tool = next(+ (candidate for candidate in get_tool_catalog(repo_path) if candidate.entry.name == name),+ None,+ )+ if tool is None:+ return {+ "error": f"Tool is not enabled for this repository: {name}",+ "error_code": "tool_not_enabled",+ }+ return await execute_entry(tool.entry, arguments, repo=repo, confirmed=confirmed)+++def get_artifact_type(tool_name: str, repo_path: str | None) -> str:+ tool = next(+ (+ candidate+ for candidate in get_tool_catalog(repo_path)+ if candidate.entry.name == tool_name+ ),+ None,+ )+ return tool.entry.artifact_type if tool is not None else "generic"+++def get_artifact_presentation(tool_name: str, repo_path: str | None) -> str:+ tool = next(+ (+ candidate+ for candidate in get_tool_catalog(repo_path)+ if candidate.entry.name == tool_name+ ),+ None,+ )+ return tool.entry.presentation if tool is not None else "generic"+++def get_artifact_evidence_basis(tool_name: str, repo_path: str | None) -> str:+ tool = next(+ (+ candidate+ for candidate in get_tool_catalog(repo_path)+ if candidate.entry.name == tool_name+ ),+ None,+ )+ return tool.entry.evidence_basis if tool is not None else "unknown"def init_tool_state(@@ -384,11 +176,7 @@ def init_tool_state(decision_store: Any | None = None,repo_path: str | None = None,) -> None:- """Bridge FastAPI app state to the MCP server module globals.-- Must be called during app lifespan startup so that direct tool calls- from the chat router use the same DB session factory and stores.- """+ """Bridge FastAPI app state to the MCP server module globals."""import repowise.server.mcp_server as mcp_modmcp_mod._session_factory = session_factory@@ -409,12 +197,7 @@ def set_tool_workspace(workspace_root: Any = _UNSET,cross_repo_enricher: Any = _UNSET,) -> None:- """Publish workspace state to the MCP tool globals.-- The stdio MCP server sets these in its own lifespan; the HTTP server has- to do the same or the tools resolve every alias against the primary- repo's database alone (issue #970). Arguments left out are untouched.- """+ """Publish workspace state to the MCP tool globals used by both surfaces."""import repowise.server.mcp_server as mcp_modif registry is not _UNSET:diff --git a/packages/server/src/repowise/server/mcp_server/_tool_selection.py b/packages/server/src/repowise/server/mcp_server/_tool_selection.pyindex 39b783a75..a253788ac 100644--- a/packages/server/src/repowise/server/mcp_server/_tool_selection.py+++ b/packages/server/src/repowise/server/mcp_server/_tool_selection.py@@ -258,6 +258,33 @@ def selected_tool_names(*, is_workspace: bool) -> set[str]:return resolve_enabled_tools(mcp_tool_registry.entries(), is_workspace=is_workspace)+def selected_tool_entries(repo_path: str | None) -> list[ToolEntry]:+ """Return the configured MCP entries available to one repository.++ This is the shared selection seam for external MCP clients and in-product+ chat. It deliberately resolves from the live registry on every request so+ neither surface can grow a second catalog or retain a stale config view.+ """+ _ensure_registered()+ entries = mcp_tool_registry.entries()+ enabled = resolve_enabled_tools(+ entries,+ is_workspace=_is_workspace(repo_path),+ override=_read_config_override(repo_path),+ )+ return [+ entry+ for entry in sorted(entries, key=lambda item: (item.surface_order, item.name))+ if entry.name in enabled+ ]+++def get_registered_tool(name: str) -> Any | None:+ """Return FastMCP's generated tool contract for a registry entry."""+ _ensure_registered()+ return (_full_surface or {}).get(name)++def _tool_description(name: str, fn: Any | None = None) -> str:"""One-line description for a tool, from its registered FastMCP schema."""tool = (_full_surface or {}).get(name)@@ -291,6 +318,10 @@ def registry_tool_rows(entries: Iterable[ToolEntry] | None = None) -> list[dict[}for recipe in entry.recipes],+ "artifact_type": entry.artifact_type,+ "presentation": entry.presentation,+ "safety": entry.safety,+ "evidence_basis": entry.evidence_basis,}for entry in sorted(catalog, key=lambda item: (item.surface_order, item.name))]diff --git a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.pyindex a5a092de1..728503b4a 100644--- a/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py+++ b/packages/server/src/repowise/server/mcp_server/tool_answer/answer.py@@ -810,6 +810,8 @@ _projected_get_answer = projected_answer(_get_answer_raw)@mcp.tool(surface_order=10,+ artifact_type="answer",+ presentation="answer",recipes=(ToolRecipe("answer_question",diff --git a/packages/server/src/repowise/server/mcp_server/tool_architecture.py b/packages/server/src/repowise/server/mcp_server/tool_architecture.pyindex f92acace6..5f149f4d3 100644--- a/packages/server/src/repowise/server/mcp_server/tool_architecture.py+++ b/packages/server/src/repowise/server/mcp_server/tool_architecture.py@@ -21,7 +21,14 @@ from repowise.server.mcp_server._meta import persisted_analysis_meta as _analysi_MCP_CORE_MEMBER_LIMIT = 25[email protected](default=False, requires_workspace=True, surface_order=200, trust_kind="structural")+ default=False,+ requires_workspace=True,+ surface_order=200,+ trust_kind="structural",+ artifact_type="workspace_architecture",+ presentation="dependency_graph",+)async def get_architecture() -> dict[str, Any]:"""Workspace architecture metrics — coupling, core, and a 1-10 score.diff --git a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.pyindex aa9b58930..76308de31 100644--- a/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py+++ b/packages/server/src/repowise/server/mcp_server/tool_blast_radius.py@@ -29,7 +29,14 @@ _MCP_IMPACTED_LIMIT = 25_SYMBOL_CONSUMER_LIMIT = 10[email protected](default=False, requires_workspace=True, surface_order=210, trust_kind="structural")+ default=False,+ requires_workspace=True,+ surface_order=210,+ trust_kind="structural",+ artifact_type="dependency_graph",+ presentation="dependency_graph",+)async def get_blast_radius(targets: list[str],max_depth: int = 3,diff --git a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py b/packages/server/src/repowise/server/mcp_server/tool_change_risk.pyindex a6bfa7fd0..d64ad0962 100644--- a/packages/server/src/repowise/server/mcp_server/tool_change_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_change_risk.py@@ -55,7 +55,12 @@ _SHED_ORDER = response_budget_shed_order("get_change_risk")#: Per-field units and calibration. Identical on every call, so it is opt-in._INCLUDE_BLOCKS = frozenset({"scales"})[email protected](surface_order=60)+ surface_order=60,+ artifact_type="change_risk",+ presentation="change_risk",+ evidence_basis="measured",+)async def get_change_risk(revspec: str | None = None,repo: str | None = None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_conformance.py b/packages/server/src/repowise/server/mcp_server/tool_conformance.pyindex 7f97ee0c5..3706abebf 100644--- a/packages/server/src/repowise/server/mcp_server/tool_conformance.py+++ b/packages/server/src/repowise/server/mcp_server/tool_conformance.py@@ -27,6 +27,8 @@ _MCP_CYCLE_LIMIT = 25requires_workspace=True,surface_order=250,trust_kind="structural",+ artifact_type="conformance",+ presentation="conformance",)async def get_conformance(repo: str | None = None) -> dict[str, Any]:"""Architecture conformance — dependency-rule violations + cycles.diff --git a/packages/server/src/repowise/server/mcp_server/tool_context/context.py b/packages/server/src/repowise/server/mcp_server/tool_context/context.pyindex 772fcee9a..988f1d3b7 100644--- a/packages/server/src/repowise/server/mcp_server/tool_context/context.py+++ b/packages/server/src/repowise/server/mcp_server/tool_context/context.py@@ -80,6 +80,8 @@ _INCLUDE_BLOCKS = frozenset(@mcp.tool(surface_order=20,+ artifact_type="context",+ presentation="context",recipes=(ToolRecipe("read_file_shape",diff --git a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py b/packages/server/src/repowise/server/mcp_server/tool_dead_code.pyindex e54317309..a3a45f0b8 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dead_code.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dead_code.py@@ -262,7 +262,7 @@ def _resolve_min_confidence(value: float | str, ignored: list[dict[str, Any]]) -return RISK_CAP_CONFIDENCE[email protected](surface_order=100)[email protected](surface_order=100, artifact_type="dead_code", presentation="dead_code", evidence_basis="inferred")async def get_dead_code(repo: str | None = None,kind: str | None = None,diff --git a/packages/server/src/repowise/server/mcp_server/tool_dependency.py b/packages/server/src/repowise/server/mcp_server/tool_dependency.pyindex d4b99f4aa..06b15fef5 100644--- a/packages/server/src/repowise/server/mcp_server/tool_dependency.py+++ b/packages/server/src/repowise/server/mcp_server/tool_dependency.py@@ -25,7 +25,14 @@ from repowise.server.mcp_server._helpers import ()[email protected](default=False, surface_order=220, trust_kind="structural")+ default=False,+ surface_order=220,+ trust_kind="structural",+ artifact_type="dependency_path",+ presentation="dependency_path",+ evidence_basis="inferred",+)async def get_dependency_path(source: str, target: str, repo: str | None = None) -> dict:"""Find how two files/modules are connected in the dependency graph.diff --git a/packages/server/src/repowise/server/mcp_server/tool_flows.py b/packages/server/src/repowise/server/mcp_server/tool_flows.pyindex 94a93be1b..ddf851f18 100644--- a/packages/server/src/repowise/server/mcp_server/tool_flows.py+++ b/packages/server/src/repowise/server/mcp_server/tool_flows.py@@ -37,7 +37,14 @@ from repowise.server.mcp_server._helpers import (from repowise.server.mcp_server._meta import build_meta as _build_meta[email protected](default=False, surface_order=230, trust_kind="structural")+ default=False,+ surface_order=230,+ trust_kind="structural",+ artifact_type="call_path",+ presentation="call_path",+ evidence_basis="inferred",+)async def get_execution_flows(top_n: int = 10,max_depth: int = 8,diff --git a/packages/server/src/repowise/server/mcp_server/tool_health.py b/packages/server/src/repowise/server/mcp_server/tool_health.pyindex 15381ef96..94e37f6fa 100644--- a/packages/server/src/repowise/server/mcp_server/tool_health.py+++ b/packages/server/src/repowise/server/mcp_server/tool_health.py@@ -1043,6 +1043,9 @@ def _compute_kpis(@mcp.tool(surface_order=90,+ artifact_type="health",+ presentation="health",+ evidence_basis="measured",recipes=(ToolRecipe("health_directive",diff --git a/packages/server/src/repowise/server/mcp_server/tool_overview.py b/packages/server/src/repowise/server/mcp_server/tool_overview.pyindex 748208286..9e23f43e0 100644--- a/packages/server/src/repowise/server/mcp_server/tool_overview.py+++ b/packages/server/src/repowise/server/mcp_server/tool_overview.py@@ -943,7 +943,7 @@ def _build_guided_tour(result.setdefault("architecture", {})["layer_order"] = layer_order[email protected](surface_order=80)[email protected](surface_order=80, artifact_type="overview", presentation="overview")async def get_overview(repo: str | None = None, include: list[str] | None = None) -> dict:"""Architecture map for an unfamiliar repo — first call when you don't know your way around.diff --git a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py b/packages/server/src/repowise/server/mcp_server/tool_refactoring.pyindex af8c8ffd2..0cf163d4c 100644--- a/packages/server/src/repowise/server/mcp_server/tool_refactoring.py+++ b/packages/server/src/repowise/server/mcp_server/tool_refactoring.py@@ -20,7 +20,14 @@ from repowise.server.mcp_server._helpers import _get_repo, _resolve_repo_contextfrom repowise.server.mcp_server._meta import build_meta as _build_meta[email protected](default=False, surface_order=240, trust_kind="generated")+ default=False,+ surface_order=240,+ trust_kind="generated",+ artifact_type="refactoring",+ presentation="source_diff",+ safety="generative",+)async def generate_refactoring_code(suggestion_id: str, repo: str | None = None) -> dict:"""Generate refactored code + a unified diff for one refactoring plan.diff --git a/packages/server/src/repowise/server/mcp_server/tool_repos.py b/packages/server/src/repowise/server/mcp_server/tool_repos.pyindex 498b6146e..279645183 100644--- a/packages/server/src/repowise/server/mcp_server/tool_repos.py+++ b/packages/server/src/repowise/server/mcp_server/tool_repos.py@@ -58,7 +58,13 @@ def _workspace_repos(registry: Any) -> list[dict[str, Any]]:return repos[email protected](tier="utility", requires_workspace=True, surface_order=110)+ tier="utility",+ requires_workspace=True,+ surface_order=110,+ artifact_type="repository_list",+ presentation="repository_list",+)async def list_repos() -> dict[str, Any]:"""List repos available through this MCP server.diff --git a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.pyindex 9c0abb663..9afc81255 100644--- a/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py+++ b/packages/server/src/repowise/server/mcp_server/tool_risk/get_risk.py@@ -89,6 +89,9 @@ def _drop_opt_in_blocks(response: dict, include: set[str]) -> None:@mcp.tool(surface_order=50,+ artifact_type="risk",+ presentation="risk",+ evidence_basis="measured",recipes=(ToolRecipe("assess_hotspot",diff --git a/packages/server/src/repowise/server/mcp_server/tool_search.py b/packages/server/src/repowise/server/mcp_server/tool_search.pyindex fef47439f..845cfe2fa 100644--- a/packages/server/src/repowise/server/mcp_server/tool_search.py+++ b/packages/server/src/repowise/server/mcp_server/tool_search.py@@ -1084,6 +1084,9 @@ async def _structured_search(@mcp.tool(surface_order=40,+ artifact_type="search_results",+ presentation="search_results",+ evidence_basis="inferred",recipes=(ToolRecipe("find_raw_hits",diff --git a/packages/server/src/repowise/server/mcp_server/tool_symbol.py b/packages/server/src/repowise/server/mcp_server/tool_symbol.pyindex 713aefef5..01664bff2 100644--- a/packages/server/src/repowise/server/mcp_server/tool_symbol.py+++ b/packages/server/src/repowise/server/mcp_server/tool_symbol.py@@ -656,7 +656,7 @@ async def _render_ambiguous(return response[email protected](surface_order=30)[email protected](surface_order=30, artifact_type="source", presentation="source", evidence_basis="measured")async def get_symbol(symbol_id: str | None = None,context_lines: int = 0,diff --git a/packages/server/src/repowise/server/mcp_server/tool_why.py b/packages/server/src/repowise/server/mcp_server/tool_why.pyindex 051f1c07f..4c6bfdc32 100644--- a/packages/server/src/repowise/server/mcp_server/tool_why.py+++ b/packages/server/src/repowise/server/mcp_server/tool_why.py@@ -106,6 +106,9 @@ def _stamp_answer_basis(result: dict) -> dict:@mcp.tool(surface_order=70,+ artifact_type="decisions",+ presentation="decision_evidence",+ evidence_basis="inferred",recipes=(ToolRecipe("read_rationale",diff --git a/packages/server/src/repowise/server/routers/chat.py b/packages/server/src/repowise/server/routers/chat.pyindex 3015aa915..5de0950fa 100644--- a/packages/server/src/repowise/server/routers/chat.py+++ b/packages/server/src/repowise/server/routers/chat.py@@ -13,9 +13,19 @@ from starlette.responses import StreamingResponsefrom repowise.core.persistence import crudfrom repowise.core.persistence.database import get_sessionfrom repowise.core.providers.llm.base import ChatProvider, ProviderError+from repowise.server.chat_artifacts import (+ create_artifact_envelope,+ find_artifact,+ normalize_message_artifacts,+ set_artifact_pinned,+)from repowise.server.chat_tools import (+ ChatToolContract,execute_tool,+ get_artifact_evidence_basis,+ get_artifact_presentation,get_artifact_type,+ get_tool_catalog,get_tool_schemas_for_llm,)from repowise.server.deps import (@@ -25,6 +35,7 @@ from repowise.server.deps import ()from repowise.server.provider_config import get_chat_provider_instancefrom repowise.server.schemas import (+ ArtifactUpdateRequest,ChatMessageResponse,ChatRequest,ConversationForkRequest,@@ -43,22 +54,35 @@ _MAX_AGENTIC_LOOPS = 10_SYSTEM_PROMPT_TEMPLATE = """You are a codebase intelligence assistant for the repository "{repo_name}" located at {repo_path}.-You have access to 7 specialized tools for querying the codebase wiki, dependency graph, git history, and architectural decisions. Use them proactively — do NOT answer from memory when a tool gives more accurate answers.+The repository has configured these callable tools: {tool_names}. Use only this advertised surface, and use a tool when it provides stronger evidence than memory.+{recipes}Guidelines:-- Call get_overview first if the user asks about the codebase generally and no prior context exists-- Pass all relevant targets to get_context and get_risk in a single call — never call the same tool twice for different targets when they can be batched-- Call get_change_risk for commit / PR-range defect scoring (revspec)-- Call get_why for any "why was this built this way" question-- Call search_codebase for broad questions about where something is implemented-- Cite specific file paths, function names, and line numbers from tool results — be concrete, not general+- Cite specific file paths, function names, and line numbers from tool results; be concrete, not general- Format responses in markdown. File paths in backticks. Code in fenced blocks.- When tool results contain documentation, synthesize and explain rather than dumping raw content-- If a tool returns an error, explain what happened and suggest alternatives"""---def _build_system_prompt(repo_name: str, repo_path: str) -> str:- return _SYSTEM_PROMPT_TEMPLATE.format(repo_name=repo_name, repo_path=repo_path)+- If a tool returns an error, explain what happened and suggest alternatives+- Never claim a tool ran when it did not, and never reveal or invent hidden chain-of-thought+- A mutating tool cannot run without an explicit user confirmation grant"""+++def _build_system_prompt(+ repo_name: str,+ repo_path: str,+ tools: list[ChatToolContract],+) -> str:+ recipes = [recipe.call for tool in tools for recipe in tool.entry.recipes]+ recipe_text = (+ "Registry recipes:\n" + "\n".join(f"- {recipe}" for recipe in recipes)+ if recipes+ else "No registry recipes are configured."+ )+ return _SYSTEM_PROMPT_TEMPLATE.format(+ repo_name=repo_name,+ repo_path=repo_path,+ tool_names=", ".join(tool.entry.name for tool in tools) or "none",+ recipes=recipe_text,+ )def _with_navigation_context(@@ -212,13 +236,14 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):llm_messages = _db_messages_to_llm_format(db_messages)llm_messages = _with_navigation_context(llm_messages, body.context)- system_prompt = _build_system_prompt(repo_name, repo_path)- tool_schemas = get_tool_schemas_for_llm()+ tool_catalog = get_tool_catalog(repo_path)+ system_prompt = _build_system_prompt(repo_name, repo_path, tool_catalog)+ tool_schemas = get_tool_schemas_for_llm(repo_path)# Tool executor callback — used by providers that run the# agentic loop internally (e.g. Gemini for thought_signature).async def _tool_executor(name: str, args: dict) -> dict:- return await execute_tool(name, args, repo=repo_alias)+ return await execute_tool(name, args, repo_path=repo_path, repo=repo_alias)# Agentic loopassistant_text_parts: list[str] = []@@ -273,8 +298,16 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Emit the result to the frontend.tc = event.tool_callresult = event.tool_result_data or {}- artifact_type = get_artifact_type(tc.name)+ artifact_type = get_artifact_type(tc.name, repo_path)summary = _build_tool_summary(tc.name, result)+ artifact = create_artifact_envelope(+ tool_name=tc.name,+ artifact_type=artifact_type,+ presentation=get_artifact_presentation(tc.name, repo_path),+ data=result,+ title=summary,+ evidence_basis=get_artifact_evidence_basis(tc.name, repo_path),+ )yield _sse_event("data",@@ -283,10 +316,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):"tool_id": tc.id,"tool_name": tc.name,"summary": summary,- "artifact": {- "type": artifact_type,- "data": result,- },+ "artifact": artifact,},)@@ -295,9 +325,8 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):tc.id,tc.name,tc.arguments,- result,summary,- artifact_type,+ artifact,))@@ -340,11 +369,24 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):# Execute each tool and add resultsfor tc in pending_tool_calls:- result = await execute_tool(tc["name"], tc["arguments"], repo=repo_alias)- artifact_type = get_artifact_type(tc["name"])+ result = await execute_tool(+ tc["name"],+ tc["arguments"],+ repo_path=repo_path,+ repo=repo_alias,+ )+ artifact_type = get_artifact_type(tc["name"], repo_path)# Build summary from resultsummary = _build_tool_summary(tc["name"], result)+ artifact = create_artifact_envelope(+ tool_name=tc["name"],+ artifact_type=artifact_type,+ presentation=get_artifact_presentation(tc["name"], repo_path),+ data=result,+ title=summary,+ evidence_basis=get_artifact_evidence_basis(tc["name"], repo_path),+ )yield _sse_event("data",@@ -353,10 +395,7 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):"tool_id": tc["id"],"tool_name": tc["name"],"summary": summary,- "artifact": {- "type": artifact_type,- "data": result,- },+ "artifact": artifact,},)@@ -365,9 +404,8 @@ async def chat_messages(repo_id: str, body: ChatRequest, request: Request):tc["id"],tc["name"],tc["arguments"],- result,summary,- artifact_type,+ artifact,))@@ -475,6 +513,72 @@ async def get_conversation(}[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}")+async def get_conversation_artifact(+ repo_id: str,+ conversation_id: str,+ artifact_id: str,+ session=Depends(get_db_session),+):+ conv = await crud.get_conversation(session, conversation_id)+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:+ raise HTTPException(404, "Conversation not found")+ for message in await crud.list_chat_messages(session, conversation_id):+ raw = message.content_json+ try:+ content = json.loads(raw) if isinstance(raw, str) else raw+ except (TypeError, json.JSONDecodeError):+ continue+ if not isinstance(content, dict):+ continue+ artifact = find_artifact(+ content,+ message_id=message.id,+ artifact_id=artifact_id,+ )+ if artifact is not None:+ return artifact+ raise HTTPException(404, "Artifact not found")++[email protected]("/api/repos/{repo_id}/chat/conversations/{conversation_id}/artifacts/{artifact_id}")+async def update_conversation_artifact(+ repo_id: str,+ conversation_id: str,+ artifact_id: str,+ body: ArtifactUpdateRequest,+ session=Depends(get_db_session),+):+ conv = await crud.get_conversation(session, conversation_id)+ if not conv or conv.repository_id != repo_id or conv.deleted_at is not None:+ raise HTTPException(404, "Conversation not found")+ for message in await crud.list_chat_messages(session, conversation_id):+ raw = message.content_json+ try:+ content = json.loads(raw) if isinstance(raw, str) else raw+ except (TypeError, json.JSONDecodeError):+ continue+ if not isinstance(content, dict):+ continue+ updated, found = set_artifact_pinned(+ content,+ message_id=message.id,+ artifact_id=artifact_id,+ pinned=body.pinned,+ )+ if not found:+ continue+ await crud.update_chat_message_content(session, message.id, updated)+ await crud.touch_conversation(session, conversation_id)+ artifact = find_artifact(+ updated,+ message_id=message.id,+ artifact_id=artifact_id,+ )+ return artifact+ raise HTTPException(404, "Artifact not found")++@router.delete("/api/repos/{repo_id}/chat/conversations/{conversation_id}")async def delete_conversation(repo_id: str,@@ -558,18 +662,16 @@ def _stored_tool_call(tool_id: str,name: str,arguments: dict[str, Any],- result: dict[str, Any],summary: str,- artifact_type: str,+ artifact: dict[str, Any],) -> dict[str, Any]:- """Persist the exact artifact contract emitted over SSE."""+ """Persist one durable artifact payload with the assistant message."""return {"id": tool_id,"name": name,"arguments": arguments,- "result": result,"summary": summary,- "artifact_type": artifact_type,+ "artifact": artifact,}@@ -581,6 +683,8 @@ def _db_messages_to_llm_format(db_messages: list) -> list[dict[str, Any]]:content = (json.loads(msg.content_json) if isinstance(msg.content_json, str) else msg.content_json)+ if isinstance(content, dict):+ content = normalize_message_artifacts(content, message_id=str(msg.id))if msg.role == "user":llm_messages.append(@@ -613,12 +717,14 @@ def _db_messages_to_llm_format(db_messages: list) -> list[dict[str, Any]]:# Add tool resultsfor tc in tool_calls:+ artifact = tc.get("artifact")+ result = artifact.get("data", {}) if isinstance(artifact, dict) else {}llm_messages.append({"role": "tool","tool_call_id": tc["id"],"name": tc["name"],- "content": json.dumps(tc.get("result", {})),+ "content": json.dumps(result),})else:diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex e6e80b981..45a88b6cf 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -35,6 +35,7 @@ from .c4 import (C4SystemResponse,)from .chat import (+ ArtifactUpdateRequest,ChatMessageResponse,ChatRequest,ConversationForkRequest,@@ -237,6 +238,7 @@ __all__ = ["ArchitectureGraphResponse","ArchitectureNodeResponse","ArchitectureViewResponse",+ "ArtifactUpdateRequest","BlastRadiusRequest","BlastRadiusResponse","C4ComponentResponse",diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.pyindex 8d2ff0960..25017b47b 100644--- a/packages/server/src/repowise/server/schemas/chat.py+++ b/packages/server/src/repowise/server/schemas/chat.py@@ -8,6 +8,8 @@ from typing import Literalfrom pydantic import BaseModel, Field+from repowise.server.chat_artifacts import normalize_message_artifacts+class ChatPageContext(BaseModel):"""Navigation metadata supplied by a product chat surface."""@@ -89,6 +91,10 @@ class ConversationForkRequest(BaseModel):before_message_id: str | None = None+class ArtifactUpdateRequest(BaseModel):+ pinned: bool++class ChatMessageResponse(BaseModel):id: strconversation_id: str@@ -103,6 +109,11 @@ class ChatMessageResponse(BaseModel):content = json.loads(content_str) if isinstance(content_str, str) else content_strexcept Exception:content = {"text": content_str}+ if isinstance(content, dict):+ content = normalize_message_artifacts(+ content,+ message_id=str(obj.id), # type: ignore[attr-defined]+ )return cls(id=obj.id, # type: ignore[attr-defined]conversation_id=obj.conversation_id, # type: ignore[attr-defined]diff --git a/packages/server/src/repowise/server/schemas/mcp.py b/packages/server/src/repowise/server/schemas/mcp.pyindex fe7774a4b..10e4b1485 100644--- a/packages/server/src/repowise/server/schemas/mcp.py+++ b/packages/server/src/repowise/server/schemas/mcp.py@@ -2,7 +2,13 @@from __future__ import annotations-from pydantic import BaseModel+from pydantic import BaseModel, Field+++class McpToolRecipeInfo(BaseModel):+ name: str+ call: str+ requires: list[str]class McpToolInfo(BaseModel):@@ -19,6 +25,11 @@ class McpToolInfo(BaseModel):eligible_workspace: boolrequires_workspace: boolenabled: bool+ recipes: list[McpToolRecipeInfo] = Field(default_factory=list)+ artifact_type: str+ presentation: str+ safety: str+ evidence_basis: strclass McpToolSurfaceResponse(BaseModel):diff --git a/packages/types/__tests__/contracts.test.ts b/packages/types/__tests__/contracts.test.tsindex cee8dbc46..3cbaa4186 100644--- a/packages/types/__tests__/contracts.test.ts+++ b/packages/types/__tests__/contracts.test.ts@@ -76,7 +76,11 @@ describe("ChatArtifact discriminated union", () => {it("falls through to GenericArtifact for unknown tool types", () => {const generic: ChatArtifact = {+ id: "artifact-1",+ version: 1,type: "future_tool_we_havent_typed_yet",+ tool_name: "future_tool",+ presentation: "generic",data: { whatever: 1 },};expectTypeOf(generic).toMatchTypeOf<GenericArtifact>();diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex eb4fe0d3b..201563d08 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -86,6 +86,7 @@ export interface ChatToolCall {result?: Record<string, unknown>;summary?: string;artifact_type?: string;+ artifact?: ChatArtifact;}export interface ChatMessage {@@ -111,7 +112,7 @@ export interface ChatUIToolCall {arguments: Record<string, unknown>;result?: Record<string, unknown>;summary?: string;- artifact?: { type: string; data: Record<string, unknown> };+ artifact?: ChatArtifact;status: "running" | "done" | "error";}@@ -142,6 +143,26 @@ export interface ChatCitation {end_line?: number;}+export interface ArtifactEvidence {+ basis: "measured" | "inferred" | "unknown" | string;+ confidence?: number | string;+ coverage?: unknown;+ limits?: Record<string, unknown>;+ truncated?: boolean;+ stale?: string;+}++export interface ArtifactEnvelopeIdentity {+ id: string;+ version: 1;+ tool_name: string;+ title?: string;+ presentation: string;+ evidence?: ArtifactEvidence;+ pinned?: boolean;+ created_at?: string;+}+/** `get_overview` — repository fact sheet. */export interface OverviewArtifactData {total_files: number;@@ -153,7 +174,7 @@ export interface OverviewArtifactData {git_summary?: Record<string, unknown> | null;is_monorepo: boolean;}-export interface OverviewArtifact {+export interface OverviewArtifact extends ArtifactEnvelopeIdentity {type: "overview";data: OverviewArtifactData;}@@ -170,7 +191,7 @@ export interface ContextArtifactData {}>;}-export interface ContextArtifact {+export interface ContextArtifact extends ArtifactEnvelopeIdentity {type: "context";data: ContextArtifactData;}@@ -219,10 +240,18 @@ export interface RiskReportArtifactData {error?: string;[k: string]: unknown;}-export interface RiskReportArtifact {+export interface RiskReportArtifact extends ArtifactEnvelopeIdentity {type: "risk_report";data: RiskReportArtifactData;}+export interface RiskArtifact extends ArtifactEnvelopeIdentity {+ type: "risk";+ data: RiskReportArtifactData;+}+export interface ChangeRiskArtifact extends ArtifactEnvelopeIdentity {+ type: "change_risk";+ data: RiskReportArtifactData;+}/** `search_codebase` — wiki page hits. */export interface SearchResultsArtifactData {@@ -236,7 +265,7 @@ export interface SearchResultsArtifactData {relevance_score?: number;}>;}-export interface SearchResultsArtifact {+export interface SearchResultsArtifact extends ArtifactEnvelopeIdentity {type: "search_results";data: SearchResultsArtifactData;}@@ -251,10 +280,26 @@ export interface GraphPathArtifactData {distance: number;explanation: string;}-export interface GraphPathArtifact {+export interface GraphPathArtifact extends ArtifactEnvelopeIdentity {type: "graph";data: GraphPathArtifactData;}+export interface DependencyPathArtifact extends ArtifactEnvelopeIdentity {+ type: "dependency_path";+ data: Record<string, unknown>;+}+export interface CallPathArtifact extends ArtifactEnvelopeIdentity {+ type: "call_path";+ data: Record<string, unknown>;+}+export interface SourceArtifact extends ArtifactEnvelopeIdentity {+ type: "source";+ data: Record<string, unknown>;+}+export interface HealthArtifact extends ArtifactEnvelopeIdentity {+ type: "health";+ data: Record<string, unknown>;+}/** `get_why` — decision register search / path lookup / health dashboard. */export interface DecisionsArtifactData {@@ -310,7 +355,7 @@ export interface DecisionsArtifactData {[k: string]: unknown;};}-export interface DecisionsArtifact {+export interface DecisionsArtifact extends ArtifactEnvelopeIdentity {type: "decisions";data: DecisionsArtifactData;}@@ -336,7 +381,7 @@ export interface DeadCodeArtifactData {reason: string;}>;}-export interface DeadCodeArtifact {+export interface DeadCodeArtifact extends ArtifactEnvelopeIdentity {type: "dead_code";data: DeadCodeArtifactData;}@@ -350,7 +395,7 @@ export interface DiagramArtifactData {mermaid_syntax: string;description?: string;}-export interface DiagramArtifact {+export interface DiagramArtifact extends ArtifactEnvelopeIdentity {type: "diagram";data: DiagramArtifactData;}@@ -359,17 +404,17 @@ export interface DiagramArtifact {* Fallback for tools that haven't yet been promoted to a typed variant.* The renderer falls back to JSON pretty-print for this case.*/-export interface GenericArtifact {+export interface GenericArtifact extends ArtifactEnvelopeIdentity {type: string;data: Record<string, unknown>;}/** Future variants — declared for the type system, not yet emitted on the wire. */-export interface HotspotArtifact {+export interface HotspotArtifact extends ArtifactEnvelopeIdentity {type: "hotspot";data: { hotspots: Hotspot[] };}-export interface AnswerArtifact {+export interface AnswerArtifact extends ArtifactEnvelopeIdentity {type: "answer";data: {answer: string;@@ -378,15 +423,15 @@ export interface AnswerArtifact {};}/** Strict-typed future variants — wire-format alternatives mirroring engine canonicals. */-export interface StrictGraphArtifact {+export interface StrictGraphArtifact extends ArtifactEnvelopeIdentity {type: "graph_export";data: GraphExport;}-export interface StrictDeadCodeArtifact {+export interface StrictDeadCodeArtifact extends ArtifactEnvelopeIdentity {type: "dead_code_strict";data: { findings: DeadCodeFinding[] };}-export interface StrictDecisionsArtifact {+export interface StrictDecisionsArtifact extends ArtifactEnvelopeIdentity {type: "decisions_strict";data: { decisions: DecisionRecord[] };}@@ -399,8 +444,14 @@ export interface StrictDecisionsArtifact {export type KnownChatArtifact =| OverviewArtifact| ContextArtifact+ | SourceArtifact+ | RiskArtifact+ | ChangeRiskArtifact| RiskReportArtifact+ | HealthArtifact| SearchResultsArtifact+ | DependencyPathArtifact+ | CallPathArtifact| GraphPathArtifact| DecisionsArtifact| DeadCodeArtifact@@ -416,8 +467,14 @@ export type ChatArtifact = KnownChatArtifact | GenericArtifact;const KNOWN_ARTIFACT_TYPES: ReadonlyArray<KnownChatArtifact["type"]> = ["overview","context",+ "source",+ "risk",+ "change_risk","risk_report",+ "health","search_results",+ "dependency_path",+ "call_path","graph","decisions","dead_code",diff --git a/packages/ui/__tests__/chat/artifact-panel.test.tsx b/packages/ui/__tests__/chat/artifact-panel.test.tsxnew file mode 100644index 000000000..9db6ac73d--- /dev/null+++ b/packages/ui/__tests__/chat/artifact-panel.test.tsx@@ -0,0 +1,144 @@+import { describe, expect, it, vi } from "vitest";+import { fireEvent, render, screen } from "@testing-library/react";+import { ArtifactPanel } from "../../src/chat/artifact-panel.js";+import type { ChatArtifact } from "@repowise-dev/types/chat";++const riskArtifact: ChatArtifact = {+ id: "risk-1",+ version: 1,+ type: "risk",+ tool_name: "get_risk",+ title: "Modification risk",+ presentation: "risk",+ pinned: false,+ evidence: {+ basis: "measured",+ confidence: 0.91,+ coverage: { available: true },+ limits: { emitted: 25, total: 90 },+ truncated: true,+ stale: "Index is one commit behind",+ },+ data: { targets: { "src/hot.ts": { is_hotspot: true, hotspot_score: 0.97 } } },+};++const searchArtifact: ChatArtifact = {+ id: "search-1",+ version: 1,+ type: "search_results",+ tool_name: "search_codebase",+ title: "Search results",+ presentation: "search_results",+ evidence: { basis: "inferred" },+ data: { query: "chat", results: [] },+};++describe("ArtifactPanel workspace", () => {+ it("shows evidence beside the result and keeps raw JSON secondary", () => {+ render(+ <ArtifactPanel+ artifacts={[riskArtifact]}+ activeArtifactId="risk-1"+ open+ onClose={vi.fn()}+ />,+ );++ expect(screen.getByText("Measured")).toBeInTheDocument();+ expect(screen.getByText(/Coverage available/)).toBeInTheDocument();+ expect(screen.getByText(/91% confidence/)).toBeInTheDocument();+ expect(screen.getByText(/25 of 90 shown/)).toBeInTheDocument();+ expect(screen.getByText("Truncated")).toBeInTheDocument();+ expect(screen.getByText(/one commit behind/)).toBeInTheDocument();+ expect(screen.getByText("Inspect raw result")).toBeInTheDocument();+ expect(screen.queryByText(/"src\/hot.ts"/)).not.toBeInTheDocument();+ const details = screen.getByText("Inspect raw result").closest("details")!;+ details.open = true;+ fireEvent(details, new Event("toggle", { bubbles: true }));+ expect(screen.getByText(/"src\/hot.ts"/)).toBeVisible();+ });++ it("exposes pin, compare, copy, export, source, and follow-up actions", () => {+ const onPin = vi.fn();+ const onCompare = vi.fn();+ const onOpenSource = vi.fn();+ const onFollowUp = vi.fn();+ Object.assign(navigator, { clipboard: { writeText: vi.fn() } });++ render(+ <ArtifactPanel+ artifacts={[riskArtifact, searchArtifact]}+ activeArtifactId="risk-1"+ open+ onClose={vi.fn()}+ onPin={onPin}+ onCompare={onCompare}+ onOpenSource={onOpenSource}+ onFollowUp={onFollowUp}+ />,+ );++ fireEvent.click(screen.getByRole("button", { name: "Pin artifact" }));+ fireEvent.click(screen.getByRole("button", { name: "Compare artifact" }));+ fireEvent.click(screen.getByRole("button", { name: "Copy artifact" }));+ fireEvent.click(screen.getByRole("button", { name: "Open artifact source" }));+ fireEvent.click(screen.getByRole("button", { name: "Follow up on artifact" }));++ expect(onPin).toHaveBeenCalledWith(riskArtifact, true);+ expect(onCompare).toHaveBeenCalledWith("risk-1");+ expect(navigator.clipboard.writeText).toHaveBeenCalled();+ expect(onOpenSource).toHaveBeenCalledWith(expect.objectContaining({ id: "risk-1", pinned: true }));+ expect(onFollowUp).toHaveBeenCalledWith(expect.stringContaining("Modification risk"));+ expect(screen.getByRole("button", { name: "Export artifact" })).toBeEnabled();+ });++ it("renders a selected comparison without changing the primary artifact", () => {+ render(+ <ArtifactPanel+ artifacts={[riskArtifact, searchArtifact]}+ activeArtifactId="risk-1"+ compareArtifactId="search-1"+ open+ onClose={vi.fn()}+ />,+ );+ expect(screen.getByRole("region", { name: "Primary artifact" })).toHaveTextContent("src/hot.ts");+ expect(screen.getByRole("region", { name: "Comparison artifact" })).toHaveTextContent("No results found");+ });++ it("never compares an artifact with itself", () => {+ render(<ArtifactPanel artifacts={[riskArtifact, searchArtifact]} activeArtifactId="risk-1" compareArtifactId="risk-1" open onClose={vi.fn()} />);+ expect(screen.queryByRole("region", { name: "Comparison artifact" })).not.toBeInTheDocument();+ });++ it("keeps raw JSON unmounted after the panel is closed and reopened", () => {+ const view = render(<ArtifactPanel artifacts={[riskArtifact]} open onClose={vi.fn()} />);+ const details = screen.getByText("Inspect raw result").closest("details")!;+ details.open = true;+ fireEvent(details, new Event("toggle", { bubbles: true }));+ expect(screen.getByText(/"src\/hot.ts"/)).toBeInTheDocument();+ view.rerender(<ArtifactPanel artifacts={[riskArtifact]} open={false} onClose={vi.fn()} />);+ view.rerender(<ArtifactPanel artifacts={[riskArtifact]} open onClose={vi.fn()} />);+ expect(screen.queryByText(/"src\/hot.ts"/)).not.toBeInTheDocument();+ });++ it("keeps an optimistic pin while switching artifacts", () => {+ const view = render(<ArtifactPanel artifacts={[riskArtifact, searchArtifact]} activeArtifactId="risk-1" open onClose={vi.fn()} onPin={vi.fn()} />);+ fireEvent.click(screen.getByRole("button", { name: "Pin artifact" }));+ view.rerender(<ArtifactPanel artifacts={[riskArtifact, searchArtifact]} activeArtifactId="search-1" open onClose={vi.fn()} onPin={vi.fn()} />);+ view.rerender(<ArtifactPanel artifacts={[riskArtifact, searchArtifact]} activeArtifactId="risk-1" open onClose={vi.fn()} onPin={vi.fn()} />);+ expect(screen.getByRole("button", { name: "Unpin artifact" })).toBeInTheDocument();+ });++ it("shows tool errors without invoking a typed renderer", () => {+ render(<ArtifactPanel artifacts={[{ ...riskArtifact, type: "overview", data: { error: "Index unavailable" } }]} open onClose={vi.fn()} />);+ expect(screen.getByRole("alert")).toHaveTextContent("Index unavailable");+ });++ it("contains incomplete typed results in a malformed state", () => {+ const error = vi.spyOn(console, "error").mockImplementation(() => undefined);+ render(<ArtifactPanel artifacts={[{ ...riskArtifact, type: "overview", data: {} }]} open onClose={vi.fn()} />);+ expect(screen.getByRole("alert")).toHaveTextContent(/incomplete or malformed/i);+ error.mockRestore();+ });+});diff --git a/packages/ui/__tests__/chat/artifacts.test.tsx b/packages/ui/__tests__/chat/artifacts.test.tsxindex f107cd56d..5ae80dfff 100644--- a/packages/ui/__tests__/chat/artifacts.test.tsx+++ b/packages/ui/__tests__/chat/artifacts.test.tsx@@ -10,6 +10,10 @@ import {OverviewRenderer,RiskReportRenderer,SearchResultsRenderer,+ HealthRenderer,+ DependencyPathRenderer,+ CallPathRenderer,+ SourceRenderer,} from "../../src/chat/artifacts.js";// Mermaid pulls in DOM measuring APIs jsdom doesn't implement; the renderer is@@ -309,4 +313,40 @@ describe("chat artifact renderers", () => {render(<GenericJsonRenderer data={{ foo: "bar" }} />);expect(screen.getByText(/"foo": "bar"/)).toBeInTheDocument();});++ it("HealthRenderer supports the real dashboard contract", () => {+ render(<HealthRenderer data={{ mode: "dashboard", kpis: { average_health: 7.4, hotspot_health: 5.2, maintainability_average: 8.6, performance_average: 6.9 }, top_findings: [{ file_path: "src/risky.ts", reason: "Low coverage" }], worst_files: [] }} />);+ expect(screen.getByText("7.4")).toBeInTheDocument();+ expect(screen.getByText("5.2")).toBeInTheDocument();+ expect(screen.getByText("8.6")).toBeInTheDocument();+ expect(screen.getByText("6.9")).toBeInTheDocument();+ expect(screen.getByText("src/risky.ts")).toBeInTheDocument();+ expect(screen.getByText("Low coverage")).toBeInTheDocument();+ });++ it("HealthRenderer renders a valid KPI-only dashboard", () => {+ render(<HealthRenderer data={{ kpis: { average_health: 7.4 } }} />);+ expect(screen.getByText("average health")).toBeInTheDocument();+ expect(screen.getByText("7.4")).toBeInTheDocument();+ });++ it("DependencyPathRenderer supports canonical node/relationship rows", () => {+ render(<DependencyPathRenderer data={{ path: [{ node: "src/a.ts", relationship: "imports" }, { node: "src/b.ts", relationship: "" }] }} />);+ expect(screen.getByText("src/a.ts")).toBeInTheDocument();+ expect(screen.getByText("imports")).toBeInTheDocument();+ expect(screen.queryByText("Unknown node")).not.toBeInTheDocument();+ });++ it("CallPathRenderer shows canonical traces and termination", () => {+ render(<CallPathRenderer data={{ flows: [{ entry_point_name: "main", trace: ["main", "loadConfig"], termination: "max_depth" }] }} />);+ expect(screen.getAllByText("main")).toHaveLength(2);+ expect(screen.getByText("loadConfig")).toBeInTheDocument();+ expect(screen.getByText(/Stopped:/)).toHaveTextContent("Stopped: max_depth");+ });++ it("SourceRenderer reads the canonical get_symbol file field", () => {+ render(<SourceRenderer data={{ file: "src/index.ts", source: "export const value = 1;" }} />);+ expect(screen.getByText("src/index.ts")).toBeInTheDocument();+ expect(screen.getByText(/export const value/)).toBeInTheDocument();+ });});diff --git a/packages/ui/__tests__/chat/chat-interface.test.tsx b/packages/ui/__tests__/chat/chat-interface.test.tsxindex 4b4803e90..2388b7f57 100644--- a/packages/ui/__tests__/chat/chat-interface.test.tsx+++ b/packages/ui/__tests__/chat/chat-interface.test.tsx@@ -20,6 +20,58 @@ const USER_MSG: ChatUIMessage = {};describe("ChatInterface shell", () => {+ it("restores and opens a durable artifact by stable ID", () => {+ const withArtifact: ChatUIMessage = {+ ...ASSISTANT_MSG,+ toolCalls: [{+ id: "tool-1",+ name: "search_codebase",+ arguments: {},+ status: "done",+ artifact: {+ id: "artifact-1",+ version: 1,+ type: "search_results",+ tool_name: "search_codebase",+ title: "Chat search",+ presentation: "search_results",+ evidence: { basis: "unknown" },+ data: { query: "chat", results: [] },+ },+ }],+ };+ render(<ChatInterface repoId="r1" messages={[withArtifact]} activeArtifactId="artifact-1" isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />);+ expect(screen.getByText("Artifact workspace")).toBeInTheDocument();+ expect(screen.getByText("Chat search")).toBeInTheDocument();+ expect(screen.getByText("No results found.")).toBeInTheDocument();+ });++ it("clears comparison when its artifact becomes the primary selection", () => {+ const onArtifactCompare = vi.fn();+ const withArtifacts: ChatUIMessage = {+ ...ASSISTANT_MSG,+ toolCalls: ["artifact-1", "artifact-2"].map((id, index) => ({+ id: `tool-${index}`,+ name: "search_codebase",+ arguments: {},+ status: "done" as const,+ artifact: {+ id,+ version: 1 as const,+ type: "search_results",+ tool_name: "search_codebase",+ title: index === 0 ? "First result" : "Second result",+ presentation: "search_results",+ evidence: { basis: "unknown" as const },+ data: { query: "chat", results: [] },+ },+ })),+ };+ render(<ChatInterface repoId="r1" messages={[withArtifacts]} activeArtifactId="artifact-1" compareArtifactId="artifact-2" onArtifactCompare={onArtifactCompare} isStreaming={false} onSend={vi.fn()} onCancel={vi.fn()} />);+ fireEvent.click(screen.getByRole("button", { name: "Second result" }));+ expect(onArtifactCompare).toHaveBeenCalledWith(null);+ });+it("renders empty-state heading + suggestion chips when messages is empty", () => {render(<ChatInterfacediff --git a/packages/ui/src/chat/artifact-panel.tsx b/packages/ui/src/chat/artifact-panel.tsxindex af4679237..2be5e180f 100644--- a/packages/ui/src/chat/artifact-panel.tsx+++ b/packages/ui/src/chat/artifact-panel.tsx@@ -1,128 +1,174 @@"use client";-import { useState } from "react";+import { Component, memo, useCallback, useEffect, useMemo, useState, type ErrorInfo, type ReactNode } from "react";+import { Copy, Download, ExternalLink, GitCompareArrows, MessageSquarePlus, Pin, PinOff } from "lucide-react";import { cn } from "../lib/cn";import { AdaptivePanel } from "../shared/adaptive-panel";import { Markdown } from "../shared/markdown";+import { getArtifactSourceTarget } from "./artifact-source";import {- ContextRenderer,- DeadCodeRenderer,- DecisionsRenderer,- DiagramRenderer,- GenericJsonRenderer,- GraphPathRenderer,- OverviewRenderer,- RiskReportRenderer,- SearchResultsRenderer,+ CallPathRenderer, ContextRenderer, DeadCodeRenderer, DecisionsRenderer,+ DependencyPathRenderer, DiagramRenderer, GenericJsonRenderer, GraphPathRenderer,+ HealthRenderer, OverviewRenderer, RiskReportRenderer, SearchResultsRenderer, SourceRenderer,} from "./artifacts";import type {- ChatArtifact,- ContextArtifactData,- DeadCodeArtifactData,- DecisionsArtifactData,- DiagramArtifactData,- GraphPathArtifactData,- OverviewArtifactData,- RiskReportArtifactData,- SearchResultsArtifactData,+ ChatArtifact, ContextArtifactData, DeadCodeArtifactData, DecisionsArtifactData,+ DiagramArtifactData, GraphPathArtifactData, OverviewArtifactData,+ RiskReportArtifactData, SearchResultsArtifactData,} from "@repowise-dev/types/chat";-export interface Artifact {- type: string;- title: string;- data: Record<string, unknown>;-}-interface ArtifactPanelProps {- artifacts: Artifact[];+ artifacts: ChatArtifact[];+ activeArtifactId?: string | null;+ compareArtifactId?: string | null;open: boolean;onClose: () => void;+ onSelect?: (artifactId: string) => void;+ onCompare?: (artifactId: string | null) => void;+ onPin?: (artifact: ChatArtifact, pinned: boolean) => void | Promise<void>;+ onOpenSource?: (artifact: ChatArtifact) => void;+ onFollowUp?: (text: string) => void;}-export function ArtifactPanel({ artifacts, open, onClose }: ArtifactPanelProps) {- const [activeIdx, setActiveIdx] = useState(0);-- if (artifacts.length === 0) return null;-- const active = artifacts[Math.min(activeIdx, artifacts.length - 1)];+export function ArtifactPanel({ artifacts, activeArtifactId, compareArtifactId, open, onClose, onSelect, onCompare, onPin, onOpenSource, onFollowUp }: ArtifactPanelProps) {+ const [pinOverrides, setPinOverrides] = useState<Record<string, boolean>>({});+ const [rawOpen, setRawOpen] = useState(false);+ const withPin = useCallback((artifact: ChatArtifact | undefined) => artifact ? { ...artifact, pinned: pinOverrides[artifact.id] ?? artifact.pinned } as ChatArtifact : undefined, [pinOverrides]);+ const active = useMemo(() => withPin(artifacts.find((item) => item.id === activeArtifactId) ?? artifacts[0]), [activeArtifactId, artifacts, withPin]);+ const comparison = useMemo(() => withPin(artifacts.find((item) => item.id === compareArtifactId && item.id !== active?.id)), [active?.id, artifacts, compareArtifactId, withPin]);+ useEffect(() => setRawOpen(false), [active?.id, open]);+ const pinArtifact = useCallback(async (artifact: ChatArtifact, pinned: boolean) => {+ const previous = pinOverrides[artifact.id] ?? Boolean(artifact.pinned);+ setPinOverrides((current) => ({ ...current, [artifact.id]: pinned }));+ try { await onPin?.(artifact, pinned); }+ catch (error) { setPinOverrides((current) => ({ ...current, [artifact.id]: previous })); throw error; }+ }, [onPin, pinOverrides]);if (!active) return null;return (- <AdaptivePanel- open={open}- onOpenChange={(o) => (!o ? onClose() : undefined)}- title="Artifacts"- widthClassName="md:max-w-[480px] lg:max-w-[420px]"- modal={false}- >+ <AdaptivePanel open={open} onOpenChange={(next) => { if (!next) { setRawOpen(false); onClose(); } }} title="Artifact workspace" widthClassName="md:max-w-[720px] xl:max-w-[880px]" modal={false}>{artifacts.length > 1 && (- <div className="flex gap-0 border-b border-[var(--color-border-default)] shrink-0 overflow-x-auto px-2">- {artifacts.map((art, idx) => (- <button- key={idx}- onClick={() => setActiveIdx(idx)}- className={cn(- "px-3 py-2 text-xs whitespace-nowrap border-b-2 transition-colors",- idx === activeIdx- ? "border-[var(--color-border-hover)] bg-[var(--color-bg-elevated)] text-[var(--color-text-primary)]"- : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]",- )}- >- {art.title || art.type}+ <div className="flex shrink-0 overflow-x-auto border-b border-[var(--color-border-default)] px-2" aria-label="Research artifacts">+ {artifacts.map((artifact) => (+ <button key={artifact.id} type="button" aria-pressed={artifact.id === active.id} onClick={() => onSelect?.(artifact.id)} className={cn("border-b-2 px-3 py-2 text-xs whitespace-nowrap transition-colors motion-reduce:transition-none", artifact.id === active.id ? "border-[var(--color-border-hover)] text-[var(--color-text-primary)]" : "border-transparent text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]")}>+ {artifact.title || artifact.type}</button>))}</div>)}-- <div className="flex-1 overflow-y-auto p-4">- <ArtifactRenderer artifact={active} />+ <div className="min-h-0 flex-1 overflow-y-auto p-4 sm:p-5">+ <ArtifactHeader key={active.id} artifact={active} comparing={Boolean(comparison)} {...(onCompare && artifacts.length > 1 ? { onCompare } : {})} {...(onPin ? { onPin: pinArtifact } : {})} {...(onOpenSource && getArtifactSourceTarget(active) ? { onOpenSource } : {})} {...(onFollowUp ? { onFollowUp } : {})} />+ <div className={cn("mt-5 grid gap-6", comparison && "lg:grid-cols-2")}>+ <section aria-label="Primary artifact" className="min-w-0">+ <EvidenceQualifiers artifact={active} />+ <ArtifactRenderBoundary artifactId={active.id}><ArtifactRenderer artifact={active} /></ArtifactRenderBoundary>+ </section>+ {comparison && (+ <section aria-label="Comparison artifact" className="min-w-0 border-t border-[var(--color-border-default)] pt-5 lg:border-l lg:border-t-0 lg:pl-6 lg:pt-0">+ <p className="mb-3 font-mono text-[10px] uppercase tracking-[0.12em] text-[var(--color-text-tertiary)]">Compared with {comparison.title || comparison.type}</p>+ <EvidenceQualifiers artifact={comparison} />+ <ArtifactRenderBoundary artifactId={comparison.id}><ArtifactRenderer artifact={comparison} /></ArtifactRenderBoundary>+ </section>+ )}+ </div>+ <details open={rawOpen} className="mt-6 border-t border-[var(--color-border-default)] pt-3" onToggle={(event) => setRawOpen(event.currentTarget.open)}>+ <summary className="cursor-pointer text-xs text-[var(--color-text-tertiary)] hover:text-[var(--color-text-secondary)]">Inspect raw result</summary>+ {rawOpen && <div className="mt-3"><GenericJsonRenderer data={active.data as unknown as Record<string, unknown>} /></div>}+ </details></div></AdaptivePanel>);}-/**- * Dispatcher: switches on the artifact `.type` discriminant. Every- * `KnownChatArtifact` variant has a dedicated renderer; the `default`- * branch handles `wiki_page` (legacy markdown-shaped overview pages from- * older indexer outputs) and falls through to `GenericJsonRenderer` for- * unknown shapes.- */-function ArtifactRenderer({ artifact }: { artifact: Artifact | ChatArtifact }) {- const { type, data } = artifact;-- switch (type) {- case "overview":- return <OverviewRenderer data={data as unknown as OverviewArtifactData} />;- case "context":- return <ContextRenderer data={data as unknown as ContextArtifactData} />;- case "risk_report":- return <RiskReportRenderer data={data as unknown as RiskReportArtifactData} />;- case "search_results":- return <SearchResultsRenderer data={data as unknown as SearchResultsArtifactData} />;- case "graph":- return <GraphPathRenderer data={data as unknown as GraphPathArtifactData} />;- case "decisions":- return <DecisionsRenderer data={data as unknown as DecisionsArtifactData} />;- case "dead_code":- return <DeadCodeRenderer data={data as unknown as DeadCodeArtifactData} />;- case "diagram":- return <DiagramRenderer data={data as unknown as DiagramArtifactData} />;+function ArtifactHeader({ artifact, comparing, onCompare, onPin, onOpenSource, onFollowUp }: { artifact: ChatArtifact; comparing: boolean; onCompare?: (artifactId: string | null) => void; onPin?: (artifact: ChatArtifact, pinned: boolean) => void | Promise<void>; onOpenSource?: (artifact: ChatArtifact) => void; onFollowUp?: (text: string) => void }) {+ const [status, setStatus] = useState("");+ const copy = useCallback(async () => { await navigator.clipboard.writeText(JSON.stringify(artifact.data, null, 2)); setStatus("Artifact copied."); }, [artifact.data]);+ const exportArtifact = useCallback(() => {+ const url = URL.createObjectURL(new Blob([JSON.stringify(artifact, null, 2)], { type: "application/json" }));+ const link = document.createElement("a");+ link.href = url;+ link.download = `${artifact.tool_name}-${artifact.id}.json`;+ link.click();+ URL.revokeObjectURL(url);+ setStatus("Artifact exported.");+ }, [artifact]);+ const actionClass = "inline-flex h-8 items-center gap-1.5 px-2 text-xs text-[var(--color-text-secondary)] hover:text-[var(--color-text-primary)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]";+ return (+ <header className="border-b border-[var(--color-border-default)] pb-4">+ <div className="flex items-start justify-between gap-3">+ <div className="min-w-0"><h2 className="truncate text-sm font-semibold text-[var(--color-text-primary)]">{artifact.title || artifact.type}</h2><p className="mt-1 font-mono text-[10px] text-[var(--color-text-tertiary)]">{artifact.tool_name} · {artifact.id}</p></div>+ {artifact.pinned && <span className="text-[10px] uppercase tracking-wider text-[var(--color-text-tertiary)]">Pinned</span>}+ </div>+ <div className="mt-3 flex flex-wrap items-center gap-x-1">+ {onPin && <button type="button" aria-label={artifact.pinned ? "Unpin artifact" : "Pin artifact"} className={actionClass} onClick={() => { const next = !artifact.pinned; void Promise.resolve(onPin(artifact, next)).catch(() => setStatus("Artifact pin update failed.")); }}>{artifact.pinned ? <PinOff className="h-3.5 w-3.5" /> : <Pin className="h-3.5 w-3.5" />}<span>{artifact.pinned ? "Unpin" : "Pin"}</span></button>}+ {onCompare && <button type="button" aria-label="Compare artifact" className={actionClass} onClick={() => onCompare(comparing ? null : artifact.id)}><GitCompareArrows className="h-3.5 w-3.5" /><span>Compare</span></button>}+ <button type="button" aria-label="Copy artifact" className={actionClass} onClick={() => void copy()}><Copy className="h-3.5 w-3.5" /><span>Copy</span></button>+ <button type="button" aria-label="Export artifact" className={actionClass} onClick={exportArtifact}><Download className="h-3.5 w-3.5" /><span>Export</span></button>+ {onOpenSource && <button type="button" aria-label="Open artifact source" className={actionClass} onClick={() => onOpenSource(artifact)}><ExternalLink className="h-3.5 w-3.5" /><span>Source</span></button>}+ {onFollowUp && <button type="button" aria-label="Follow up on artifact" className={actionClass} onClick={() => onFollowUp(`Follow up on ${artifact.title || artifact.type}: `)}><MessageSquarePlus className="h-3.5 w-3.5" /><span>Follow up</span></button>}+ </div>+ <p role="status" aria-live="polite" className="sr-only">{status}</p>+ </header>+ );+}- case "wiki_page": {- // Legacy markdown-shaped artifact, pre-dating the typed union.- const content =- ((data as Record<string, unknown>).content_md as string) ??- ((data as Record<string, unknown>).content as string) ??- "";- return content ? (- <Markdown content={content} density="compact" />- ) : (- <GenericJsonRenderer data={data as Record<string, unknown>} />- );+function EvidenceQualifiers({ artifact }: { artifact: ChatArtifact }) {+ const evidence = artifact.evidence;+ const basis = evidence?.basis ?? "unknown";+ const labels = [basis.charAt(0).toUpperCase() + basis.slice(1)];+ if (evidence?.coverage !== undefined) {+ const coverage = evidence.coverage;+ const available = typeof coverage === "boolean" ? coverage : coverage && typeof coverage === "object" ? (coverage as Record<string, unknown>).available : undefined;+ labels.push(available === true ? "Coverage available" : available === false ? "Coverage unavailable" : "Coverage unknown");+ }+ if (evidence?.confidence !== undefined) labels.push(typeof evidence.confidence === "number" ? `${Math.round(evidence.confidence * (evidence.confidence <= 1 ? 100 : 1))}% confidence` : `${evidence.confidence} confidence`);+ const limits = evidence?.limits;+ if (limits) {+ const emitted = limits.emitted ?? limits.shown;+ const total = limits.total;+ const cap = limits.cap ?? limits.limit;+ if (emitted !== undefined && total !== undefined) labels.push(`${String(emitted)} of ${String(total)} shown`);+ else if (cap !== undefined) labels.push(`Cap ${String(cap)}`);+ const collections = Array.isArray(limits.collections) ? limits.collections : [];+ for (const item of collections.slice(0, 4)) {+ if (!item || typeof item !== "object") continue;+ const row = item as Record<string, unknown>;+ if (row.name && row.emitted !== undefined && row.total !== undefined) labels.push(`${String(row.name)}: ${String(row.emitted)} of ${String(row.total)} shown`);}+ }+ if (evidence?.truncated) labels.push("Truncated");+ return <div className="mb-4" aria-label="Evidence qualifications"><div className="flex flex-wrap gap-x-3 gap-y-1 font-mono text-[10px] uppercase tracking-[0.08em] text-[var(--color-text-tertiary)]">{labels.map((label) => <span key={label}>{label}</span>)}</div>{evidence?.stale && <p className="mt-2 text-xs text-[var(--color-warning)]">{evidence.stale}</p>}</div>;+}- default:- return <GenericJsonRenderer data={data as Record<string, unknown>} />;+const ArtifactRenderer = memo(function ArtifactRenderer({ artifact }: { artifact: ChatArtifact }) {+ const data = artifact.data;+ if (!data || typeof data !== "object" || Array.isArray(data)) return <p role="alert" className="text-xs text-[var(--color-error)]">This artifact is malformed and cannot be rendered safely.</p>;+ const record = data as unknown as Record<string, unknown>;+ if (typeof record.error === "string") return <p role="alert" className="text-xs text-[var(--color-error)]">{record.error}</p>;+ switch (artifact.type) {+ case "overview": return <OverviewRenderer data={data as unknown as OverviewArtifactData} />;+ case "context": return <ContextRenderer data={data as unknown as ContextArtifactData} />;+ case "source": return <SourceRenderer data={record} />;+ case "risk": case "change_risk": case "risk_report": return <RiskReportRenderer data={data as unknown as RiskReportArtifactData} />;+ case "health": return <HealthRenderer data={record} />;+ case "search_results": return <SearchResultsRenderer data={data as unknown as SearchResultsArtifactData} />;+ case "dependency_path": return <DependencyPathRenderer data={record} />;+ case "call_path": return <CallPathRenderer data={record} />;+ case "graph": return <GraphPathRenderer data={data as unknown as GraphPathArtifactData} />;+ case "decisions": return <DecisionsRenderer data={data as unknown as DecisionsArtifactData} />;+ case "dead_code": return <DeadCodeRenderer data={data as unknown as DeadCodeArtifactData} />;+ case "diagram": return <DiagramRenderer data={data as unknown as DiagramArtifactData} />;+ case "wiki_page": { const content = (record.content_md as string) ?? (record.content as string) ?? ""; return content ? <Markdown content={content} density="compact" /> : <ArtifactUnavailable />; }+ default: return <ArtifactUnavailable />;}+});++function ArtifactUnavailable() { return <p className="text-xs leading-relaxed text-[var(--color-text-secondary)]">A focused view is not available for this result. Use “Inspect raw result” below to examine its structured data.</p>; }++class ArtifactRenderBoundary extends Component<{ artifactId: string; children: ReactNode }, { failed: boolean }> {+ override state = { failed: false };+ static getDerivedStateFromError() { return { failed: true }; }+ override componentDidCatch(_error: Error, _info: ErrorInfo) {}+ override componentDidUpdate(previous: { artifactId: string }) { if (previous.artifactId !== this.props.artifactId && this.state.failed) this.setState({ failed: false }); }+ override render() { return this.state.failed ? <p role="alert" className="text-xs text-[var(--color-error)]">This artifact is incomplete or malformed and cannot be rendered safely.</p> : this.props.children; }}diff --git a/packages/ui/src/chat/artifact-source.ts b/packages/ui/src/chat/artifact-source.tsnew file mode 100644index 000000000..ebbd3a4d7--- /dev/null+++ b/packages/ui/src/chat/artifact-source.ts@@ -0,0 +1,20 @@+import type { ChatArtifact } from "@repowise-dev/types/chat";++export interface ArtifactSourceTarget {+ pageId?: string;+ path?: string;+}++/** Resolve the canonical source reference shapes emitted by MCP tools. */+export function getArtifactSourceTarget(artifact: ChatArtifact): ArtifactSourceTarget | null {+ const data = artifact.data as unknown as Record<string, unknown>;+ const pageId = typeof data.page_id === "string" ? data.page_id : undefined;+ const targets = data.targets && typeof data.targets === "object" && !Array.isArray(data.targets)+ ? Object.keys(data.targets as Record<string, unknown>)+ : [];+ const candidates = Array.isArray(data.candidates) ? data.candidates : [];+ const candidatePath = candidates.find((candidate) => candidate && typeof candidate === "object" && typeof (candidate as Record<string, unknown>).file === "string") as Record<string, unknown> | undefined;+ const path = [data.file, data.file_path, data.path, data.target, targets[0], candidatePath?.file]+ .find((value): value is string => typeof value === "string" && value.length > 0);+ return pageId || path ? { ...(pageId ? { pageId } : {}), ...(path ? { path } : {}) } : null;+}diff --git a/packages/ui/src/chat/artifacts.tsx b/packages/ui/src/chat/artifacts.tsxindex 4f48c3e02..7726a168b 100644--- a/packages/ui/src/chat/artifacts.tsx+++ b/packages/ui/src/chat/artifacts.tsx@@ -767,6 +767,71 @@ export function DiagramRenderer({ data }: { data: DiagramArtifactData }) {);}+// ---------------------------------------------------------------------------+// Source, health, and selective path views+// ---------------------------------------------------------------------------++export function SourceRenderer({ data }: { data: Record<string, unknown> }) {+ const source = typeof data.source === "string" ? data.source : typeof data.content === "string" ? data.content : "";+ const path = typeof data.file === "string" ? data.file : typeof data.path === "string" ? data.path : typeof data.file_path === "string" ? data.file_path : typeof data.target === "string" ? data.target : "Source";+ const fallback = Array.isArray(data.fallback_lines) ? data.fallback_lines : [];+ if (!source && fallback.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No source content was returned.</p>;+ return (+ <div className="space-y-3">+ <p className="truncate font-mono text-xs text-[var(--color-text-secondary)]" title={path}>{path}</p>+ <pre className="max-h-[60vh] overflow-auto border-l border-[var(--color-border-default)] pl-3 font-mono text-[11px] leading-relaxed text-[var(--color-text-secondary)] whitespace-pre-wrap break-words">{source || fallback.map((line) => typeof line === "string" ? line : JSON.stringify(line)).join("\n")}</pre>+ </div>+ );+}++export function HealthRenderer({ data }: { data: Record<string, unknown> }) {+ const findings = Array.isArray(data.findings) ? data.findings : Array.isArray(data.top_findings) ? data.top_findings : [];+ const files = Array.isArray(data.ranked_files) ? data.ranked_files : Array.isArray(data.worst_files) ? data.worst_files : [];+ const kpis = data.kpis && typeof data.kpis === "object" ? data.kpis as Record<string, unknown> : {};+ const scores = data.scores && typeof data.scores === "object" ? data.scores as Record<string, unknown> : {};+ const dimensions = ["defect", "maintainability", "performance"]+ .map((key) => [key, data[key] ?? scores[key]] as const)+ .filter((entry) => entry[1] !== undefined);+ const headlineKpis = [+ ["average health", kpis.average_health ?? data.average_health],+ ["hotspot health", kpis.hotspot_health ?? data.hotspot_health],+ ["maintainability", kpis.maintainability_average ?? data.maintainability_average],+ ["performance", kpis.performance_average ?? data.performance_average],+ ["code-only health", kpis.average_health_code_only ?? data.average_health_code_only],+ ["worst performer", kpis.worst_performer_score ?? data.worst_performer_score],+ ].filter((entry): entry is [string, unknown] => entry[1] !== undefined && entry[1] !== null);+ const rows = findings.length > 0 ? findings : files;+ if (rows.length === 0 && dimensions.length === 0 && headlineKpis.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No health findings were returned for these targets.</p>;+ return (+ <div className="space-y-4">+ {(headlineKpis.length > 0 || dimensions.length > 0) && <div className="space-y-1">{[...headlineKpis, ...dimensions].map(([label, value]) => <StatRow key={label} label={label} value={typeof value === "object" ? JSON.stringify(value) : String(value)} />)}</div>}+ {rows.length > 0 && <div><SectionTitle icon={Activity}>{findings.length > 0 ? "Findings" : "Worst files"}</SectionTitle><ol className="border-t border-[var(--color-border-default)]">{rows.slice(0, 50).map((finding, index) => { const row = finding as Record<string, unknown>; const title = String(row.title ?? row.file_path ?? row.path ?? row.kind ?? `Finding ${index + 1}`); return <li key={`${title}:${index}`} className="border-b border-[var(--color-border-default)] py-2"><p className="font-mono text-xs text-[var(--color-text-primary)] break-all">{title}</p>{row.reason || row.summary || row.message ? <p className="mt-1 text-xs text-[var(--color-text-secondary)]">{String(row.reason ?? row.summary ?? row.message)}</p> : null}</li>; })}</ol></div>}+ </div>+ );+}++function extractPath(data: Record<string, unknown>): Array<{ node: string; relationship?: string }> {+ if (Array.isArray(data.path)) return data.path.map((item) => typeof item === "string" ? { node: item } : { node: String((item as Record<string, unknown>).node ?? (item as Record<string, unknown>).name ?? (item as Record<string, unknown>).id ?? "Unknown node"), ...(typeof (item as Record<string, unknown>).relationship === "string" ? { relationship: String((item as Record<string, unknown>).relationship) } : {}) });+ if (Array.isArray(data.nodes)) return data.nodes.map((item) => typeof item === "string" ? { node: item } : { node: String((item as Record<string, unknown>).node ?? (item as Record<string, unknown>).name ?? (item as Record<string, unknown>).id ?? "Unknown node") });+ const paths = Array.isArray(data.paths) ? data.paths : [];+ const first = paths[0];+ return Array.isArray(first) ? first.map((item) => ({ node: String(item) })) : [];+}++export function DependencyPathRenderer({ data }: { data: Record<string, unknown> }) {+ const path = extractPath(data);+ if (path.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No dependency path was found. This does not prove that no runtime relationship exists.</p>;+ return <div><SectionTitle icon={GitBranch}>Selected dependency path</SectionTitle><ol className="space-y-1">{path.slice(0, 100).map((item, index) => <li key={`${item.node}:${index}`} className="flex items-center gap-2 font-mono text-xs text-[var(--color-text-secondary)]"><span className="w-5 shrink-0 tabular-nums text-[var(--color-text-tertiary)]">{index + 1}</span><span className="break-all">{item.node}</span>{item.relationship && <span className="text-[10px] text-[var(--color-text-tertiary)]">{item.relationship}</span>}</li>)}</ol></div>;+}++export function CallPathRenderer({ data }: { data: Record<string, unknown> }) {+ const flows = Array.isArray(data.flows) ? data.flows : Array.isArray(data.execution_flows) ? data.execution_flows : [];+ const path = extractPath(data);+ if (flows.length === 0 && path.length === 0) return <p className="text-xs text-[var(--color-text-tertiary)]">No indexed call path was returned. Dynamic calls may be outside structural coverage.</p>;+ if (path.length > 0) return <DependencyPathRenderer data={{ path }} />;+ return <div><SectionTitle icon={ArrowRight}>Selected execution flows</SectionTitle><ol className="border-t border-[var(--color-border-default)]">{flows.slice(0, 25).map((flow, index) => { const row = flow as Record<string, unknown>; const trace = Array.isArray(row.trace) ? row.trace.map(String) : []; return <li key={index} className="border-b border-[var(--color-border-default)] py-2 text-xs text-[var(--color-text-secondary)]"><span className="font-mono break-all">{String(row.entry_point_name ?? row.name ?? row.title ?? row.entry_point ?? `Flow ${index + 1}`)}</span>{trace.length > 0 && <ol className="mt-2 space-y-1 border-l border-[var(--color-border-default)] pl-3">{trace.slice(0, 50).map((node, traceIndex) => <li key={`${node}:${traceIndex}`} className="font-mono text-[11px] break-all">{node}</li>)}</ol>}{typeof row.termination === "string" && row.termination.length > 0 && <p className="mt-2 text-[10px] text-[var(--color-text-tertiary)]">Stopped: {row.termination}</p>}</li>; })}</ol></div>;+}+// ---------------------------------------------------------------------------// Generic JSON fallback// ---------------------------------------------------------------------------diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsxindex d62237105..f7d4b515b 100644--- a/packages/ui/src/chat/chat-dock.tsx+++ b/packages/ui/src/chat/chat-dock.tsx@@ -8,7 +8,7 @@ import {X,} from "lucide-react";import { useEffect, useRef, useState, type CSSProperties, type ReactNode } from "react";-import type { ChatUIMessage } from "@repowise-dev/types/chat";+import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";import { BrandMark } from "../shared/brand-mark";import { Button } from "../ui/button";import { cn } from "../lib/cn";@@ -137,6 +137,9 @@ export interface ChatDockProps {owlLightSrc?: string;/** Clears host page controls anchored near the viewport bottom. */collisionInset?: string;+ onArtifactPin?: (artifact: ChatArtifact, pinned: boolean) => void | Promise<void>;+ onOpenArtifactSource?: (artifact: ChatArtifact) => void;+ artifactOverrides?: Readonly<Record<string, ChatArtifact>>;}function contextIdentity(context: ChatContext) {@@ -166,6 +169,9 @@ export function ChatDock({owlDarkSrc = "/repowise-logo.png",owlLightSrc = "/repowise-logo-light.png",collisionInset = "1rem",+ onArtifactPin,+ onOpenArtifactSource,+ artifactOverrides,}: ChatDockProps) {const { mode, draft, setMode, setDraft } = usePersistentDockState(storageKey);const [dismissedContext, setDismissedContext] = useState<string | null>(null);@@ -455,6 +461,9 @@ export function ChatDock({{...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}{...(buildCitationHref ? { buildCitationHref } : {})}{...(linkPrefix ? { linkPrefix } : {})}+ {...(onArtifactPin ? { onArtifactPin } : {})}+ {...(onOpenArtifactSource ? { onOpenArtifactSource } : {})}+ {...(artifactOverrides ? { artifactOverrides } : {})}/></div></DialogPrimitive.Content>diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsxindex 1e544f641..654616378 100644--- a/packages/ui/src/chat/chat-interface.tsx+++ b/packages/ui/src/chat/chat-interface.tsx@@ -21,6 +21,7 @@import {useCallback,useEffect,+ useMemo,useRef,useState,type RefObject,@@ -32,13 +33,13 @@ import { ScrollArea } from "../ui/scroll-area";import { cn } from "../lib/cn";import { BrandMark } from "../shared/brand-mark";import { ChatMessage } from "./chat-message";-import { ArtifactPanel, type Artifact } from "./artifact-panel";+import { ArtifactPanel } from "./artifact-panel";import { ChatContextIndicator } from "./chat-context-indicator";import {getChatContextPresentation,type ChatContext,} from "./chat-context";-import type { ChatUIMessage } from "@repowise-dev/types/chat";+import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";import type { SourceReference } from "./source-citations";import { ChatComposer } from "./chat-composer";import { useChatScroll } from "./use-chat-scroll";@@ -118,6 +119,15 @@ export interface ChatInterfaceProps {composerRef?: RefObject<HTMLTextAreaElement | null>;onRetry?: (message: ChatUIMessage) => void | Promise<void>;onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;+ /** Controlled artifact deep links. Hosts own URL and persistence concerns. */+ activeArtifactId?: string | null;+ compareArtifactId?: string | null;+ onArtifactNavigate?: (artifactId: string | null) => void;+ onArtifactCompare?: (artifactId: string | null) => void;+ onArtifactPin?: (artifact: ChatArtifact, pinned: boolean) => void | Promise<void>;+ onOpenArtifactSource?: (artifact: ChatArtifact) => void;+ /** Host-side artifact overlays (for example a persisted pin response). */+ artifactOverrides?: Readonly<Record<string, ChatArtifact>>;}export function ChatInterface({@@ -148,12 +158,35 @@ export function ChatInterface({composerRef,onRetry,onEditAndResend,+ activeArtifactId,+ compareArtifactId,+ onArtifactNavigate,+ onArtifactCompare,+ onArtifactPin,+ onOpenArtifactSource,+ artifactOverrides,}: ChatInterfaceProps) {const [internalInput, setInternalInput] = useState("");const input = draft ?? internalInput;const setInput = onDraftChange ?? setInternalInput;const [artifactPanelOpen, setArtifactPanelOpen] = useState(false);- const [artifacts, setArtifacts] = useState<Artifact[]>([]);+ const [internalArtifactId, setInternalArtifactId] = useState<string | null>(null);+ const [internalCompareId, setInternalCompareId] = useState<string | null>(null);+ const selectedArtifactId = activeArtifactId ?? internalArtifactId;+ const selectedCompareId = compareArtifactId ?? internalCompareId;+ const artifacts = useMemo(() => {+ const seen = new Set<string>();+ const restored: ChatArtifact[] = [];+ for (const message of messages) {+ for (const toolCall of message.toolCalls) {+ if (toolCall.artifact && !seen.has(toolCall.artifact.id)) {+ seen.add(toolCall.artifact.id);+ restored.push(artifactOverrides?.[toolCall.artifact.id] ?? toolCall.artifact);+ }+ }+ }+ return restored;+ }, [artifactOverrides, messages]);const internalTextareaRef = useRef<HTMLTextAreaElement>(null);const textareaRef = composerRef ?? internalTextareaRef;@@ -213,21 +246,36 @@ export function ChatInterface({);const handleViewArtifact = useCallback(- (artifact: { type: string; data: Record<string, unknown> }) => {- const title = (artifact.data.title as string) ?? artifact.type;- const newArt: Artifact = { type: artifact.type, title, data: artifact.data };- setArtifacts((prev) => {- const existing = prev.findIndex(- (a) => a.type === newArt.type && a.title === newArt.title,- );- if (existing >= 0) return prev;- return [...prev, newArt];- });+ (artifact: ChatArtifact) => {+ setInternalArtifactId(artifact.id);+ onArtifactNavigate?.(artifact.id);setArtifactPanelOpen(true);},- [],+ [onArtifactNavigate],);+ const selectArtifact = useCallback((artifactId: string) => {+ setInternalArtifactId(artifactId);+ onArtifactNavigate?.(artifactId);+ if (artifactId === selectedCompareId) {+ setInternalCompareId(null);+ onArtifactCompare?.(null);+ }+ }, [onArtifactCompare, onArtifactNavigate, selectedCompareId]);+ const compareArtifact = useCallback((artifactId: string | null) => {+ const next = artifactId ? artifacts.find((item) => item.id !== artifactId)?.id ?? null : null;+ setInternalCompareId(next);+ onArtifactCompare?.(next);+ }, [artifacts, onArtifactCompare]);+ const closeArtifacts = useCallback(() => {+ setArtifactPanelOpen(false);+ onArtifactNavigate?.(null);+ }, [onArtifactNavigate]);++ useEffect(() => {+ if (activeArtifactId && artifacts.some((artifact) => artifact.id === activeArtifactId)) setArtifactPanelOpen(true);+ }, [activeArtifactId, artifacts]);+// Pulse the artifact-panel button when a new artifact lands while the// panel is closed, so streamed diagrams don't arrive silently.const prevArtifactCount = useRef(0);@@ -438,8 +486,15 @@ export function ChatInterface({<ArtifactPanelartifacts={artifacts}+ activeArtifactId={selectedArtifactId}+ compareArtifactId={selectedCompareId}open={artifactPanelOpen}- onClose={() => setArtifactPanelOpen(false)}+ onClose={closeArtifacts}+ onSelect={selectArtifact}+ onCompare={compareArtifact}+ onFollowUp={handleFollowUp}+ {...(onArtifactPin ? { onPin: onArtifactPin } : {})}+ {...(onOpenArtifactSource ? { onOpenSource: onOpenArtifactSource } : {})}/></div>);diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsxindex 2a319e1e1..9dcf7d528 100644--- a/packages/ui/src/chat/chat-message.tsx+++ b/packages/ui/src/chat/chat-message.tsx@@ -9,12 +9,12 @@ import { WorkingOrb } from "./working-orb";import { MessageActions } from "./message-actions";import { Markdown } from "../shared/markdown";import { SourceCitations, type SourceReference } from "./source-citations";-import type { ChatUIMessage } from "@repowise-dev/types/chat";+import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";interface ChatMessageProps {message: ChatUIMessage;repoId: string;- onViewArtifact?: (artifact: { type: string; data: Record<string, unknown> }) => void;+ onViewArtifact?: (artifact: ChatArtifact) => void;/** Optional avatar src for the assistant. Defaults to `/repowise-logo.png`. */assistantAvatarSrc?: string;/** Forwarded to `SourceCitations` so consumers can customise the link path. */diff --git a/packages/ui/src/chat/index.ts b/packages/ui/src/chat/index.tsindex 711c21315..0702fbd14 100644--- a/packages/ui/src/chat/index.ts+++ b/packages/ui/src/chat/index.ts@@ -1,4 +1,5 @@export * from "./artifact-panel";+export * from "./artifact-source";export * from "./artifacts";export * from "./chat-interface";export * from "./use-chat-scroll";diff --git a/packages/ui/src/chat/tool-call-group.tsx b/packages/ui/src/chat/tool-call-group.tsxindex e044a353a..e40585ea5 100644--- a/packages/ui/src/chat/tool-call-group.tsx+++ b/packages/ui/src/chat/tool-call-group.tsx@@ -4,11 +4,11 @@ import { useState } from "react";import { ChevronDown, ChevronRight } from "lucide-react";import { ToolCallBlock } from "./tool-call-block";import { WorkingOrb } from "./working-orb";-import type { ChatUIToolCall } from "@repowise-dev/types/chat";+import type { ChatArtifact, ChatUIToolCall } from "@repowise-dev/types/chat";interface ToolCallGroupProps {toolCalls: ChatUIToolCall[];- onViewArtifact?: (artifact: { type: string; data: Record<string, unknown> }) => void;+ onViewArtifact?: (artifact: ChatArtifact) => void;}/**diff --git a/packages/web/src/components/chat/chat-interface.test.tsx b/packages/web/src/components/chat/chat-interface.test.tsxindex c714685c2..974d676c2 100644--- a/packages/web/src/components/chat/chat-interface.test.tsx+++ b/packages/web/src/components/chat/chat-interface.test.tsx@@ -11,20 +11,26 @@ const mocks = vi.hoisted(() => ({sendMessage: vi.fn(),replace: vi.fn(),push: vi.fn(),+ router: null as { replace: ReturnType<typeof vi.fn>; push: ReturnType<typeof vi.fn> } | null,conversation: null as string | null,+ artifact: null as string | null,+ compare: null as string | null,activeConversation: null as string | null,+ shellProps: null as Record<string, unknown> | null,}));vi.mock("next/navigation", () => ({usePathname: () => "/repos/r1/chat",- useRouter: () => ({ replace: mocks.replace, push: mocks.push }),- useSearchParams: () => new URLSearchParams(- mocks.conversation ? `conversation=${mocks.conversation}` : "",- ),+ useRouter: () => mocks.router,+ useSearchParams: () => new URLSearchParams([+ ...(mocks.conversation ? [["conversation", mocks.conversation]] : []),+ ...(mocks.artifact ? [["artifact", mocks.artifact]] : []),+ ...(mocks.compare ? [["compare", mocks.compare]] : []),+ ]),}));vi.mock("swr", () => ({ default: () => ({ data: undefined }) }));vi.mock("next/link", () => ({ default: ({ children }: { children: React.ReactNode }) => <>{children}</> }));-vi.mock("@repowise-dev/ui/chat/chat-interface", () => ({ ChatInterface: () => <div /> }));+vi.mock("@repowise-dev/ui/chat/chat-interface", () => ({ ChatInterface: (props: Record<string, unknown>) => { mocks.shellProps = props; return <div />; } }));vi.mock("./model-selector", () => ({ ModelSelector: () => <div /> }));vi.mock("./conversation-history", () => ({ ConversationHistory: () => <div /> }));vi.mock("./repository-chat-provider", () => ({@@ -40,8 +46,12 @@ vi.mock("./repository-chat-provider", () => ({describe("chat route conversation lifecycle", () => {beforeEach(() => {vi.clearAllMocks();+ mocks.router = { replace: mocks.replace, push: mocks.push };mocks.conversation = null;mocks.activeConversation = null;+ mocks.artifact = null;+ mocks.compare = null;+ mocks.shellProps = null;});it("starts a fresh conversation on the plain chat URL", async () => {@@ -67,4 +77,31 @@ describe("chat route conversation lifecycle", () => {view.rerender(<ChatInterface repoId="r1" />);expect(mocks.loadConversation).not.toHaveBeenCalled();});++ it("passes artifact deep links through and preserves the conversation when navigating artifacts", async () => {+ mocks.conversation = "c42";+ mocks.artifact = "a1";+ mocks.compare = "a2";+ render(<ChatInterface repoId="r1" />);+ await waitFor(() => expect(mocks.shellProps).not.toBeNull());+ expect(mocks.shellProps).toMatchObject({ activeArtifactId: "a1", compareArtifactId: "a2" });+ (mocks.shellProps?.onArtifactNavigate as (id: string | null) => void)("a3");+ expect(mocks.replace).toHaveBeenCalledWith("/repos/r1/chat?conversation=c42&artifact=a3&compare=a2");+ (mocks.shellProps?.onArtifactNavigate as (id: string | null) => void)(null);+ expect(mocks.replace).toHaveBeenCalledWith("/repos/r1/chat?conversation=c42");+ });++ it("keeps artifact navigation callbacks stable across URL-only updates", async () => {+ mocks.conversation = "c42";+ mocks.artifact = "a1";+ const view = render(<ChatInterface repoId="r1" />);+ await waitFor(() => expect(mocks.shellProps).not.toBeNull());+ const navigate = mocks.shellProps?.onArtifactNavigate;+ const compare = mocks.shellProps?.onArtifactCompare;+ mocks.artifact = "a2";+ mocks.compare = "a1";+ view.rerender(<ChatInterface repoId="r1" />);+ expect(mocks.shellProps?.onArtifactNavigate).toBe(navigate);+ expect(mocks.shellProps?.onArtifactCompare).toBe(compare);+ });});diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsxindex 1e7b52d36..dd5739c06 100644--- a/packages/web/src/components/chat/chat-interface.tsx+++ b/packages/web/src/components/chat/chat-interface.tsx@@ -5,12 +5,12 @@ import useSWR from "swr";import Link from "next/link";import { usePathname, useRouter, useSearchParams } from "next/navigation";import { ChatInterface as ChatInterfaceShell } from "@repowise-dev/ui/chat/chat-interface";-import { useChatDraft } from "@repowise-dev/ui/chat";+import { getArtifactSourceTarget, useChatDraft } from "@repowise-dev/ui/chat";import { pageHref } from "@/lib/utils/page-href";import { getProviders } from "@/lib/api/providers";import { getRepoStats } from "@/lib/api/repos";-import { forkConversation } from "@/lib/api/chat";-import type { ChatUIMessage } from "@repowise-dev/types/chat";+import { forkConversation, setConversationArtifactPinned } from "@/lib/api/chat";+import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";import { ModelSelector } from "./model-selector";import { ConversationHistory } from "./conversation-history";import { useRepositoryChat } from "./repository-chat-provider";@@ -46,11 +46,17 @@ export function ChatInterface({selectedProvider,selectedModel,selectModel,+ artifactOverrides,+ replaceArtifact,} = useRepositoryChat();const pathname = usePathname();const router = useRouter();const searchParams = useSearchParams();+ const searchParamsRef = useRef(searchParams);+ searchParamsRef.current = searchParams;const urlConversationId = searchParams.get("conversation");+ const activeArtifactId = searchParams.get("artifact");+ const compareArtifactId = searchParams.get("compare");const [draft, setDraft] = useChatDraft(`repowise:chat-draft:${repoId}:${urlConversationId ?? conversationId ?? "new"}`,);@@ -132,6 +138,27 @@ export function ChatInterface({router.push(`${pathname}?conversation=${encodeURIComponent(fork.id)}`);await sendWithConversationModel(text);}, [conversationId, loadConversation, pathname, repoId, router, sendWithConversationModel]);+ const updateArtifactUrl = useCallback((key: "artifact" | "compare", artifactId: string | null) => {+ const next = new URLSearchParams(searchParamsRef.current.toString());+ if (artifactId) next.set(key, artifactId);+ else {+ next.delete(key);+ if (key === "artifact") next.delete("compare");+ }+ const query = next.toString();+ router.replace(query ? `${pathname}?${query}` : pathname);+ }, [pathname, router]);+ const pinArtifact = useCallback(async (artifact: ChatArtifact, pinned: boolean) => {+ if (!conversationId) return;+ replaceArtifact(await setConversationArtifactPinned(repoId, conversationId, artifact.id, pinned));+ }, [conversationId, repoId, replaceArtifact]);+ const navigateArtifact = useCallback((artifactId: string | null) => updateArtifactUrl("artifact", artifactId), [updateArtifactUrl]);+ const compareArtifact = useCallback((artifactId: string | null) => updateArtifactUrl("compare", artifactId), [updateArtifactUrl]);+ const openArtifactSource = useCallback((artifact: ChatArtifact) => {+ const target = getArtifactSourceTarget(artifact);+ if (target?.pageId) router.push(pageHref(repoId, target.pageId));+ else if (target?.path) router.push(pageHref(repoId, `file_page:${target.path}`));+ }, [repoId, router]);return (<div className="flex h-full min-h-0 overflow-hidden">@@ -161,6 +188,13 @@ export function ChatInterface({modelSelectorSlot={<ModelSelector repoId={repoId} activeProvider={selectedProvider} activeModel={selectedModel} onSelect={selectModel} />}onRetry={retryMessage}onEditAndResend={editAndResend}+ activeArtifactId={activeArtifactId}+ compareArtifactId={compareArtifactId}+ onArtifactNavigate={navigateArtifact}+ onArtifactCompare={compareArtifact}+ onArtifactPin={pinArtifact}+ onOpenArtifactSource={openArtifactSource}+ artifactOverrides={artifactOverrides}statusSlot={// Orientation, in one line: what was indexed, and which commit it was// indexed from. The branch and SHA used to sit in a second page headerdiff --git a/packages/web/src/components/chat/repository-chat-context.test.ts b/packages/web/src/components/chat/repository-chat-context.test.tsindex e9fe5df94..f97afe626 100644--- a/packages/web/src/components/chat/repository-chat-context.test.ts+++ b/packages/web/src/components/chat/repository-chat-context.test.ts@@ -1,9 +1,13 @@import { describe, expect, it } from "vitest";-import { getRepositoryChatContext } from "./repository-chat-context";+import { getRepositoryChatContext, getRepositoryChatContextQuery } from "./repository-chat-context";const params = (entries: Record<string, string>) => new URLSearchParams(entries);describe("getRepositoryChatContext", () => {+ it("excludes conversation workspace state from context identity", () => {+ const params = new URLSearchParams("file=src%2Fchat.ts&conversation=c1&artifact=a1&compare=a2");+ expect(getRepositoryChatContextQuery(params)).toBe("file=src%2Fchat.ts");+ });it("returns a repository fallback at the repo root", () => {expect(getRepositoryChatContext("/repos/r1")).toEqual({kind: "repository",diff --git a/packages/web/src/components/chat/repository-chat-context.ts b/packages/web/src/components/chat/repository-chat-context.tsindex 5e1ce7171..4c74e1cc5 100644--- a/packages/web/src/components/chat/repository-chat-context.ts+++ b/packages/web/src/components/chat/repository-chat-context.ts@@ -10,6 +10,20 @@ interface SearchParamsReader {getAll?(name: string): string[];}+const CONTEXT_QUERY_KEYS = [+ "page", "commit", "file", "node", "view", "package", "focus", "module", "tab", "lens",+] as const;++/** Keep workspace-only query state (conversation/artifact/compare) out of chat context identity. */+export function getRepositoryChatContextQuery(searchParams: SearchParamsReader): string {+ const relevant = new URLSearchParams();+ for (const key of CONTEXT_QUERY_KEYS) {+ const values = searchParams.getAll?.(key) ?? [searchParams.get(key)].filter((value): value is string => value !== null);+ for (const value of values) relevant.append(key, value);+ }+ return relevant.toString();+}+interface RouteDefinition {kind: ChatContextKind;targetKind?: ChatContextTargetKind;diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsxindex 733cba25c..040013ffe 100644--- a/packages/web/src/components/chat/repository-chat-dock.tsx+++ b/packages/web/src/components/chat/repository-chat-dock.tsx@@ -3,8 +3,9 @@import useSWR from "swr";import Link from "next/link";import { useRouter } from "next/navigation";-import { ChatDock } from "@repowise-dev/ui/chat";+import { ChatDock, getArtifactSourceTarget } from "@repowise-dev/ui/chat";import { getProviders } from "@/lib/api/providers";+import { setConversationArtifactPinned } from "@/lib/api/chat";import { pageHref } from "@/lib/utils/page-href";import { ModelSelector } from "./model-selector";import { ConversationHistory } from "./conversation-history";@@ -59,6 +60,16 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {})}onCancel={chat.cancel}buildCitationHref={(source) => pageHref(chat.repoId, source.pageId)}+ onArtifactPin={async (artifact, pinned) => {+ if (!chat.conversationId) return;+ chat.replaceArtifact(await setConversationArtifactPinned(chat.repoId, chat.conversationId, artifact.id, pinned));+ }}+ artifactOverrides={chat.artifactOverrides}+ onOpenArtifactSource={(artifact) => {+ const target = getArtifactSourceTarget(artifact);+ if (target?.pageId) router.push(pageHref(chat.repoId, target.pageId));+ else if (target?.path) router.push(pageHref(chat.repoId, `file_page:${target.path}`));+ }}onOpenFullChat={() => router.push(chat.conversationId? `/repos/${chat.repoId}/chat?conversation=${encodeURIComponent(chat.conversationId)}`diff --git a/packages/web/src/components/chat/repository-chat-provider.tsx b/packages/web/src/components/chat/repository-chat-provider.tsxindex 4a2cbcbf2..39a18020c 100644--- a/packages/web/src/components/chat/repository-chat-provider.tsx+++ b/packages/web/src/components/chat/repository-chat-provider.tsx@@ -12,7 +12,7 @@ import {import { usePathname, useSearchParams } from "next/navigation";import type { ChatContext as PageChatContext } from "@repowise-dev/ui/chat";import { useChat } from "@/lib/hooks/use-chat";-import { getRepositoryChatContext } from "./repository-chat-context";+import { getRepositoryChatContext, getRepositoryChatContextQuery } from "./repository-chat-context";type ChatController = ReturnType<typeof useChat>;@@ -64,9 +64,10 @@ export function RepositoryChatProvider({}, [modelIdentity, repoId]);const pathname = usePathname();const searchParams = useSearchParams();+ const contextQuery = getRepositoryChatContextQuery(searchParams);const pageContext = useMemo(- () => getRepositoryChatContext(pathname, searchParams),- [pathname, searchParams],+ () => getRepositoryChatContext(pathname, new URLSearchParams(contextQuery)),+ [contextQuery, pathname],);const {messages,@@ -77,6 +78,8 @@ export function RepositoryChatProvider({loadConversation,cancel,reset,+ artifactOverrides,+ replaceArtifact,} = chat;const value = useMemo<RepositoryChatValue>(() => ({@@ -94,6 +97,8 @@ export function RepositoryChatProvider({loadConversation,cancel,reset,+ artifactOverrides,+ replaceArtifact,}),[repoId,@@ -107,6 +112,8 @@ export function RepositoryChatProvider({loadConversation,cancel,reset,+ artifactOverrides,+ replaceArtifact,modelSelection,selectModel,],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 16ed45fe0..1eeaa6d79 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,41 @@ import type { ChatMessageResponse } from "@/lib/api/types";import { toChatUiMessages } from "./to-chat-ui-messages";describe("toChatUiMessages", () => {+ it("restores the persisted artifact envelope without rebuilding it", () => {+ const stored: ChatMessageResponse[] = [+ {+ id: "m1",+ conversation_id: "c1",+ role: "assistant",+ content: {+ tool_calls: [+ {+ id: "t1",+ name: "get_health",+ artifact: {+ id: "artifact-1",+ version: 1,+ type: "health",+ tool_name: "get_health",+ presentation: "health",+ data: { score: 8.4 },+ pinned: true,+ },+ },+ ],+ },+ created_at: "2026-08-28T00:00:00Z",+ },+ ];++ expect(toChatUiMessages(stored)[0]?.toolCalls[0]?.artifact).toMatchObject({+ id: "artifact-1",+ type: "health",+ data: { score: 8.4 },+ pinned: true,+ });+ });+it("restores artifacts from stored tool results", () => {const stored: ChatMessageResponse[] = [{@@ -25,7 +60,7 @@ describe("toChatUiMessages", () => {];const [message] = toChatUiMessages(stored);- expect(message?.toolCalls[0]?.artifact).toEqual({+ expect(message?.toolCalls[0]?.artifact).toMatchObject({type: "risk_report",data: { targets: { "src/a.ts": { trend: "increasing" } } },});diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.tsindex 3f43d2968..1f169b137 100644--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts@@ -17,12 +17,23 @@ export function toChatUiMessages(arguments: toolCall.arguments ?? {},result: toolCall.result,summary: toolCall.summary,- ...(toolCall.result+ ...(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,},}diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsxindex c4324ccd3..98f843235 100644--- a/packages/web/src/lib/hooks/use-chat.test.tsx+++ b/packages/web/src/lib/hooks/use-chat.test.tsx@@ -203,4 +203,14 @@ describe("useChat lifecycle", () => {expect(result.current.messages).toEqual([]);expect(result.current.conversationId).toBeNull();});++ it("stores artifact mutations outside transcript messages", () => {+ const { result } = renderHook(() => useChat("r1"));+ const artifact = { id: "a1", version: 1 as const, type: "risk", tool_name: "get_risk", presentation: "risk", pinned: true, data: {} };+ const messages = result.current.messages;+ act(() => result.current.replaceArtifact(artifact));+ expect(result.current.artifactOverrides.a1).toEqual(artifact);+ expect(result.current.messages).toBe(messages);+ });+});diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.tsindex 3acaf910c..3b7918555 100644--- a/packages/web/src/lib/hooks/use-chat.ts+++ b/packages/web/src/lib/hooks/use-chat.ts@@ -4,6 +4,7 @@ import { useCallback, useEffect, useRef, useState } from "react";import { postChatMessage, getConversation } from "@/lib/api/chat";import type { ChatSSEEvent } from "@/lib/api/types";import type {+ ChatArtifact,ChatContext,ChatUIToolCall as ChatToolCall,ChatUIMessage as ChatMessage,@@ -43,6 +44,7 @@ function stopRunningTools(message: ChatMessage, summary: string): ChatMessage {export function useChat(repoId: string) {const [state, setState] = useState<UseChatState>(EMPTY_CHAT_STATE);+ const [artifactOverrides, setArtifactOverrides] = useState<Record<string, ChatArtifact>>({});const abortRef = useRef<AbortController | null>(null);const activeRepoRef = useRef(repoId);@@ -57,6 +59,7 @@ export function useChat(repoId: string) {activeRepoRef.current = repoId;conversationIdRef.current = null;setState(EMPTY_CHAT_STATE);+ setArtifactOverrides({});}return () => abortRef.current?.abort();}, [repoId]);@@ -243,7 +246,7 @@ export function useChat(repoId: string) {tc.id === ev.tool_id? {...tc,- result: ev.artifact.data,+ result: ev.artifact.data as unknown as Record<string, unknown>,summary: ev.summary,artifact: ev.artifact,status: "done" as const,@@ -301,6 +304,7 @@ export function useChat(repoId: string) {isStreaming: false,error: null,});+ setArtifactOverrides({});} catch (err) {if (activeRepoRef.current !== repoId || loadRequestRef.current !== requestId) return;setState((prev) => ({@@ -330,8 +334,13 @@ export function useChat(repoId: string) {loadRequestRef.current += 1;conversationIdRef.current = null;setState(EMPTY_CHAT_STATE);+ setArtifactOverrides({});+ }, []);++ const replaceArtifact = useCallback((artifact: ChatArtifact) => {+ setArtifactOverrides((current) => ({ ...current, [artifact.id]: artifact }));}, []);const visibleState = activeRepoRef.current === repoId ? state : EMPTY_CHAT_STATE;- return { ...visibleState, sendMessage, loadConversation, cancel, reset };+ return { ...visibleState, artifactOverrides, sendMessage, loadConversation, cancel, reset, replaceArtifact };}diff --git a/tests/unit/server/test_chat_artifacts.py b/tests/unit/server/test_chat_artifacts.pynew file mode 100644index 000000000..3519560d5--- /dev/null+++ b/tests/unit/server/test_chat_artifacts.py@@ -0,0 +1,107 @@+"""Durable chat artifact envelopes and legacy-row compatibility."""++from __future__ import annotations++from repowise.server.chat_artifacts import (+ create_artifact_envelope,+ find_artifact,+ normalize_message_artifacts,+ set_artifact_pinned,+)+++def test_new_envelope_has_a_stable_id_and_one_payload() -> None:+ payload = {"targets": {"src/a.py": {"trend": "increasing"}}}++ artifact = create_artifact_envelope(+ tool_name="get_risk",+ artifact_type="risk",+ presentation="risk",+ data=payload,+ title="Risk assessment",+ evidence_basis="measured",+ )+ content = {+ "tool_calls": [+ {+ "id": "tool-1",+ "name": "get_risk",+ "artifact": artifact,+ }+ ]+ }++ restored = normalize_message_artifacts(content, message_id="message-1")++ assert restored["tool_calls"][0]["artifact"]["id"] == artifact["id"]+ assert restored["tool_calls"][0]["artifact"]["data"] is payload+ assert restored["tool_calls"][0]["artifact"]["evidence"]["basis"] == "measured"+ assert "result" not in restored["tool_calls"][0]+++def test_legacy_result_restores_with_a_deterministic_artifact_id() -> None:+ legacy = {+ "tool_calls": [+ {+ "id": "tool-1",+ "name": "get_context",+ "result": {"targets": {}},+ "artifact_type": "context",+ }+ ]+ }++ first = normalize_message_artifacts(legacy, message_id="message-1")+ second = normalize_message_artifacts(legacy, message_id="message-1")++ first_call = first["tool_calls"][0]+ assert first_call["artifact"]["id"] == second["tool_calls"][0]["artifact"]["id"]+ assert first_call["artifact"]["type"] == "context"+ assert first_call["artifact"]["data"] == {"targets": {}}+ assert "result" not in first_call+ assert "artifact_type" not in first_call+++def test_pin_upgrades_a_legacy_row_without_duplicating_payload() -> None:+ legacy = {"tool_calls": [{"id": "tool-1", "name": "get_health", "result": {"score": 8.4}}]}+ normalized = normalize_message_artifacts(legacy, message_id="message-1")+ artifact_id = normalized["tool_calls"][0]["artifact"]["id"]++ updated, found = set_artifact_pinned(+ legacy,+ message_id="message-1",+ artifact_id=artifact_id,+ pinned=True,+ )++ assert found is True+ call = updated["tool_calls"][0]+ assert call["artifact"]["pinned"] is True+ assert call["artifact"]["data"] == {"score": 8.4}+ assert "result" not in call+++def test_find_artifact_handles_malformed_rows_safely() -> None:+ content = {"tool_calls": [None, {"artifact": "bad"}, {"artifact": {"id": "a1"}}]}++ assert find_artifact(content, message_id="message-1", artifact_id="missing") is None+++def test_evidence_normalizes_real_coverage_and_collection_limits() -> None:+ artifact = create_artifact_envelope(+ tool_name="get_health",+ artifact_type="health",+ presentation="health",+ evidence_basis="measured",+ data={+ "top_findings": [{"id": "f1"}],+ "top_findings_total": 9,+ "coverage": {"summary": {}, "files": [], "files_total": 4, "files_emitted": 0},+ },+ )++ assert artifact["evidence"]["coverage"] == {"available": True}+ assert artifact["evidence"]["limits"]["collections"] == [+ {"name": "top findings", "total": 9, "emitted": 1},+ {"name": "coverage files", "total": 4, "emitted": 0},+ ]diff --git a/tests/unit/server/test_chat_change_risk_summary.py b/tests/unit/server/test_chat_change_risk_summary.pyindex 3ffb11215..137c1026a 100644--- a/tests/unit/server/test_chat_change_risk_summary.py+++ b/tests/unit/server/test_chat_change_risk_summary.py@@ -2,7 +2,7 @@from __future__ import annotations-from repowise.server.chat_tools import get_tool_registry+from repowise.server.chat_tools import get_tool_catalogfrom repowise.server.routers.chat import _build_tool_summary@@ -24,8 +24,8 @@ def test_get_change_risk_summary_is_not_generic_completed():def test_every_chat_registry_tool_has_a_non_generic_summary_shape():"""Smoke: registered tools either specialize or return Completed only as fallback."""- registry = get_tool_registry()- assert "get_change_risk" in registry+ catalog = get_tool_catalog(None)+ assert "get_change_risk" in {tool.entry.name for tool in catalog}# get_change_risk must not fall through to the generic Completed string.assert (_build_tool_summary("get_change_risk", {"ref": "main..HEAD", "review_priority": "Typical"})diff --git a/tests/unit/server/test_chat_stream_terminal_event.py b/tests/unit/server/test_chat_stream_terminal_event.pyindex f3e1fec20..11c54594e 100644--- a/tests/unit/server/test_chat_stream_terminal_event.py+++ b/tests/unit/server/test_chat_stream_terminal_event.py@@ -31,8 +31,10 @@ from sqlalchemy import inspectfrom sqlalchemy.ext.asyncio import AsyncSession, async_sessionmaker, create_async_enginefrom sqlalchemy.pool import StaticPool+from repowise.core.persistence import crudfrom repowise.core.persistence.database import init_dbfrom repowise.core.persistence.models import Repository+from repowise.server.chat_artifacts import normalize_message_artifactsfrom repowise.server.routers import chat_NOW = datetime(2026, 8, 15, 10, 0, 0, tzinfo=UTC)@@ -105,9 +107,7 @@ def _data_events(body: str) -> list[dict]:async def _post(app: FastAPI, payload: dict) -> str:transport = ASGITransport(app=app)async with AsyncClient(transport=transport, base_url="http://testserver") as client:- response = await client.post(- f"/api/repos/{_REPO_ID}/chat/messages", json=payload- )+ response = await client.post(f"/api/repos/{_REPO_ID}/chat/messages", json=payload)assert response.status_code == 200, response.textreturn response.text@@ -120,9 +120,7 @@ async def test_unknown_conversation_ends_the_stream_with_a_typed_error():"repowise.server.routers.chat.get_chat_provider_instance",return_value=_SilentProvider(),):- body = await _post(- app, {"message": "hi", "conversation_id": "no-such-conversation"}- )+ body = await _post(app, {"message": "hi", "conversation_id": "no-such-conversation"})events = _data_events(body)assert events, f"stream carried no readable data events: {body!r}"@@ -169,9 +167,7 @@ async def test_conversation_history_supports_rename_pin_fork_and_delete_undo():assert updated.json()["title"] == "Pinned investigation"assert updated.json()["pinned"] is True- messages = await client.get(- f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"- )+ messages = await client.get(f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}")user_message_id = messages.json()["messages"][0]["id"]forked_before = await client.post(f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}/fork",@@ -199,9 +195,7 @@ async def test_conversation_history_supports_rename_pin_fork_and_delete_undo():assert forked.status_code == 200assert forked.json()["message_count"] == 2- deleted = await client.delete(- f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}"- )+ deleted = await client.delete(f"/api/repos/{_REPO_ID}/chat/conversations/{conversation_id}")assert deleted.status_code == 200listed = await client.get(f"/api/repos/{_REPO_ID}/chat/conversations")assert all(row["id"] != conversation_id for row in listed.json())@@ -214,6 +208,64 @@ async def test_conversation_history_supports_rename_pin_fork_and_delete_undo():assert any(row["id"] == conversation_id for row in listed.json())+async def test_artifact_lookup_pin_and_repository_isolation():+ app = await _make_app()+ async with app.state.session_factory() as session:+ conversation = await crud.create_conversation(+ session,+ repository_id=_REPO_ID,+ title="Artifacts",+ )+ message = await crud.create_chat_message(+ session,+ conversation_id=conversation.id,+ role="assistant",+ content={+ "tool_calls": [+ {+ "id": "tool-1",+ "name": "get_context",+ "result": {"targets": {"src/a.py": {}}},+ "artifact_type": "context",+ }+ ]+ },+ )+ await session.commit()++ normalized = normalize_message_artifacts(+ json.loads(message.content_json),+ message_id=message.id,+ )+ artifact_id = normalized["tool_calls"][0]["artifact"]["id"]++ transport = ASGITransport(app=app)+ async with AsyncClient(transport=transport, base_url="http://testserver") as client:+ fetched = await client.get(+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation.id}/artifacts/{artifact_id}"+ )+ assert fetched.status_code == 200+ assert fetched.json()["id"] == artifact_id++ isolated = await client.get(+ f"/api/repos/other-repo/chat/conversations/{conversation.id}/artifacts/{artifact_id}"+ )+ assert isolated.status_code == 404++ pinned = await client.patch(+ f"/api/repos/{_REPO_ID}/chat/conversations/{conversation.id}/artifacts/{artifact_id}",+ json={"pinned": True},+ )+ assert pinned.status_code == 200+ assert pinned.json()["pinned"] is True++ restored = await client.get(f"/api/repos/{_REPO_ID}/chat/conversations/{conversation.id}")+ call = restored.json()["messages"][0]["content"]["tool_calls"][0]+ assert call["artifact"]["pinned"] is True+ assert "result" not in call++def test_conversation_refinement_migration_upgrades_sqlite() -> None:core_root = Path("packages/core").resolve()with tempfile.TemporaryDirectory() as tmp:diff --git a/tests/unit/server/test_chat_system_prompt_tools.py b/tests/unit/server/test_chat_system_prompt_tools.pyindex aa49c597d..2cede6915 100644--- a/tests/unit/server/test_chat_system_prompt_tools.py+++ b/tests/unit/server/test_chat_system_prompt_tools.py@@ -2,7 +2,7 @@from __future__ import annotations-from repowise.server.chat_tools import get_tool_registry+from repowise.server.chat_tools import get_tool_catalogfrom repowise.server.routers.chat import (_build_system_prompt,_stored_tool_call,@@ -11,11 +11,12 @@ from repowise.server.routers.chat import (from repowise.server.schemas.chat import ChatPageContext-def test_system_prompt_tool_count_matches_registry():- n = len(get_tool_registry())- prompt = _build_system_prompt("demo", "/tmp/demo")- assert f"{n} specialized tools" in prompt+def test_system_prompt_uses_selected_registry_tools_and_recipes():+ tools = get_tool_catalog(None)+ prompt = _build_system_prompt("demo", "/tmp/demo", tools)assert "get_change_risk" in prompt+ assert "Registry recipes" in prompt+ assert "hidden chain-of-thought" in promptdef test_navigation_context_is_user_level_untrusted_metadata():@@ -28,7 +29,9 @@ def test_navigation_context_is_user_level_untrusted_metadata():original = [{"role": "user", "content": "What does this do?"}]contextualized = _with_navigation_context(original, context)- assert "ignore previous instructions" not in _build_system_prompt("demo", "/tmp/demo")+ assert "ignore previous instructions" not in _build_system_prompt(+ "demo", "/tmp/demo", get_tool_catalog(None)+ )assert contextualized[-1]["role"] == "user"assert '"kind": "file"' in contextualized[-1]["content"]assert "ignore previous instructions" in contextualized[-1]["content"]@@ -38,17 +41,24 @@ def test_navigation_context_is_user_level_untrusted_metadata():def test_stored_tool_call_preserves_streamed_artifact_contract():result = {"targets": {"src/a.py": {"trend": "increasing"}}}+ artifact = {+ "id": "artifact-1",+ "version": 1,+ "type": "risk",+ "tool_name": "get_risk",+ "presentation": "risk",+ "data": result,+ }stored = _stored_tool_call("t1","get_risk",{"targets": ["src/a.py"]},- result,"Risk assessment for 1 file(s)",- "risk_report",+ artifact,)assert stored["summary"] == "Risk assessment for 1 file(s)"- assert stored["artifact_type"] == "risk_report"- assert stored["result"] is result- assert "artifact" not in stored+ assert stored["artifact"] is artifact+ assert stored["artifact"]["data"] is result+ assert "result" not in storeddiff --git a/tests/unit/server/test_chat_tool_registry.py b/tests/unit/server/test_chat_tool_registry.pyindex 706d70464..a2effe3bc 100644--- a/tests/unit/server/test_chat_tool_registry.py+++ b/tests/unit/server/test_chat_tool_registry.py@@ -1,45 +1,78 @@-"""Drift guard: chat tool registry stays a documented 7-tool subset."""+"""Chat consumes the configured MCP registry without maintaining a copy."""from __future__ import annotations-from repowise.server.chat_tools import get_tool_registry+from unittest.mock import patch+import pytest-def test_chat_tool_registry_is_the_documented_seven() -> None:- names = set(get_tool_registry())- assert names == {- "get_overview",- "get_context",- "get_risk",- "get_change_risk",- "get_why",- "search_codebase",- "get_dead_code",+from repowise.core.registry import ToolEntry+from repowise.server import chat_tools+from repowise.server.mcp_server import _tool_selection, ensure_full_surface+++def test_chat_catalog_matches_the_selected_mcp_surface(tmp_path) -> None:+ ensure_full_surface()+ selected = _tool_selection.resolve_enabled_tools(+ _tool_selection.mcp_tool_registry.entries(),+ is_workspace=_tool_selection._is_workspace(str(tmp_path)),+ override=None,+ )++ catalog = chat_tools.get_tool_catalog(str(tmp_path))++ assert {tool.entry.name for tool in catalog} == selected+++def test_chat_honors_the_repository_mcp_allowlist(tmp_path) -> None:+ ensure_full_surface()+ with patch.object(+ _tool_selection,+ "_read_config_override",+ return_value=["get_answer", "get_health"],+ ):+ catalog = chat_tools.get_tool_catalog(str(tmp_path))++ assert [tool.entry.name for tool in catalog] == ["get_answer", "get_health"]+++def test_chat_llm_schemas_are_the_fastmcp_generated_schemas(tmp_path) -> None:+ ensure_full_surface()+ schemas = {+ item["function"]["name"]: item["function"]["parameters"]+ for item in chat_tools.get_tool_schemas_for_llm(str(tmp_path))}+ for name, parameters in schemas.items():+ assert parameters == _tool_selection.get_registered_tool(name).parameters+++def test_artifact_and_evidence_metadata_come_from_registry(tmp_path) -> None:+ catalog = {tool.entry.name: tool.entry for tool in chat_tools.get_tool_catalog(str(tmp_path))}++ assert catalog["get_risk"].artifact_type == "risk"+ assert catalog["get_risk"].presentation == "risk"+ assert catalog["get_risk"].evidence_basis == "measured"+ assert catalog["search_codebase"].evidence_basis == "inferred"+-def test_chat_dead_code_schema_default_matches_risk_cap() -> None:- from repowise.core.analysis.dead_code.risk_factors import RISK_CAP_CONFIDENCE- from repowise.server.chat_tools import get_tool_registry+async def test_mutating_tools_require_an_explicit_confirmation() -> None:+ called = False- params = get_tool_registry()["get_dead_code"].parameters["properties"]["min_confidence"]- assert params["default"] == RISK_CAP_CONFIDENCE+ async def mutate() -> dict:+ nonlocal called+ called = True+ return {"changed": True}+ entry = ToolEntry(fn=mutate, name="mutate", safety="mutating")-def test_chat_get_context_include_matches_cli_blocks() -> None:- """Chat schema must advertise the same include blocks MCP/CLI accept.+ result = await chat_tools.execute_entry(entry, {}, confirmed=False)- A stale enum that listed docs/freshness/source and omitted skeleton/health- made the chat model request a no-op ``source`` block and never ask for- skeleton or health — both of which get_context actually serves.- """- from repowise.cli.commands.context_cmd import _INCLUDE_BLOCKS- from repowise.server.chat_tools import get_tool_registry+ assert called is False+ assert result["error_code"] == "confirmation_required"+ assert result["requires_confirmation"] is True- props = get_tool_registry()["get_context"].parameters["properties"]- enum = props["include"]["items"]["enum"]- assert set(enum) == set(_INCLUDE_BLOCKS)- assert "compact" in props- assert props["compact"]["default"] is True- for bogus in ("docs", "freshness", "source"):- assert bogus not in enum+ result = await chat_tools.execute_entry(entry, {}, confirmed=True)+ assert called is True+ assert result == {"changed": True}diff --git a/tests/unit/server/test_chat_tool_repo_scope.py b/tests/unit/server/test_chat_tool_repo_scope.pyindex 5bd1219b2..b104f3b8b 100644--- a/tests/unit/server/test_chat_tool_repo_scope.py+++ b/tests/unit/server/test_chat_tool_repo_scope.py@@ -14,6 +14,7 @@ workspace:from __future__ import annotations+from dataclasses import replacefrom types import SimpleNamespacefrom typing import Any@@ -46,12 +47,19 @@ def captured_call(monkeypatch):"""Replace get_overview with a recorder and return the recorded kwargs."""seen: dict[str, Any] = {}- async def _fake_get_overview(**kwargs):- seen.update(kwargs)+ async def _fake_get_overview(repo: str | None = None):+ seen["repo"] = reporeturn {"ok": True}- tool_def = chat_tools.get_tool_registry()["get_overview"]- monkeypatch.setattr(tool_def, "function", _fake_get_overview)+ original = next(+ tool for tool in chat_tools.get_tool_catalog(None) if tool.entry.name == "get_overview"+ )+ replacement = chat_tools.ChatToolContract(+ entry=replace(original.entry, fn=_fake_get_overview),+ description=original.description,+ parameters=original.parameters,+ )+ monkeypatch.setattr(chat_tools, "get_tool_catalog", lambda _repo_path: [replacement])return seendiff --git a/tests/unit/server/test_mcp_tools_router.py b/tests/unit/server/test_mcp_tools_router.pyindex 111e69e63..d0ed6a472 100644--- a/tests/unit/server/test_mcp_tools_router.py+++ b/tests/unit/server/test_mcp_tools_router.py@@ -25,6 +25,10 @@ def test_describe_tool_surface_single_repo(tmp_path, monkeypatch):by_name = {t["name"]: t for t in surface["tools"]}assert by_name["get_answer"]["enabled"] is Trueassert by_name["get_answer"]["tier"] == "canonical"+ assert by_name["get_answer"]["artifact_type"] == "answer"+ assert by_name["get_answer"]["presentation"] == "answer"+ assert by_name["get_answer"]["safety"] == "read_only"+ assert by_name["get_risk"]["evidence_basis"] == "measured"assert by_name["list_repos"]["tier"] == "utility"assert by_name["list_repos"]["eligible"] is Falseassert by_name["list_repos"]["enabled"] is False@@ -84,6 +88,10 @@ async def test_router_get_and_patch(tmp_path, monkeypatch):got = await mcp_router.get_tool_surface(request=None, repo_id="r1")assert got.repo_id == "r1"assert any(t.name == "get_answer" and t.enabled for t in got.tools)+ answer = next(t for t in got.tools if t.name == "get_answer")+ assert answer.artifact_type == "answer"+ assert answer.presentation == "answer"+ assert answer.safety == "read_only"from repowise.server.schemas import UpdateMcpToolsRequest