Skip to content

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

feat(chat): check each figure in an answer against the turn's tool results (#3793)

Raghav Chamadiya6b10fd472060
diff --git a/packages/server/src/repowise/server/chat_figures.py b/packages/server/src/repowise/server/chat_figures.py
new file mode 100644
index 000000000..1b979c9ee
--- /dev/null
+++ b/packages/server/src/repowise/server/chat_figures.py
@@ -0,0 +1,482 @@
+"""Post-turn numeric check: each figure in an answer should come from a tool.
+
+``check_figures`` reads every number in the final answer text, sets aside the
+ones that are not figures (dates, years, versions, ``file:line`` citations,
+list ordinals, identifiers and hashes, anything inside code, numbers the
+question already holds) and looks each remaining one up among the numbers of
+the turn's tool results and views, then, for a figure still unmatched, among
+earlier turns' results. The lookup tolerates rounding to the precision the
+answer shows, percent and fraction forms (``73%`` for ``0.734``), size and time
+units (``1.2 MB``, ``250 ms``), ``k``/``M`` suffixes and thousands separators;
+a hedged figure ("about 1,200", "24,000+") gets 10%. A signed figure (``-5``)
+only matches a value of that sign; an unsigned one matches either.
+
+A number right after a position or label word (``_LABEL_WORDS``: line, top,
+first, level, tier, step, version...) is never checked, even when it is a real
+count such as "the top 5 files". That is a deliberate false negative: those
+words far more often introduce a position, rank or label than a figure, and a
+missed check costs less than a false flag.
+
+Reading evidence is bounded: past ``MAX_NODES_PER_ARTIFACT`` or
+``MAX_CHARS_PER_ARTIFACT`` in one result, or ``MAX_NODES_TOTAL`` or
+``MAX_CHARS_TOTAL`` overall, the rest is not read, and a figure that matched
+nothing read counts as not checked rather than flagged.
+
+A figure with no match is flagged, never removed. A matched one carries the
+``artifact_id`` of the tool result it came from, which is its citation.
+Offsets are UTF-16 code units so a browser can slice the text with them.
+"""
+
+from __future__ import annotations
+
+import bisect
+import re
+from collections.abc import Iterable
+from dataclasses import dataclass, field
+from typing import Any
+
+# A leading minus is a sign only when no word character or digit precedes it,
+# so "10-20" stays a range and "utf-8" an identifier.
+_NUMBER = re.compile(
+ r"(?:(?<![A-Za-z0-9_])[-−])?"
+ r"(?:[0-9]{1,3}(?:,[0-9]{3})+(?:\.[0-9]+)?|[0-9]+(?:\.[0-9]+)?)"
+)
+_UNIT = re.compile(
+ r" ?(%|percent\b|ms\b|milliseconds?\b|secs?\b|seconds?\b|s\b|mins?\b|minutes?\b"
+ r"|hrs?\b|hours?\b|h\b|days?\b|[KMGT]i?B\b|kB\b|bytes?\b|B\b|k\b|K\b|M\b"
+ r"|thousand\b|million\b|billion\b|x\b|×)",
+ re.ASCII,
+)
+
+MAX_NODES_PER_ARTIFACT = 20_000
+MAX_CHARS_PER_ARTIFACT = 256_000
+MAX_NODES_TOTAL = 100_000
+MAX_CHARS_TOTAL = 1_000_000
+
+_KB, _MB, _GB, _TB = 1024.0, 1024.0**2, 1024.0**3, 1024.0**4
+#: unit -> (family, multipliers to the family's base). Sizes read both 1024 and 1000.
+_SCALES: dict[str, tuple[str, tuple[float, ...]]] = {
+ "ms": ("time", (1.0,)),
+ "s": ("time", (1e3,)),
+ "min": ("time", (6e4,)),
+ "h": ("time", (3.6e6,)),
+ "day": ("time", (8.64e7,)),
+ "B": ("size", (1.0,)),
+ "KB": ("size", (_KB, 1e3)),
+ "MB": ("size", (_MB, 1e6)),
+ "GB": ("size", (_GB, 1e9)),
+ "TB": ("size", (_TB, 1e12)),
+ "k": ("count", (1e3,)),
+ "M": ("count", (1e6,)),
+ "bn": ("count", (1e9,)),
+}
+_UNIT_ALIASES = {
+ "percent": "%",
+ "millisecond": "ms",
+ "milliseconds": "ms",
+ "sec": "s",
+ "secs": "s",
+ "second": "s",
+ "seconds": "s",
+ "mins": "min",
+ "minute": "min",
+ "minutes": "min",
+ "hr": "h",
+ "hrs": "h",
+ "hour": "h",
+ "hours": "h",
+ "days": "day",
+ "KiB": "KB",
+ "kB": "KB",
+ "MiB": "MB",
+ "GiB": "GB",
+ "TiB": "TB",
+ "byte": "B",
+ "bytes": "B",
+ "K": "k",
+ "thousand": "k",
+ "million": "M",
+ "billion": "bn",
+ "×": "x",
+}
+
+# Spans whose numbers are never figures: code, links, dates, file:line, refs.
+_MASKS = re.compile(
+ r"```.*?(?:```|\Z)|~~~.*?(?:~~~|\Z)|``[^`]*``|`[^`\n]*`"
+ r"|https?://\S+|\]\([^)\s]*\)"
+ r"|[0-9]{4}-[0-9]{2}-[0-9]{2}(?:[T ][0-9]{2}:[0-9]{2}(?::[0-9]{2})?(?:\.[0-9]+)?Z?)?"
+ r"|[\w./\\-]+\.[A-Za-z]\w*:[0-9]+(?:[-–:][0-9]+)?"
+ r"|#[0-9]+|\b(?=[0-9a-f]*[a-f])(?=[0-9a-f]*[0-9])[0-9a-f]{7,40}\b",
+ re.DOTALL,
+)
+# The word just before a number that makes it a position, label or version.
+# Each one also hides real counts ("top 5"): a deliberate false negative.
+_LABEL_WORDS = frozenset(
+ {
+ "line", "lines", "row", "rows", "column", "col", "version", "versions", "v", "release",
+ "python", "node", "java", "go", "ruby", "php", "typescript", "es", "schema", "revision",
+ "migration", "alembic", "step", "steps", "phase", "stage", "section", "sections",
+ "part", "item", "items", "chapter", "wave", "track", "lane", "option", "options",
+ "rank", "top", "bottom", "first", "last", "no", "number", "pr", "prs", "issue",
+ "issues", "pull", "tier", "level", "priority", "round", "iteration", "turn", "page",
+ "pages", "figure", "table", "question", "point"
+ }
+)
+_MONTHS = frozenset(
+ {
+ "jan", "feb", "mar", "apr", "may", "jun", "jul", "aug", "sep", "sept", "oct", "nov",
+ "dec", "january", "february", "march", "april", "june", "july", "august", "september",
+ "october", "november", "december"
+ }
+)
+_HEDGES = re.compile(
+ r"(?:~|≈|<|>|≤|≥|\b(?:about|around|approximately|approx\.?|roughly|nearly"
+ r"|almost|over|under|some|more than|less than|fewer than|at least|at most|up to"
+ r"|close to))\s*$",
+ re.IGNORECASE,
+)
+# What may precede a list ordinal on its line: indent, quote, heading, bullet, bold.
+_LIST_MARKER = re.compile(r"[ \t]*(?:>[ \t]*)*(?:#{1,6}[ \t]+)?(?:[-*+][ \t]+)?(?:\*\*)?")
+# Emphasis may sit between the word and the number ("line **485**").
+_WORD_BEFORE = re.compile(r"([A-Za-z]+)\.?[ \t]*[*_]*$")
+_WORD_AFTER = re.compile(r"[ \t]*([A-Za-z]+)")
+_HEDGE_RELATIVE = 0.10
+
+
+def _word_char(ch: str) -> bool:
+ """An ASCII letter, digit or underscore: CJK around a number is prose, not an identifier."""
+ return ch.isascii() and (ch.isalnum() or ch == "_")
+
+
+def _letter(ch: str) -> bool:
+ return ch.isascii() and ch.isalpha()
+
+
+@dataclass(frozen=True)
+class Figure:
+ """One number in an answer that the check looked up."""
+
+ text: str
+ start: int
+ end: int
+ verified: bool
+ artifact_id: str | None = None
+
+ def to_json(self) -> dict[str, Any]:
+ out: dict[str, Any] = {
+ "text": self.text,
+ "start": self.start,
+ "end": self.end,
+ "verified": self.verified,
+ }
+ if self.artifact_id:
+ out["artifact_id"] = self.artifact_id
+ return out
+
+
+@dataclass
+class FigureCheck:
+ """The figures looked up, and how many were left unchecked because the
+ evidence was past the read cap."""
+
+ figures: list[Figure] = field(default_factory=list)
+ not_checked: int = 0
+
+ def diagnostics(self) -> dict[str, int]:
+ if not self.figures and not self.not_checked:
+ return {}
+ out = {
+ "figures_checked": len(self.figures),
+ "figures_unverified": sum(not f.verified for f in self.figures),
+ }
+ if self.not_checked:
+ out["figures_not_checked"] = self.not_checked
+ return out
+
+
+@dataclass(frozen=True)
+class _Reading:
+ value: float
+ signed: bool
+ decimals: int
+ unit: str | None
+ text_end: int
+
+
+def _read(text: str, match: re.Match[str]) -> _Reading:
+ raw = match.group().replace(",", "").replace("−", "-")
+ decimals = len(raw.partition(".")[2])
+ unit_match = _UNIT.match(text, match.end())
+ if unit_match is None:
+ unit, end = None, match.end()
+ else:
+ unit = _UNIT_ALIASES.get(unit_match.group(1), unit_match.group(1))
+ end = unit_match.end()
+ return _Reading(float(raw), raw.startswith("-"), decimals, unit, end)
+
+
+def _values(reading: _Reading) -> list[float]:
+ """The reading's value and its forms in the other units of its family."""
+ value, unit = reading.value, reading.unit
+ if unit == "%":
+ return [value, value / 100]
+ if unit not in _SCALES:
+ return [value]
+ family, multipliers = _SCALES[unit]
+ out = [value]
+ for mult in multipliers:
+ base = value * mult
+ out.append(base)
+ if family in ("time", "size"):
+ for other, (other_family, other_mults) in _SCALES.items():
+ if other_family == family and other != unit:
+ out.extend(base / m for m in other_mults)
+ return out
+
+
+# ---------------------------------------------------------------------------
+# Source pool
+# ---------------------------------------------------------------------------
+
+
+@dataclass
+class _Budget:
+ nodes: int = MAX_NODES_TOTAL
+ chars: int = MAX_CHARS_TOTAL
+
+
+class _Pool:
+ """The numbers some evidence holds, sorted, with the artifact each came from.
+
+ Raw values only, plus the two expansions an answer's own conversions do
+ not cover: a source percent read as a fraction and a ``k``/``M`` suffix
+ read in full, both only when the answer states a unitless figure.
+ """
+
+ def __init__(self, budget: _Budget, *, expand: bool) -> None:
+ self._entries: list[tuple[float, int, str | None]] = []
+ self._values: list[float] = []
+ self._budget = budget
+ self._expand = expand
+ self.truncated = False
+
+ def add_all(self, artifact_id: str | None, data: Any) -> None:
+ nodes, chars = MAX_NODES_PER_ARTIFACT, MAX_CHARS_PER_ARTIFACT
+ stack = [data]
+ while stack:
+ if nodes <= 0 or chars <= 0 or self._budget.nodes <= 0 or self._budget.chars <= 0:
+ self.truncated = True
+ return
+ node = stack.pop()
+ nodes -= 1
+ self._budget.nodes -= 1
+ if isinstance(node, bool) or node is None:
+ continue
+ if isinstance(node, (int, float)):
+ if node == node: # NaN is no figure
+ self._add(float(node), artifact_id)
+ elif isinstance(node, str):
+ chars -= len(node)
+ self._budget.chars -= len(node)
+ self._add_text(node, artifact_id)
+ elif isinstance(node, dict):
+ # A count the answer may state is often the size of a list or map.
+ self._add(float(len(node)), artifact_id)
+ stack.extend(reversed(node.values()))
+ elif isinstance(node, (list, tuple)):
+ self._add(float(len(node)), artifact_id)
+ stack.extend(reversed(node))
+
+ def _add_text(self, text: str, artifact_id: str | None) -> None:
+ if not any(ch.isdigit() for ch in text):
+ return
+ for match in _NUMBER.finditer(text):
+ reading = _read(text, match)
+ self._add(reading.value, artifact_id)
+ if self._expand and reading.unit == "%":
+ self._add(reading.value / 100, artifact_id)
+ elif self._expand and reading.unit in ("k", "M", "bn"):
+ self._add(reading.value * _SCALES[reading.unit][1][0], artifact_id)
+
+ def _add(self, value: float, artifact_id: str | None) -> None:
+ self._entries.append((value, len(self._entries), artifact_id))
+
+ def freeze(self) -> _Pool:
+ self._entries.sort()
+ self._values = [entry[0] for entry in self._entries]
+ return self
+
+ def find(self, value: float, tolerance: float) -> str | None | bool:
+ """The matching artifact id (``None`` when it has none), or ``False``."""
+ slack = tolerance + 1e-9 * max(1.0, abs(value))
+ i = bisect.bisect_left(self._values, value - slack)
+ if i < len(self._values) and self._values[i] <= value + slack:
+ return self._entries[i][2]
+ return False
+
+
+def _pool(sources: Iterable[tuple[str | None, Any]], budget: _Budget, expand: bool) -> _Pool:
+ pool = _Pool(budget, expand=expand)
+ for artifact_id, data in sources:
+ pool.add_all(artifact_id, data)
+ return pool.freeze()
+
+
+# ---------------------------------------------------------------------------
+# Answer side
+# ---------------------------------------------------------------------------
+
+
+def _masked(text: str) -> list[tuple[int, int]]:
+ return [m.span() for m in _MASKS.finditer(text)]
+
+
+def _inside(spans: list[tuple[int, int]], start: int, end: int) -> bool:
+ i = bisect.bisect_right(spans, (start, float("inf"))) - 1
+ return i >= 0 and spans[i][0] <= start and end <= spans[i][1]
+
+
+def _not_a_figure(text: str, start: int, reading: _Reading, previous_skipped_end: int) -> bool:
+ # A space stands in for the text's edges so every test below is a plain char test.
+ before = text[start - 1] if start else " "
+ before2 = text[start - 2] if start > 1 else " "
+ end = reading.text_end
+ after = text[end] if end < len(text) else " "
+ after2 = text[end + 1] if end + 1 < len(text) else " "
+
+ if _letter(before) or before in "_/\\#@":
+ return True
+ if before == "." and _word_char(before2):
+ return True
+ if before == ":" and not before2.isspace():
+ return True
+ if before in "-–" and _letter(before2):
+ return True
+ # The far end of a range whose near end was not a figure ("lines 10-20").
+ if before in "-–" and previous_skipped_end == start - 1:
+ return True
+ if reading.unit is None:
+ if _letter(after) or after in "_/\\":
+ return True
+ if after in ".:" and _word_char(after2):
+ return True
+ if (before, after) in (("[", "]"), ("(", ")")):
+ return True
+ if (
+ reading.unit is None
+ and reading.decimals == 0
+ and not reading.signed
+ and after in ".)"
+ and after2.isspace()
+ and _LIST_MARKER.fullmatch(text, text.rfind("\n", 0, start) + 1, start)
+ ):
+ return True
+ if reading.unit in (None, "s") and reading.decimals == 0 and 1900 <= reading.value <= 2099:
+ return True
+ word = _WORD_BEFORE.search(text, max(0, start - 24), start)
+ if word and word.group(1).lower() in _LABEL_WORDS | _MONTHS:
+ return True
+ if reading.unit is None and reading.decimals == 0 and 0 <= reading.value <= 31:
+ following = _WORD_AFTER.match(text, end)
+ if following and following.group(1).lower() in _MONTHS:
+ return True
+ return False
+
+
+def _tolerance(text: str, start: int, reading: _Reading) -> float:
+ """Half a unit of the last digit shown; a hedged figure ("about 1,200",
+ "24,000+") also gets 10% and its round zeros."""
+ tolerance = 0.5 * 10.0**-reading.decimals
+ if _HEDGES.search(text, max(0, start - 16), start) or text.startswith("+", reading.text_end):
+ magnitude = abs(reading.value)
+ if reading.decimals == 0:
+ digits = str(int(magnitude))
+ zeros = len(digits) - len(digits.rstrip("0")) if magnitude else 0
+ tolerance = max(tolerance, 0.5 * 10.0**zeros)
+ tolerance = max(tolerance, _HEDGE_RELATIVE * magnitude)
+ return tolerance
+
+
+def _find(pool: _Pool, reading: _Reading, tolerance: float) -> str | None | bool:
+ """Look *reading* up in each of its units; an unsigned figure also matches a negative value."""
+ for value in _values(reading):
+ scale = abs(value / reading.value) if reading.value else 1.0
+ for candidate in (value,) if reading.signed or not value else (value, -value):
+ found = pool.find(candidate, tolerance * scale)
+ if found is not False:
+ return found
+ return False
+
+
+def _utf16_offsets(text: str) -> list[int] | None:
+ """Code-point index -> UTF-16 offset, or None when every character is in the BMP."""
+ if all(ord(ch) < 0x10000 for ch in text):
+ return None
+ offsets, total = [], 0
+ for ch in text:
+ offsets.append(total)
+ total += 2 if ord(ch) >= 0x10000 else 1
+ offsets.append(total)
+ return offsets
+
+
+def check_figures(
+ answer: str,
+ sources: Iterable[tuple[str | None, Any]],
+ question: str = "",
+ earlier: Iterable[tuple[str | None, Any]] = (),
+) -> FigureCheck:
+ """Look up every figure in *answer* among the numbers of *sources*, then
+ the still-unmatched ones among *earlier*.
+
+ Each source is ``(artifact_id, data)``: a tool result or view of this turn
+ for *sources*, a tool result of an earlier turn for *earlier*. Pure and
+ CPU-bound; a caller on an event loop runs it in a thread.
+ """
+ check = FigureCheck()
+ if not answer or not any(ch.isdigit() for ch in answer):
+ return check
+ asked = {abs(_read(question, m).value) for m in _NUMBER.finditer(question)}
+ masks = _masked(answer)
+
+ candidates: list[tuple[int, _Reading]] = []
+ skipped_end = -1
+ for match in _NUMBER.finditer(answer):
+ start = match.start()
+ reading = _read(answer, match)
+ if _inside(masks, start, match.end()) or _not_a_figure(
+ answer, start, reading, skipped_end
+ ):
+ skipped_end = match.end()
+ continue
+ if abs(reading.value) not in asked:
+ candidates.append((start, reading))
+ if not candidates:
+ return check
+
+ budget = _Budget()
+ expand = any(reading.unit is None for _, reading in candidates)
+ pools = [_pool(sources, budget, expand)]
+ earlier_sources = list(earlier)
+ utf16 = _utf16_offsets(answer)
+ for start, reading in candidates:
+ tolerance = _tolerance(answer, start, reading)
+ found = _find(pools[0], reading, tolerance)
+ if found is False and earlier_sources:
+ if len(pools) == 1:
+ pools.append(_pool(earlier_sources, budget, expand))
+ found = _find(pools[1], reading, tolerance)
+ if found is False and any(pool.truncated for pool in pools):
+ check.not_checked += 1
+ continue
+ end = reading.text_end
+ check.figures.append(
+ Figure(
+ text=answer[start:end],
+ start=utf16[start] if utf16 else start,
+ end=utf16[end] if utf16 else end,
+ verified=found is not False,
+ artifact_id=found if isinstance(found, str) else None,
+ )
+ )
+ return check
diff --git a/packages/server/src/repowise/server/chat_session.py b/packages/server/src/repowise/server/chat_session.py
index a9ffc786d..b5a6fde87 100644
--- a/packages/server/src/repowise/server/chat_session.py
+++ b/packages/server/src/repowise/server/chat_session.py
@@ -25,6 +25,8 @@ from collections.abc import AsyncIterator, Awaitable, Callable
from dataclasses import asdict, dataclass, field
from typing import Any, Literal
+from pydantic import ValidationError
+
from repowise.core.providers.llm.base import ChatProvider, ProviderError
from repowise.server.auth import Principal
from repowise.server.chat_artifacts import create_artifact_envelope
@@ -34,6 +36,7 @@ from repowise.server.chat_context import (
compose_request,
is_context_overflow,
)
+from repowise.server.chat_figures import check_figures
from repowise.server.chat_grounding import plan_grounding, run_grounding
from repowise.server.chat_prompt import (
_build_system_prompt,
@@ -62,6 +65,7 @@ from repowise.server.chat_suggestions import conversation_title, follow_up_sugge
from repowise.server.chat_summaries import _build_tool_summary
from repowise.server.chat_tools import ChatToolContract, LocalToolBackend, tool_schemas
from repowise.server.chat_views import SHOW_VIEW_TOOL, TurnViews, show_view_schema
+from repowise.server.schemas.evidence import CardRef
logger = logging.getLogger(__name__)
@@ -121,6 +125,10 @@ class ChatTurnResult:
citations: list[dict[str, Any]] = field(default_factory=list)
cards: list[dict[str, Any]] = field(default_factory=list)
views: list[dict[str, Any]] = field(default_factory=list)
+ #: Each number the answer states, looked up in the turn's tool results;
+ #: a verified one carries the ``artifact_id`` it came from.
+ figures: list[dict[str, Any]] = field(default_factory=list)
+ diagnostics: dict[str, int] = field(default_factory=dict)
tool_trace: list[ToolTraceEntry] = field(default_factory=list)
follow_ups: list[dict[str, Any]] = field(default_factory=list)
usage: TurnUsage = field(default_factory=TurnUsage)
@@ -157,11 +165,13 @@ async def _never_cancelled() -> bool:
def _citations(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
- """Files the turn's tool results cite, first mention first."""
+ """Files the turn's tool results cite, first mention first, each with the
+ ``artifact_id`` of the result that cited it and its entity ``ref``."""
seen: set[tuple[Any, ...]] = set()
out: list[dict[str, Any]] = []
for call in tool_calls:
- data = (call.get("artifact") or {}).get("data") or {}
+ artifact = call.get("artifact") or {}
+ data = artifact.get("data") or {}
raw = data.get("citations") if isinstance(data, dict) else None
for item in raw if isinstance(raw, list) else []:
if isinstance(item, str):
@@ -175,12 +185,35 @@ def _citations(tool_calls: list[dict[str, Any]]) -> list[dict[str, Any]]:
else:
continue
key = tuple(sorted(citation.items()))
- if key not in seen:
- seen.add(key)
- out.append(citation)
+ if key in seen:
+ continue
+ seen.add(key)
+ if isinstance(artifact.get("id"), str):
+ citation["artifact_id"] = artifact["id"]
+ ref = _citation_ref(citation)
+ if ref is not None:
+ citation["ref"] = ref
+ out.append(citation)
return out
+def _citation_ref(citation: dict[str, Any]) -> dict[str, Any] | None:
+ """The file or symbol a citation names, as a ``CardRef``; None when it does not validate."""
+ symbol = citation.get("symbol_name")
+ ref: dict[str, Any] = (
+ {"type": "symbol", "id": f"{citation['file_path']}::{symbol}"}
+ if isinstance(symbol, str) and symbol
+ else {"type": "file", "id": citation["file_path"]}
+ )
+ for key in ("start_line", "end_line"):
+ if key in citation:
+ ref[key] = citation[key]
+ try:
+ return CardRef.model_validate(ref).model_dump(exclude_none=True)
+ except ValidationError:
+ return None
+
+
def _tool_trace(tool_calls: list[dict[str, Any]]) -> list[ToolTraceEntry]:
trace = []
for call in tool_calls:
@@ -220,6 +253,8 @@ def _result_from_content(
citations=_citations(tool_calls),
cards=list(content.get("cards") or []),
views=list(content.get("views") or []),
+ figures=list(content.get("figures") or []),
+ diagnostics=dict(content.get("diagnostics") or {}),
tool_trace=_tool_trace(tool_calls),
follow_ups=list(content.get("follow_ups") or []),
usage=TurnUsage(**usage) if isinstance(usage, dict) else TurnUsage(),
@@ -227,8 +262,26 @@ def _result_from_content(
)
-def _closing_events(result: ChatTurnResult) -> list[dict[str, Any]]:
+def _closing_events(result: ChatTurnResult, text_shift: int = 0) -> list[dict[str, Any]]:
+ """``text_shift`` moves figure offsets from the answer onto the streamed
+ text, which also holds what the model wrote before its tool calls."""
events: list[dict[str, Any]] = []
+ if result.diagnostics:
+ events.append(
+ {
+ "type": "diagnostics",
+ **result.diagnostics,
+ "unverified_figures": [
+ {
+ "text": f["text"],
+ "start": f["start"] + text_shift,
+ "end": f["end"] + text_shift,
+ }
+ for f in result.figures
+ if not f.get("verified")
+ ],
+ }
+ )
if result.follow_ups:
events.append({"type": "suggestions", "suggestions": result.follow_ups})
done: dict[str, Any] = {
@@ -269,6 +322,8 @@ class _Turn:
tokens_before: int,
is_cancelled: IsCancelled,
shows_views: bool = False,
+ question: str = "",
+ prior_calls: list[dict[str, Any]] | None = None,
) -> None:
self.provider = provider
self.tools = tools
@@ -281,6 +336,11 @@ class _Turn:
self.tokens_before = tokens_before
self.is_cancelled = is_cancelled
self.text_parts: list[str] = []
+ #: Text streamed this turn in UTF-16 units, the offsets a browser uses.
+ self.streamed_units = 0
+ self.question = question
+ #: Earlier turns' tool calls: a figure restated from them is still a tool's.
+ self.prior_calls = prior_calls or []
self.provider_content: list[dict[str, Any]] | None = None
self.tool_calls: list[dict[str, Any]] = []
self.stop_reason: StopReason = "answered"
@@ -419,6 +479,7 @@ class _Turn:
def _on_provider_event(self, event: Any, pending: list[dict[str, Any]]) -> list[dict]:
if event.type == "text_delta" and event.text:
self.text_parts.append(event.text)
+ self.streamed_units += len(event.text.encode("utf-16-le")) // 2
return [{"type": "text_delta", "text": event.text}]
if event.type == "usage":
self.input_tokens = (self.input_tokens or 0) + event.input_tokens
@@ -513,6 +574,39 @@ class _Turn:
content["views"] = self.views.parts
return content
+ async def check_figures(self, content: dict[str, Any]) -> None:
+ """Add the numeric check to *content*; CPU-bound, so off the event loop."""
+ check = await asyncio.to_thread(
+ check_figures,
+ content["text"],
+ [
+ *_artifact_sources(self.tool_calls),
+ *((part["source"]["artifact_id"], part) for part in self.views.parts),
+ ],
+ self.question,
+ _artifact_sources(self.prior_calls),
+ )
+ if check.figures:
+ content["figures"] = [figure.to_json() for figure in check.figures]
+ if diagnostics := check.diagnostics():
+ content["diagnostics"] = diagnostics
+
+ @property
+ def answer_shift(self) -> int:
+ """UTF-16 units streamed before the final answer's text."""
+ answer = "".join(self.text_parts)
+ return self.streamed_units - len(answer.encode("utf-16-le")) // 2
+
+
+def _artifact_sources(tool_calls: list[dict[str, Any]]) -> list[tuple[str | None, Any]]:
+ """``(artifact_id, data)`` of each stored tool call that has a result."""
+ sources: list[tuple[str | None, Any]] = []
+ for call in tool_calls:
+ artifact = call.get("artifact") or {}
+ if isinstance(artifact, dict) and "data" in artifact:
+ sources.append((artifact.get("id"), artifact["data"]))
+ return sources
+
def _stored_tool_call(
tool_id: str,
@@ -799,6 +893,14 @@ class ChatSession:
tokens_before=conversation.tokens_used,
is_cancelled=is_cancelled,
shows_views=shows_views,
+ question=message,
+ prior_calls=[
+ call
+ for stored in history
+ if stored.id != user_message_id
+ for call in stored.content.get("tool_calls") or []
+ if isinstance(call, dict)
+ ],
)
grounded = await turn.ground(context)
if grounded is not None:
@@ -820,6 +922,7 @@ class ChatSession:
return
content = turn.reply_content()
+ await turn.check_figures(content)
title = conversation_title(message, tool_names(turn.tool_calls)) if opening else None
message_id = await self.store.add_reply(
self.id, content, title=title, usage=turn.usage
@@ -832,7 +935,7 @@ class ChatSession:
user_message_id=user_message_id,
stop_reason=turn.stop_reason,
)
- for event in _closing_events(outcome.result):
+ for event in _closing_events(outcome.result, turn.answer_shift):
yield event
diff --git a/packages/server/src/repowise/server/schemas/chat.py b/packages/server/src/repowise/server/schemas/chat.py
index 300da7e1b..a561c7a69 100644
--- a/packages/server/src/repowise/server/schemas/chat.py
+++ b/packages/server/src/repowise/server/schemas/chat.py
@@ -9,6 +9,7 @@ from typing import Any, Literal
from pydantic import BaseModel, Field
from repowise.server.chat_artifacts import normalize_message_artifacts
+from repowise.server.schemas.evidence import CardRef
class ChatPageContext(BaseModel):
@@ -240,6 +241,28 @@ class ChatTurnUsage(BaseModel):
model_calls: int = 0
+class ChatCitation(BaseModel):
+ """A file a tool result cited, and that result's ``artifact_id``."""
+
+ file_path: str
+ symbol_name: str | None = None
+ start_line: int | None = None
+ end_line: int | None = None
+ artifact_id: str | None = None
+ ref: CardRef | None = None
+
+
+class ChatFigure(BaseModel):
+ """A number the answer states. Offsets are UTF-16 units into ``answer``;
+ a verified figure carries the ``artifact_id`` of the result holding it."""
+
+ text: str
+ start: int
+ end: int
+ verified: bool
+ artifact_id: str | None = None
+
+
class ChatTurnResultResponse(BaseModel):
conversation_id: str
message_id: str | None = None
@@ -250,9 +273,13 @@ class ChatTurnResultResponse(BaseModel):
]
provider: str
model: str
- citations: list[dict[str, Any]] = []
+ citations: list[ChatCitation] = []
cards: list[dict[str, Any]] = []
views: list[dict[str, Any]] = []
+ figures: list[ChatFigure] = []
+ #: ``figures_checked``, ``figures_unverified`` and, past the evidence read
+ #: cap, ``figures_not_checked``; empty when the answer states no figure.
+ diagnostics: dict[str, int] = {}
tool_trace: list[ChatToolTraceEntry] = []
follow_ups: list[ChatSuggestion] = []
usage: ChatTurnUsage = ChatTurnUsage()
diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.ts
index da5fb72e6..3fb500551 100644
--- a/packages/types/src/chat.ts
+++ b/packages/types/src/chat.ts
@@ -11,11 +11,13 @@ import type { GraphExport } from "./graph.js";
import type { Hotspot } from "./git.js";
import type { DeadCodeFinding } from "./dead-code.js";
import type { DecisionRecord } from "./decisions.js";
-import type { EvidenceCard } from "./cards.js";
+import type { CardRef, EvidenceCard } from "./cards.js";
import type { ViewPart } from "./views.js";
+import type { ChatFigure } from "./generated/http.js";
/** Headless chat session wire types, generated from the server schema. */
export type {
+ ChatFigure,
ChatSessionMessageRequest,
ChatSessionOpenRequest,
ChatSessionPolicyRequest,
@@ -141,6 +143,14 @@ export interface ChatMessage {
cards?: unknown[];
/** View parts `show_view` built this turn, unvalidated until parsed. */
views?: unknown[];
+ /** Each number the answer states, looked up in the turn's tool results. */
+ figures?: ChatFigure[];
+ diagnostics?: {
+ figures_checked?: number;
+ figures_unverified?: number;
+ /** Figures left unchecked because the evidence was past the read cap. */
+ figures_not_checked?: number;
+ };
};
created_at: string;
}
@@ -178,6 +188,15 @@ export interface ChatUIMessage {
cards?: EvidenceCard[];
/** Validated view parts for this turn, in the order they were built. */
views?: ViewPart[];
+ /** Figures in `text` no tool result of the turn holds; flagged, not removed. */
+ unverifiedFigures?: ChatFigureSpan[];
+}
+
+/** A figure's place in the text a message shows, in UTF-16 offsets. */
+export interface ChatFigureSpan {
+ text: string;
+ start: number;
+ end: number;
}
// ---------------------------------------------------------------------------
@@ -193,6 +212,10 @@ export interface ChatCitation {
symbol_name?: string;
start_line?: number;
end_line?: number;
+ /** The tool result that cited this file. */
+ artifact_id?: string;
+ /** The file or symbol as an entity ref, resolved like a card's. */
+ ref?: CardRef;
}
export interface ArtifactEvidence {
@@ -714,6 +737,15 @@ export type ChatSSEEvent =
/** A limit stopped the turn before a final answer; `done` still follows.
* `reason` is `loop_cap` (every call ended in a tool call) or `token_budget`. */
| { type: "truncated"; loops: number; reason?: "loop_cap" | "token_budget" }
+ /** The post-turn numeric check, sent before `suggestions` when the answer
+ * states a figure. Spans are offsets into the streamed text. */
+ | {
+ type: "diagnostics";
+ figures_checked: number;
+ figures_unverified: number;
+ figures_not_checked?: number;
+ unverified_figures: ChatFigureSpan[];
+ }
/** Next steps for the turn that just finished, sent just before `done`.
* A turn that failed or called no tool sends none. */
| { type: "suggestions"; suggestions: ChatSuggestion[] }
diff --git a/packages/types/src/generated/http.ts b/packages/types/src/generated/http.ts
index 65824ff42..f277ece58 100644
--- a/packages/types/src/generated/http.ts
+++ b/packages/types/src/generated/http.ts
@@ -367,6 +367,14 @@ export interface CallersCalleesResponse {
relations?: SymbolRelationGroup[];
}
+/** An entity a card or view points at. Never a URL; the renderer resolves it. */
+export interface CardRef {
+ type: "repo" | "file" | "symbol" | "module" | "component" | "commit" | "change" | "decision";
+ id: string;
+ start_line?: number | null;
+ end_line?: number | null;
+}
+
export interface ChangeAuthor {
name: string;
email: string;
@@ -497,6 +505,28 @@ export interface ChatArtifactEnvelope {
created_at?: string | null;
}
+/** A file a tool result cited, and that result's ``artifact_id``. */
+export interface ChatCitation {
+ file_path: string;
+ symbol_name?: string | null;
+ start_line?: number | null;
+ end_line?: number | null;
+ artifact_id?: string | null;
+ ref?: CardRef | null;
+}
+
+/**
+ * A number the answer states. Offsets are UTF-16 units into ``answer``;
+ * a verified figure carries the ``artifact_id`` of the result holding it.
+ */
+export interface ChatFigure {
+ text: string;
+ start: number;
+ end: number;
+ verified: boolean;
+ artifact_id?: string | null;
+}
+
export interface ChatMessageResponse {
id: string;
conversation_id: string;
@@ -602,9 +632,11 @@ export interface ChatTurnResultResponse {
stop_reason: "answered" | "loop_cap" | "token_budget" | "turn_budget" | "refused" | "cancelled" | "error";
provider: string;
model: string;
- citations?: Record<string, unknown>[];
+ citations?: ChatCitation[];
cards?: Record<string, unknown>[];
views?: Record<string, unknown>[];
+ figures?: ChatFigure[];
+ diagnostics?: Record<string, number>;
tool_trace?: ChatToolTraceEntry[];
follow_ups?: ChatSuggestion[];
usage?: ChatTurnUsage;
diff --git a/packages/ui/__tests__/chat/chat-message.test.tsx b/packages/ui/__tests__/chat/chat-message.test.tsx
index 5b96081c8..b119f420b 100644
--- a/packages/ui/__tests__/chat/chat-message.test.tsx
+++ b/packages/ui/__tests__/chat/chat-message.test.tsx
@@ -171,4 +171,63 @@ describe("ChatMessage truncation", () => {
);
expect(container.querySelector('[data-working-orb="true"]')).not.toBeNull();
});
+
+ it("marks an unverified figure with a dotted underline and screen-reader text", () => {
+ const { container } = render(
+ <ChatMessage
+ message={{
+ ...ASSISTANT,
+ text: "It has **3 fixes** and 17 callers.",
+ unverifiedFigures: [{ text: "17", start: 23, end: 25 }],
+ }}
+ repoId="r1"
+ />,
+ );
+ const flagged = container.querySelector("[data-flagged]");
+ expect(flagged?.textContent).toBe("17 (Not found in this turn's tool results)");
+ expect(flagged?.className).toContain("decoration-dotted");
+ expect(flagged).toHaveAttribute("title", "Not found in this turn's tool results");
+ expect(container.querySelectorAll("[data-flagged]")).toHaveLength(1);
+ expect(container.querySelector("[data-chat-unverified-figures]")).not.toBeNull();
+ });
+
+ it.each([
+ ["inside emphasis", "Fixed **17** times.", 8],
+ ["inside a link", "See [17 callers](https://example.com).", 5],
+ ])("marks a figure %s", (_label, text, start) => {
+ const { container } = render(
+ <ChatMessage
+ message={{ ...ASSISTANT, text, unverifiedFigures: [{ text: "17", start, end: start + 2 }] }}
+ repoId="r1"
+ />,
+ );
+ expect(container.querySelector("[data-flagged]")?.firstChild?.textContent).toBe("17");
+ });
+
+ it("leaves text it cannot map by offset unmarked", () => {
+ // The escape makes the text node shorter than its source, so offsets no longer line up.
+ const { container } = render(
+ <ChatMessage
+ message={{ ...ASSISTANT, text: String.raw`3 \* 17 callers`, unverifiedFigures: [{ text: "17", start: 5, end: 7 }] }}
+ repoId="r1"
+ />,
+ );
+ expect(container.querySelector("[data-flagged]")).toBeNull();
+ expect(container.textContent).toContain("3 * 17 callers");
+ });
+
+ it("holds the flags back while the answer streams", () => {
+ const { container } = render(
+ <ChatMessage
+ message={{
+ ...ASSISTANT,
+ text: "17 callers",
+ isStreaming: true,
+ unverifiedFigures: [{ text: "17", start: 0, end: 2 }],
+ }}
+ repoId="r1"
+ />,
+ );
+ expect(container.querySelector("[data-flagged]")).toBeNull();
+ });
});
diff --git a/packages/ui/src/chat/chat-dock.tsx b/packages/ui/src/chat/chat-dock.tsx
index 1d2b835ca..767ae01ac 100644
--- a/packages/ui/src/chat/chat-dock.tsx
+++ b/packages/ui/src/chat/chat-dock.tsx
@@ -31,6 +31,7 @@ import { ChatComposer } from "./chat-composer";
import { ChatContextIndicator } from "./chat-context-indicator";
import { getChatContextPresentation, type ChatContext } from "./chat-context";
import { ChatInterface } from "./chat-interface";
+import type { UnverifiedFigureCopy } from "./chat-message";
import { buildHandoffDraft } from "./chat-handoff";
import { ChatSuggestions } from "./chat-suggestions";
import { CHAT_SHORTCUT_HINT } from "./use-chat-shortcut";
@@ -176,6 +177,7 @@ export interface ChatDockProps {
assistantAvatarSrc?: string;
buildCitationHref?: (source: SourceReference) => string;
linkPrefix?: string;
+ unverifiedFigureCopy?: UnverifiedFigureCopy;
onOpenFullChat?: () => void;
owlDarkSrc?: string;
owlLightSrc?: string;
@@ -215,6 +217,7 @@ export function ChatDock({
assistantAvatarSrc,
buildCitationHref,
linkPrefix,
+ unverifiedFigureCopy,
onOpenFullChat,
owlDarkSrc = "/repowise-logo.png",
owlLightSrc = "/repowise-logo-light.png",
@@ -619,6 +622,7 @@ export function ChatDock({
{...(assistantAvatarSrc ? { assistantAvatarSrc } : {})}
{...(buildCitationHref ? { buildCitationHref } : {})}
{...(linkPrefix ? { linkPrefix } : {})}
+ {...(unverifiedFigureCopy ? { unverifiedFigureCopy } : {})}
{...(onArtifactPin ? { onArtifactPin } : {})}
{...(onOpenArtifactSource ? { onOpenArtifactSource } : {})}
{...(artifactOverrides ? { artifactOverrides } : {})}
diff --git a/packages/ui/src/chat/chat-interface.tsx b/packages/ui/src/chat/chat-interface.tsx
index 2756bb310..fb51144f0 100644
--- a/packages/ui/src/chat/chat-interface.tsx
+++ b/packages/ui/src/chat/chat-interface.tsx
@@ -32,7 +32,7 @@ import { Button } from "../ui/button";
import { ActivityDot } from "../ui/activity-dot";
import { ScrollArea } from "../ui/scroll-area";
import { cn } from "../lib/cn";
-import { ChatMessage } from "./chat-message";
+import { ChatMessage, type UnverifiedFigureCopy } from "./chat-message";
import { ArtifactPanel } from "./artifact-panel";
import { ChatContextIndicator } from "./chat-context-indicator";
import {
@@ -125,6 +125,8 @@ export interface ChatInterfaceProps {
onDraftChange?: (draft: string) => void;
onContextRemove?: () => void;
composerRef?: RefObject<HTMLTextAreaElement | null>;
+ /** Copy for figures the numeric check flagged; English by default. */
+ unverifiedFigureCopy?: UnverifiedFigureCopy;
/** Focus the composer on mount. The dock and the full page both do; a host
* embedding chat below other content should not. */
autoFocus?: boolean;
@@ -154,6 +156,7 @@ export function ChatInterface({
historySlot,
buildCitationHref,
linkPrefix,
+ unverifiedFigureCopy,
suggestions,
placeholder,
statusSlot,
@@ -422,6 +425,7 @@ export function ChatInterface({
{...(onEditAndResend ? { onEditAndResend } : {})}
{...(buildCitationHref ? { buildCitationHref } : {})}
{...(linkPrefix ? { linkPrefix } : {})}
+ {...(unverifiedFigureCopy ? { unverifiedFigureCopy } : {})}
/>
);
})}
diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsx
index 289c85bbf..afe3b4f2d 100644
--- a/packages/ui/src/chat/chat-message.tsx
+++ b/packages/ui/src/chat/chat-message.tsx
@@ -12,6 +12,19 @@ import { EvidenceCardList, cardRefHref } from "../cards/evidence-card";
import { ViewPartList } from "./view-part";
import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";
+/** Copy for figures the numeric check could not find in the turn's tool results. */
+export interface UnverifiedFigureCopy {
+ /** Tooltip and screen-reader text on each flagged figure. */
+ flag: string;
+ /** One line under an answer that has flagged figures. */
+ note: string;
+}
+
+export const DEFAULT_UNVERIFIED_FIGURE_COPY: UnverifiedFigureCopy = {
+ flag: "Not found in this turn's tool results",
+ note: "Figures with a dotted underline were not found in this turn's tool results.",
+};
+
interface ChatMessageProps {
message: ChatUIMessage;
repoId: string;
@@ -29,6 +42,7 @@ interface ChatMessageProps {
error?: string | null;
onRetry?: (message: ChatUIMessage) => void | Promise<void>;
onEditAndResend?: (message: ChatUIMessage, text: string) => void | Promise<void>;
+ unverifiedFigureCopy?: UnverifiedFigureCopy;
}
/**
@@ -50,10 +64,14 @@ function ChatMessageImpl({
error,
onRetry,
onEditAndResend,
+ unverifiedFigureCopy = DEFAULT_UNVERIFIED_FIGURE_COPY,
}: ChatMessageProps) {
const isUser = message.role === "user";
const dock = density === "dock";
const stage = isUser ? null : chatStage(message);
+ const flagged = !message.isStreaming && message.unverifiedFigures?.length
+ ? message.unverifiedFigures
+ : undefined;
if (isUser) {
return (
@@ -105,7 +123,19 @@ function ChatMessageImpl({
)}
{message.text && (
- <Markdown content={message.text} density={dock ? "narrow" : "reading"} streaming={message.isStreaming} fill />
+ <Markdown
+ content={message.text}
+ density={dock ? "narrow" : "reading"}
+ streaming={message.isStreaming}
+ fill
+ {...(flagged ? { flags: flagged, flagLabel: unverifiedFigureCopy.flag } : {})}
+ />
+ )}
+
+ {flagged && (
+ <p data-chat-unverified-figures={flagged.length} className="text-xs text-[var(--color-text-tertiary)]">
+ {unverifiedFigureCopy.note}
+ </p>
)}
{/* Views arrive live, each right after the call that built it. */}
diff --git a/packages/ui/src/shared/markdown.tsx b/packages/ui/src/shared/markdown.tsx
index 4e21f78f8..abe15424b 100644
--- a/packages/ui/src/shared/markdown.tsx
+++ b/packages/ui/src/shared/markdown.tsx
@@ -258,6 +258,65 @@ function buildComponents(s: Scale, measure: string): Components {
};
}
+/** A span of `content` (UTF-16 offsets) to mark, e.g. a figure no tool returned. */
+export interface MarkdownFlag {
+ start: number;
+ end: number;
+}
+
+interface MdNode {
+ type: string;
+ value?: string;
+ children?: MdNode[];
+ position?: { start: { offset?: number }; end: { offset?: number } };
+ data?: object;
+}
+
+const FLAG_CLASS =
+ "cursor-help underline decoration-dotted decoration-[var(--color-text-tertiary)] underline-offset-4";
+
+/** Splits text nodes at each flag. A text node whose value differs from its
+ * source (escapes, entities) cannot be mapped by offset and stays unmarked. */
+function flagSpans(node: MdNode, flags: readonly MarkdownFlag[], label: string): void {
+ if (!node.children) return;
+ node.children = node.children.flatMap((child): MdNode[] => {
+ const from = child.position?.start.offset;
+ const to = child.position?.end.offset;
+ if (child.type !== "text" || child.value === undefined || from === undefined || to === undefined) {
+ flagSpans(child, flags, label);
+ return [child];
+ }
+ const value = child.value;
+ if (value.length !== to - from) return [child];
+ const inside = flags
+ .filter((f) => f.start >= from && f.end <= to && f.end > f.start)
+ .sort((a, b) => a.start - b.start);
+ if (!inside.length) return [child];
+ const out: MdNode[] = [];
+ let at = 0;
+ for (const flag of inside) {
+ const start = flag.start - from;
+ if (start < at) continue;
+ if (start > at) out.push({ type: "text", value: value.slice(at, start) });
+ out.push({
+ type: "flag",
+ data: { hName: "span", hProperties: { className: FLAG_CLASS, title: label, "data-flagged": "" } },
+ children: [
+ { type: "text", value: value.slice(start, flag.end - from) },
+ {
+ type: "flagLabel",
+ data: { hName: "span", hProperties: { className: "sr-only" } },
+ children: [{ type: "text", value: ` (${label})` }],
+ },
+ ],
+ });
+ at = flag.end - from;
+ }
+ if (at < value.length) out.push({ type: "text", value: value.slice(at) });
+ return out;
+ });
+}
+
export interface MarkdownProps {
content: string;
/** `narrow` for the chat dock, `compact` for chrome-sized side panels. */
@@ -267,19 +326,37 @@ export interface MarkdownProps {
/** Fill the host column instead of capping prose at 72ch. For hosts that
* already set a reading width, such as the chat column. */
fill?: boolean;
+ /** Spans to mark with a dotted underline; `flagLabel` is their tooltip and
+ * screen-reader text, so the mark never rests on color alone. */
+ flags?: readonly MarkdownFlag[];
+ flagLabel?: string;
}
const REMARK_PLUGINS = [remarkGfm];
-export function Markdown({ content, density = "reading", streaming = false, fill = false }: MarkdownProps) {
+export function Markdown({
+ content,
+ density = "reading",
+ streaming = false,
+ fill = false,
+ flags,
+ flagLabel = "Flagged",
+}: MarkdownProps) {
const measure = density === "reading" && !fill ? "max-w-[72ch]" : "max-w-full";
const components = useMemo(
() => buildComponents(SCALES[density], measure),
[density, measure],
);
+ const remarkPlugins = useMemo(
+ () =>
+ flags?.length
+ ? [...REMARK_PLUGINS, () => (tree: MdNode) => flagSpans(tree, flags, flagLabel)]
+ : REMARK_PLUGINS,
+ [flags, flagLabel],
+ );
return (
<StreamingContext.Provider value={streaming}>
- <ReactMarkdown remarkPlugins={REMARK_PLUGINS} components={components}>
+ <ReactMarkdown remarkPlugins={remarkPlugins} components={components}>
{content}
</ReactMarkdown>
</StreamingContext.Provider>
diff --git a/packages/web/messages/en.json b/packages/web/messages/en.json
index 708fe288b..c790a9a9d 100644
--- a/packages/web/messages/en.json
+++ b/packages/web/messages/en.json
@@ -759,7 +759,9 @@
},
"chat": {
"noProvider": "No chat provider is configured. Add an API key in <link>settings</link> to start asking questions.",
- "noProviderShort": "No chat provider is configured. Add an API key in <link>settings</link>."
+ "noProviderShort": "No chat provider is configured. Add an API key in <link>settings</link>.",
+ "unverifiedFigure": "Not found in this turn's tool results",
+ "unverifiedFiguresNote": "Figures with a dotted underline were not found in this turn's tool results."
},
"codeHealth": {
"hotspots": {
diff --git a/packages/web/messages/zh-CN.json b/packages/web/messages/zh-CN.json
index 4d1ca7b0a..49635e10c 100644
--- a/packages/web/messages/zh-CN.json
+++ b/packages/web/messages/zh-CN.json
@@ -759,7 +759,9 @@
},
"chat": {
"noProvider": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥,然后就可以开始提问了。",
- "noProviderShort": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥。"
+ "noProviderShort": "尚未配置对话提供商。请先在<link>设置</link>中添加 API 密钥。",
+ "unverifiedFigure": "未在本轮工具结果中找到",
+ "unverifiedFiguresNote": "带点状下划线的数字未在本轮工具结果中找到。"
},
"codeHealth": {
"hotspots": {
diff --git a/packages/web/src/components/chat/chat-interface.tsx b/packages/web/src/components/chat/chat-interface.tsx
index b2e023b92..2be1d9e0f 100644
--- a/packages/web/src/components/chat/chat-interface.tsx
+++ b/packages/web/src/components/chat/chat-interface.tsx
@@ -197,6 +197,7 @@ export function ChatInterface({
onArtifactPin={pinArtifact}
onOpenArtifactSource={openArtifactSource}
artifactOverrides={artifactOverrides}
+ unverifiedFigureCopy={{ flag: t("unverifiedFigure"), note: t("unverifiedFiguresNote") }}
sendDisabled={!anyConfigured}
sendDisabledReason={
<span>
diff --git a/packages/web/src/components/chat/repository-chat-dock.tsx b/packages/web/src/components/chat/repository-chat-dock.tsx
index 52bd3a1cb..5014d11f6 100644
--- a/packages/web/src/components/chat/repository-chat-dock.tsx
+++ b/packages/web/src/components/chat/repository-chat-dock.tsx
@@ -120,6 +120,7 @@ function ConnectedRepositoryChatDock({ chat }: { chat: RepositoryChatValue }) {
)}
{...(collisionInset ? { collisionInset } : {})}
onDismiss={() => setChatDockHidden(true)}
+ unverifiedFigureCopy={{ flag: t("unverifiedFigure"), note: t("unverifiedFiguresNote") }}
sendDisabled={!anyConfigured}
sendDisabledReason={
<span>
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.ts
index a335f3b0d..93759f597 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
@@ -64,6 +64,29 @@ describe("toChatUiMessages", () => {
expect(toChatUiMessages(stored)[0]?.toolCalls[0]?.status).toBe(expected);
});
+ it("reloads only the unverified figures as flags", () => {
+ const stored: ChatMessageResponse[] = [
+ {
+ id: "m1",
+ conversation_id: "c1",
+ role: "assistant",
+ content: {
+ text: "3 fixes and 17 callers.",
+ figures: [
+ { text: "3", start: 0, end: 1, verified: true, artifact_id: "a".repeat(32) },
+ { text: "17", start: 12, end: 14, verified: false },
+ ],
+ diagnostics: { figures_checked: 2, figures_unverified: 1 },
+ },
+ created_at: "2026-10-14T00:00:00Z",
+ },
+ ];
+
+ expect(toChatUiMessages(stored)[0]?.unverifiedFigures).toEqual([
+ { text: "17", start: 12, end: 14 },
+ ]);
+ });
+
it("restores the persisted artifact envelope without rebuilding it", () => {
const stored: ChatMessageResponse[] = [
{
diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.ts
index 026386ee2..476c0fee8 100644
--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts
+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts
@@ -16,6 +16,16 @@ function storedViews(message: ChatMessageResponse): Pick<ChatUIMessage, "views">
return views.length ? { views } : {};
}
+/** Figures the numeric check found in no tool result; offsets index `content.text`. */
+function storedUnverifiedFigures(
+ message: ChatMessageResponse,
+): Pick<ChatUIMessage, "unverifiedFigures"> {
+ const spans = (message.content.figures ?? [])
+ .filter((figure) => !figure.verified)
+ .map(({ text, start, end }) => ({ text, start, end }));
+ return spans.length ? { unverifiedFigures: spans } : {};
+}
+
/** Normalize stored API messages into the same shape produced while streaming. */
export function toChatUiMessages(
messages: ChatMessageResponse[],
@@ -76,5 +86,6 @@ export function toChatUiMessages(
: {}),
...storedCards(message),
...storedViews(message),
+ ...storedUnverifiedFigures(message),
}));
}
diff --git a/packages/web/src/lib/hooks/use-chat.test.tsx b/packages/web/src/lib/hooks/use-chat.test.tsx
index e3f10ecea..db76246d7 100644
--- a/packages/web/src/lib/hooks/use-chat.test.tsx
+++ b/packages/web/src/lib/hooks/use-chat.test.tsx
@@ -395,6 +395,29 @@ describe("useChat grounding and truncation events", () => {
expect(result.current.error).toBeNull();
});
+ it("marks the figures the numeric check could not find", async () => {
+ const spans = [{ text: "17", start: 9, end: 11 }];
+ const push = streamed([
+ { type: "text_delta", text: "a.py has 17 callers." },
+ {
+ type: "diagnostics",
+ figures_checked: 1,
+ figures_unverified: 1,
+ unverified_figures: spans,
+ },
+ { type: "done", conversation_id: "c1", message_id: "m1" },
+ ]);
+ const { result } = renderHook(() => useChat("r1"));
+
+ await act(async () => {
+ const sending = result.current.sendMessage("callers?");
+ await push();
+ await sending;
+ });
+
+ expect(result.current.messages.at(-1)?.unverifiedFigures).toEqual(spans);
+ });
+
it("shows a show_view call as a step and puts its view on the answer", async () => {
const view = fixture.valid.c1;
const receipt = { view_id: "c1", kind: "chart", title: view.title };
diff --git a/packages/web/src/lib/hooks/use-chat.ts b/packages/web/src/lib/hooks/use-chat.ts
index 9383a4856..a2e8cc823 100644
--- a/packages/web/src/lib/hooks/use-chat.ts
+++ b/packages/web/src/lib/hooks/use-chat.ts
@@ -292,6 +292,11 @@ export function useChat(repoId: string) {
case "truncated":
return { ...m, truncated: true };
+ case "diagnostics":
+ return ev.unverified_figures.length
+ ? { ...m, unverifiedFigures: ev.unverified_figures }
+ : m;
+
case "suggestions":
return { ...m, followUps: ev.suggestions };
diff --git a/tests/unit/server/test_chat_figures.py b/tests/unit/server/test_chat_figures.py
new file mode 100644
index 000000000..d482c7599
--- /dev/null
+++ b/tests/unit/server/test_chat_figures.py
@@ -0,0 +1,153 @@
+"""The post-turn numeric check: what counts as a figure and what matches one."""
+
+from __future__ import annotations
+
+import pytest
+
+from repowise.server import chat_figures
+from repowise.server.chat_figures import check_figures
+
+_SOURCE = {
+ "coverage": 0.734,
+ "elapsed_ms": 1500,
+ "size_bytes": 1_258_291,
+ "files_total": 1234,
+ "summary": "fixed in 63 commits, 12.5% of them reverted, cache 340 KB",
+ "callers": [{"path": "a.py"}, {"path": "b.py"}, {"path": "c.py"}],
+}
+
+
+def _verdicts(answer: str, question: str = "") -> list[tuple[str, bool]]:
+ return [(f.text, f.verified) for f in check_figures(answer, [("a1", _SOURCE)], question).figures]
+
+
+ ("answer", "figure"),
+ [
+ ("Coverage is 73%.", "73%"),
+ ("Coverage is 73.4%.", "73.4%"),
+ ("Coverage is 0.73.", "0.73"),
+ ("Indexing took 1.5 s.", "1.5 s"),
+ ("Indexing took 1500 ms.", "1500 ms"),
+ ("Indexing took 1.5 seconds.", "1.5 seconds"),
+ ("The index is 1.2 MB.", "1.2 MB"),
+ ("The cache is 0.33 MB.", "0.33 MB"),
+ ("It holds 1,234 files.", "1,234"),
+ ("It holds 1.2k files.", "1.2k"),
+ ("It holds about 1,200 files.", "1,200"),
+ ("It holds roughly 1,300 files.", "1,300"),
+ ("It holds 1,200+ files.", "1,200"),
+ ("Fixed in 63 commits.", "63"),
+ ("12.5% were reverted.", "12.5%"),
+ ("13% were reverted.", "13%"),
+ ("It has 3 callers.", "3"),
+ ],
+)
+def test_a_figure_a_tool_returned_is_verified_in_any_rounding_or_unit(answer, figure):
+ assert _verdicts(answer) == [(figure, True)]
+
+
+ ("answer", "figure"),
+ [
+ ("Coverage is 75%.", "75%"),
+ ("Coverage is 73.9%.", "73.9%"),
+ ("It holds 1,200 files.", "1,200"),
+ ("It holds 2.4k files.", "2.4k"),
+ ("Indexing took 9 s.", "9 s"),
+ ("Fixed in 64 commits.", "64"),
+ ],
+)
+def test_a_figure_no_tool_returned_is_flagged(answer, figure):
+ assert _verdicts(answer) == [(figure, False)]
+
+
+ "answer",
+ [
+ "See `chat.py:120` and chat.py:120-140.",
+ "Read lines 10-20 and line 42.",
+ "Defined around line **485**, lines **1156–1160**.",
+ "Released in v1.2.3 and 0.56.0.",
+ "Indexed on 2026-10-14T09:30:00Z, in 2025, on Oct 14 and 14 October.",
+ "Merged in #3736 at commit 5a502a32.",
+ "1. First step\n2. Second step\n- 3) third",
+ "Uses utf-8, sha256, x86_64, gpt-5 and the 3rd pass.",
+ "```python\nx = 99\n```",
+ "Open https://example.com/page/77 or [docs](https://example.com/88).",
+ "Ranked top 10, tier 2, phase 4, step 5.",
+ "The ratio was 3:1 at 14:30.",
+ "See note [4] and (5).",
+ "Under packages/v2/src and file2.py.",
+ ],
+)
+def test_numbers_that_are_not_figures_are_not_checked(answer):
+ assert _verdicts(answer) == []
+
+
+def test_a_number_the_question_holds_is_not_checked():
+ assert _verdicts("Here are the 7 riskiest files.", question="Show the 7 riskiest files") == []
+
+
+def test_a_verified_figure_cites_the_artifact_it_came_from():
+ figures = check_figures("63 commits", [("a1", {"n": 5}), ("a2", {"n": 63})]).figures
+
+ assert [f.to_json() for f in figures] == [
+ {"text": "63", "start": 0, "end": 2, "verified": True, "artifact_id": "a2"}
+ ]
+
+
+def test_offsets_are_utf16_units():
+ answer = "\N{ROCKET} 99 bugs"
+ (figure,) = check_figures(answer, []).figures
+
+ assert (figure.start, figure.end) == (3, 5)
+ assert answer.encode("utf-16-le")[figure.start * 2 : figure.end * 2].decode("utf-16-le") == "99"
+
+
+def test_an_answer_without_digits_is_not_checked():
+ assert check_figures("No numbers.", [("a1", _SOURCE)]).figures == []
+
+
+def test_a_signed_figure_matches_only_its_sign():
+ sources = [("a1", {"delta": 5, "drop": -7})]
+
+ def verdicts(answer):
+ return [(f.text, f.verified) for f in check_figures(answer, sources).figures]
+
+ assert verdicts("Health moved by -5.") == [("-5", False)]
+ assert verdicts("Health moved by -7, a drop of 7.") == [("-7", True), ("7", True)]
+ # A range keeps each end unsigned.
+ assert verdicts("Between 5-7 points.") == [("5", True), ("7", True)]
+
+
+def test_figures_in_cjk_prose_are_checked():
+ answer = "该文件有 63 次提交,覆盖率为75%。"
+
+ assert _verdicts(answer) == [("63", True), ("75%", False)]
+
+
+def test_earlier_turns_are_read_only_for_figures_this_turn_does_not_hold():
+ check = check_figures(
+ "3 callers and 63 commits",
+ [("now", {"callers": 3})],
+ earlier=[("before", {"commits": 63, "callers": 3})],
+ )
+
+ assert [(f.text, f.artifact_id) for f in check.figures] == [("3", "now"), ("63", "before")]
+
+
+def test_evidence_past_the_read_cap_leaves_unmatched_figures_not_checked(monkeypatch):
+ monkeypatch.setattr(chat_figures, "MAX_NODES_PER_ARTIFACT", 10)
+ rows = [{"n": i} for i in range(1000)]
+
+ # Evidence is read in document order, so the cap leaves the tail unread.
+ check = check_figures("Found 5 and 999.", [("a1", {"total": 5, "rows": rows})])
+
+ assert [(f.text, f.verified) for f in check.figures] == [("5", True)]
+ assert check.not_checked == 1
+ assert check.diagnostics() == {
+ "figures_checked": 1,
+ "figures_unverified": 0,
+ "figures_not_checked": 1,
+ }
diff --git a/tests/unit/server/test_chat_session.py b/tests/unit/server/test_chat_session.py
index 927f012a5..67acfee4f 100644
--- a/tests/unit/server/test_chat_session.py
+++ b/tests/unit/server/test_chat_session.py
@@ -479,7 +479,14 @@ async def test_a_retried_send_returns_the_stored_reply(store):
assert again.replayed and not first.replayed
assert again.message_id == first.message_id
assert again.answer == first.answer == "answer"
- assert again.citations == first.citations == [{"file_path": "src/a.py"}]
+ assert again.citations == first.citations
+ (citation,) = first.citations
+ stored = (await store.messages(session.id))[-1].content
+ assert citation == {
+ "file_path": "src/a.py",
+ "artifact_id": stored["tool_calls"][0]["artifact"]["id"],
+ "ref": {"type": "file", "id": "src/a.py"},
+ }
assert events[-1]["type"] == "done" and events[-1]["replayed"] is True
assert [m.role for m in await store.messages(session.id)] == ["user", "assistant"]
@@ -699,3 +706,69 @@ async def test_a_key_reused_with_another_message_conflicts(store):
await session.send("another question", idempotency_key="k1")
await session.check_send("first question", "k1")
assert len(provider.calls) == 1
+
+
+# ---------------------------------------------------------------------------
+# Numeric check
+# ---------------------------------------------------------------------------
+
+
+def _figure_turns(answer: str) -> Callable[[int], list]:
+ return lambda i: [_text("Let me look. "), _tool("t1", "get_risk")] if i == 0 else [_text(answer)]
+
+
+async def test_figures_are_checked_against_the_turns_tool_results(store):
+ session = await _open(store, ScriptedProvider(_figure_turns("src/a.py has 3 fixes and 17 callers.")))
+
+ events = await _collect(session.stream("how risky is a.py?"))
+
+ streamed = "".join(e["text"] for e in events if e["type"] == "text_delta")
+ (diagnostics,) = [e for e in events if e["type"] == "diagnostics"]
+ assert diagnostics["figures_checked"] == 2 and diagnostics["figures_unverified"] == 1
+ # Offsets index the streamed text, which also holds the text before the tool call.
+ (span,) = diagnostics["unverified_figures"]
+ assert streamed[span["start"] : span["end"]] == span["text"] == "17"
+ assert [e["type"] for e in events][-3:] == ["diagnostics", "suggestions", "done"]
+
+ content = (await store.messages(session.id))[-1].content
+ artifact_id = content["tool_calls"][0]["artifact"]["id"]
+ assert content["diagnostics"] == {"figures_checked": 2, "figures_unverified": 1}
+ assert content["figures"] == [
+ {"text": "3", "start": 13, "end": 14, "verified": True, "artifact_id": artifact_id},
+ {"text": "17", "start": 25, "end": 27, "verified": False},
+ ]
+
+
+async def test_the_result_and_a_replay_carry_the_figures(store):
+ session = await _open(store, ScriptedProvider(_figure_turns("3 fixes, 40 callers.")))
+
+ first = await session.send("q", idempotency_key="k1")
+ replay_events = await _collect(session.stream("q", idempotency_key="k1"))
+
+ assert first.diagnostics == {"figures_checked": 2, "figures_unverified": 1}
+ assert [f["verified"] for f in first.figures] == [True, False]
+ (diagnostics,) = [e for e in replay_events if e["type"] == "diagnostics"]
+ # A replay streams the answer alone, so the offsets are the stored ones.
+ assert diagnostics["unverified_figures"] == [{"text": "40", "start": 9, "end": 11}]
+
+
+async def test_a_figure_from_an_earlier_turns_tool_result_is_verified(store):
+ provider = ScriptedProvider(
+ lambda i: [_tool("t1", "get_risk")] if i == 0 else [_text("Noted." if i == 1 else "Still 3 fixes.")]
+ )
+ session = await _open(store, provider)
+
+ await session.send("first")
+ later = await session.send("and now?")
+
+ assert later.diagnostics == {"figures_checked": 1, "figures_unverified": 0}
+
+
+async def test_an_answer_without_figures_stores_no_check(store):
+ session = await _open(store, ScriptedProvider([[_text("No numbers here.")]]))
+
+ events = await _collect(session.stream("hello"))
+
+ assert "diagnostics" not in [e["type"] for e in events]
+ content = (await store.messages(session.id))[-1].content
+ assert "figures" not in content and "diagnostics" not in content
diff --git a/tests/unit/server/test_chat_session_routes.py b/tests/unit/server/test_chat_session_routes.py
index e10aafcfa..4ece00c0d 100644
--- a/tests/unit/server/test_chat_session_routes.py
+++ b/tests/unit/server/test_chat_session_routes.py
@@ -78,7 +78,10 @@ async def test_send_returns_the_turn_result_as_json_and_replays_a_retry():
result = first.json()
assert result["answer"] == "Risky."
assert result["stop_reason"] == "answered"
- assert result["citations"] == [{"file_path": "src/a.py"}]
+ (citation,) = result["citations"]
+ assert citation["file_path"] == "src/a.py" and len(citation["artifact_id"]) == 32
+ assert citation["ref"]["type"] == "file" and citation["ref"]["id"] == "src/a.py"
+ assert result["figures"] == [] and result["diagnostics"] == {}
assert [t["name"] for t in result["tool_trace"]] == ["get_risk"]
assert result["usage"]["model_calls"] == 2
assert retry.json()["replayed"] is True