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(types): renderer-neutral evidence cards with a validator and web renderer (#3718)
Raghav Chamadiya232a59fb584a
diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex c963094ab..197ccb93e 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -15,6 +15,7 @@"./blast-radius": "./src/blast-radius.ts","./c4": "./src/c4.ts","./cache": "./src/cache.ts",+ "./cards": "./src/cards.ts","./chat": "./src/chat.ts","./code-health": "./src/code-health.ts","./costs": "./src/costs.ts",diff --git a/packages/api-client/src/cards.test.ts b/packages/api-client/src/cards.test.tsnew file mode 100644index 000000000..31c1e341c--- /dev/null+++ b/packages/api-client/src/cards.test.ts@@ -0,0 +1,216 @@+import { describe, expect, it } from "vitest";++import {+ EVIDENCE_CARD_KINDS,+ MAX_CARD_LIST_LENGTH,+ MAX_CARDS_PER_MESSAGE,+ parseEvidenceCards,+ validateEvidenceCard,+ type CardBasis,+ type CardSpec,+ type EvidenceCard,+} from "./cards";++const base = {+ schema_version: 1 as const,+ title: "Title",+ facts: [+ {+ label: "Files touched",+ value: 3,+ basis: { kind: "measured" as const, source: "git history" },+ },+ ],+ evidence: [+ {+ statement: "auth/session.py is imported by 14 modules",+ basis: { kind: "inferred" as const, source: "import graph" },+ refs: [{ type: "file" as const, id: "auth/session.py", start_line: 10, end_line: 42 }],+ },+ ],+ links: [{ label: "Session store", ref: { type: "symbol" as const, id: "auth/session.py::Store" } }],+ generated_at: "2026-10-14T09:30:00Z",+};++const VALID: Record<EvidenceCard["kind"], EvidenceCard> = {+ answer: {+ ...base,+ kind: "answer",+ question: "Where are sessions stored?",+ summary: "Sessions live in the Store class.",+ confidence: "high",+ repo: { id: "r1", name: "acme" },+ },+ change: { ...base, kind: "change", change: { type: "commit", id: "4c1e31f" } },+ component: {+ ...base,+ kind: "component",+ component: { type: "component", id: "payments" },+ facts: [+ {+ label: "Criticality",+ value: "high",+ basis: { kind: "declared", source: ".repowise/components.yaml" },+ },+ ],+ },+ scope: { ...base, kind: "scope", request: "Add SSO to the login page", evidence: [] },+ suspects: {+ ...base,+ kind: "suspects",+ incident: "Checkout errors after 14:00",+ window: { since: "2026-10-13T00:00:00Z", until: "2026-10-14T00:00:00Z" },+ },+ event: {+ ...base,+ kind: "event",+ event_type: "health.dropped",+ occurred_at: "2026-10-14T08:00:00Z",+ facts: [],+ links: [],+ },+};++const INVALID: Array<[string, unknown, string]> = [+ ["not an object", "card", "card.kind"],+ ["unknown kind", { ...VALID.answer, kind: "owner" }, "card.kind"],+ ["wrong schema version", { ...VALID.answer, schema_version: 2 }, "card.schema_version"],+ ["missing kind field", { ...base, kind: "change" }, "card.change: required"],+ [+ "fact without basis",+ { ...VALID.change, facts: [{ label: "Files", value: 3 }] },+ "card.facts[0].basis: required",+ ],+ [+ "evidence basis without source",+ { ...VALID.change, evidence: [{ statement: "x", basis: { kind: "measured" } }] },+ "card.evidence[0].basis.source: required",+ ],+ [+ "unknown basis kind",+ { ...VALID.change, evidence: [{ statement: "x", basis: { kind: "guessed", source: "s" } }] },+ "card.evidence[0].basis.kind",+ ],+ [+ "person field",+ { ...VALID.change, author: "[email protected]" },+ "card.author: unknown field",+ ],+ [+ "person in a fact",+ { ...VALID.change, facts: [{ ...base.facts[0], owner: "someone" }] },+ "card.facts[0].owner: unknown field",+ ],+ [+ "link is a URL",+ { ...VALID.change, links: [{ label: "x", url: "https://example.com" }] },+ "card.links[0].ref: required",+ ],+ [+ "unknown ref type",+ { ...VALID.change, change: { type: "person", id: "x" } },+ "card.change.type",+ ],+ ["bad line", { ...VALID.change, links: [{ label: "x", ref: { type: "file", id: "a", start_line: 0 } }] }, "start_line"],+ ["non-finite number", { ...VALID.change, facts: [{ ...base.facts[0], value: Number.NaN }] }, "card.facts[0].value"],+ ["bad timestamp", { ...VALID.event, occurred_at: "yesterday" }, "card.occurred_at"],+ ["field of another kind", { ...VALID.answer, window: VALID.suspects }, "card.window: unknown field"],+ ["empty title", { ...VALID.answer, title: "" }, "card.title"],+ ["inherited name as a field", { ...VALID.answer, constructor: "x" }, "card.constructor: unknown field"],+ ["toString as a field", { ...VALID.answer, toString: "x" }, "card.toString: unknown field"],+ [+ "own __proto__",+ JSON.parse(`{"__proto__": {"x": 1}, ${JSON.stringify(VALID.answer).slice(1)}`),+ "card.__proto__: unknown field",+ ],+ [+ "required field only on the prototype",+ Object.assign(Object.create({ title: "From the prototype" }), (({ title: _t, ...rest }) => rest)(VALID.answer)),+ "card.title: required",+ ],+ ["optional key set to undefined", { ...VALID.answer, summary: undefined }, "card.summary"],+ ["date without time", { ...VALID.answer, generated_at: "2026-10-14" }, "card.generated_at"],+ ["bare number as a date", { ...VALID.answer, generated_at: "1" }, "card.generated_at"],+ ["prose date", { ...VALID.answer, generated_at: "March 5" }, "card.generated_at"],+ ["timestamp without a zone", { ...VALID.answer, generated_at: "2026-10-14T09:30:00" }, "card.generated_at"],+ ["impossible month", { ...VALID.answer, generated_at: "2026-13-14T09:30:00Z" }, "card.generated_at"],+ ["February 30", { ...VALID.answer, generated_at: "2026-02-30T09:30:00Z" }, "card.generated_at"],+ ["April 31", { ...VALID.answer, generated_at: "2026-04-31T09:30:00Z" }, "card.generated_at"],+ ["February 29 in a common year", { ...VALID.answer, generated_at: "2026-02-29T09:30:00Z" }, "card.generated_at"],+ ["hour 24", { ...VALID.answer, generated_at: "2026-10-14T24:00:00Z" }, "card.generated_at"],+ ["second 60", { ...VALID.answer, generated_at: "2026-10-14T09:30:60Z" }, "card.generated_at"],+ [+ "end before start",+ { ...VALID.change, links: [{ label: "x", ref: { type: "file", id: "a", start_line: 9, end_line: 3 } }] },+ "end_line: before start_line",+ ],+ [+ "end without start",+ { ...VALID.change, links: [{ label: "x", ref: { type: "file", id: "a", end_line: 3 } }] },+ "end_line: requires start_line",+ ],+ [+ "lines on a commit ref",+ { ...VALID.change, change: { type: "commit", id: "abc", start_line: 1 } },+ "line numbers only apply to file and symbol refs",+ ],+ [+ "too many facts",+ { ...VALID.change, facts: Array.from({ length: MAX_CARD_LIST_LENGTH + 1 }, () => base.facts[0]) },+ `card.facts: more than ${MAX_CARD_LIST_LENGTH} items`,+ ],+];++describe("evidence card conformance", () => {+ it("has a valid fixture for every kind", () => {+ expect(Object.keys(VALID).sort()).toEqual([...EVIDENCE_CARD_KINDS].sort());+ });++ it.each(Object.entries(VALID))("accepts a valid %s card", (_kind, card) => {+ expect(validateEvidenceCard(card)).toEqual({ ok: true, card });+ });++ it.each(INVALID)("rejects %s", (_name, card, error) => {+ const result = validateEvidenceCard(card);+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.errors.join("\n")).toContain(error);+ });++ it.each(Object.entries(VALID))("round-trips a %s card through JSON unchanged", (_kind, card) => {+ const wire = JSON.parse(JSON.stringify(card)) as unknown;+ expect(wire).toEqual(card);+ expect(validateEvidenceCard(wire)).toEqual({ ok: true, card });+ });++ it("accepts a timestamp with an offset and fractional seconds", () => {+ expect(+ validateEvidenceCard({ ...VALID.answer, generated_at: "2026-10-14T09:30:00.123+05:30" }).ok,+ ).toBe(true);+ });++ it("accepts February 29 in a leap year", () => {+ expect(validateEvidenceCard({ ...VALID.answer, generated_at: "2028-02-29T09:30:00Z" }).ok).toBe(true);+ });++ it("reads at most the per-message cap of cards", () => {+ const many = Array.from({ length: MAX_CARDS_PER_MESSAGE + 10 }, () => VALID.answer);+ expect(parseEvidenceCards(many)).toHaveLength(MAX_CARDS_PER_MESSAGE);+ });++ it("needs a check for every field of a card type", () => {+ const check = () => {};+ // @ts-expect-error a field without a check fails to compile+ const missing: CardSpec<CardBasis> = { required: { kind: check }, optional: {} };+ // @ts-expect-error a check for a field the type lacks fails to compile+ const extra: CardSpec<CardBasis> = { required: { kind: check, source: check, owner: check }, optional: {} };+ expect([missing, extra]).toHaveLength(2);+ });++ it("keeps the valid cards of a mixed list", () => {+ expect(parseEvidenceCards([VALID.answer, { kind: "owner" }, VALID.scope])).toEqual([+ VALID.answer,+ VALID.scope,+ ]);+ expect(parseEvidenceCards(undefined)).toEqual([]);+ });+});diff --git a/packages/api-client/src/cards.ts b/packages/api-client/src/cards.tsnew file mode 100644index 000000000..951131060--- /dev/null+++ b/packages/api-client/src/cards.ts@@ -0,0 +1,235 @@+/**+ * Evidence cards: the schema re-exported, plus a dependency-free validator any+ * renderer can run on a payload before trusting it.+ *+ * Validation is strict: unknown fields are rejected, so a card can never carry+ * data the schema does not name (a person field, a renderer hint) and a valid+ * card round-trips through JSON unchanged. Only own keys count, so a prototype+ * can neither supply a required field nor smuggle in an inherited one.+ */++import {+ CARD_BASIS_KINDS,+ CARD_CONFIDENCE_LEVELS,+ CARD_REF_TYPES,+ EVIDENCE_CARD_KINDS,+ EVIDENCE_CARD_SCHEMA_VERSION,+ type CardBasis,+ type CardEvidenceRow,+ type CardFact,+ type CardLink,+ type CardRef,+ type EvidenceCard,+ type EvidenceCardKind,+ type SuspectsCard,+} from "@repowise-dev/types/cards";++export * from "@repowise-dev/types/cards";++export type CardValidation =+ | { ok: true; card: EvidenceCard }+ | { ok: false; errors: string[] };++/** Most cards one message renders; a longer list is cut, not rejected. */+export const MAX_CARDS_PER_MESSAGE = 50;+/** Most facts, evidence rows, links or refs one list in a card may hold. */+export const MAX_CARD_LIST_LENGTH = 100;++type Rec = Record<string, unknown>;+type Check = (value: unknown, path: string, errors: string[]) => void;++type OptionalKeys<T> = { [K in keyof T]-?: object extends Pick<T, K> ? K : never }[keyof T];+type RequiredKeys<T> = Exclude<keyof T, OptionalKeys<T>>;+/**+ * One check per field of `T`, split by whether `T` requires it. A field added+ * to a card type without a check here fails to compile.+ */+export interface CardSpec<T> {+ required: { [K in RequiredKeys<T>]: Check };+ optional: { [K in OptionalKeys<T>]: Check };+}++const isRec = (v: unknown): v is Rec =>+ typeof v === "object" && v !== null && !Array.isArray(v);++const str: Check = (v, p, e) => {+ if (typeof v !== "string" || v.length === 0) e.push(`${p}: expected a non-empty string`);+};+const line: Check = (v, p, e) => {+ if (!Number.isInteger(v) || (v as number) < 1) e.push(`${p}: expected a positive integer`);+};+const oneOf =+ (values: readonly string[]): Check =>+ (v, p, e) => {+ if (typeof v !== "string" || !values.includes(v)) {+ e.push(`${p}: expected one of ${values.join(", ")}`);+ }+ };+const value: Check = (v, p, e) => {+ if (!(typeof v === "string" || (typeof v === "number" && Number.isFinite(v)))) {+ e.push(`${p}: expected a string or a finite number`);+ }+};+const ISO_8601 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(?:\.\d+)?)?(?:Z|[+-]\d{2}:\d{2})$/;+/** Date.parse rolls impossible dates over (Feb 30 becomes Mar 2), so the fields are compared back. */+function isIsoTimestamp(v: string): boolean {+ const m = ISO_8601.exec(v);+ if (!m) return false;+ const [y, mo, d, h, mi, sec] = m.slice(1, 7).map((x) => Number(x ?? 0));+ const t = new Date(Date.UTC(y!, mo! - 1, d!, h!, mi!, sec!));+ return (+ t.getUTCFullYear() === y &&+ t.getUTCMonth() === mo! - 1 &&+ t.getUTCDate() === d &&+ t.getUTCHours() === h &&+ t.getUTCMinutes() === mi &&+ t.getUTCSeconds() === sec+ );+}+const timestamp: Check = (v, p, e) => {+ if (typeof v !== "string" || !isIsoTimestamp(v)) {+ e.push(`${p}: expected an ISO 8601 timestamp with a time zone`);+ }+};++/** Checks an object's own fields; any other own key is an error. */+function obj<T>(spec: CardSpec<T>, refine?: (v: Rec, p: string, e: string[]) => void): Check {+ const required = Object.entries(spec.required) as Array<[string, Check]>;+ const optional = Object.entries(spec.optional) as Array<[string, Check]>;+ const known = new Set([...required, ...optional].map(([key]) => key));+ return (v, p, e) => {+ if (!isRec(v)) {+ e.push(`${p}: expected an object`);+ return;+ }+ for (const [key, check] of required) {+ if (!Object.hasOwn(v, key)) e.push(`${p}.${key}: required`);+ else check(v[key], `${p}.${key}`, e);+ }+ for (const [key, check] of optional) {+ // Present means checked, so an optional key set to undefined is rejected.+ if (Object.hasOwn(v, key)) check(v[key], `${p}.${key}`, e);+ }+ for (const key of Object.keys(v)) {+ if (!known.has(key)) e.push(`${p}.${key}: unknown field`);+ }+ refine?.(v, p, e);+ };+}++const list =+ (item: Check): Check =>+ (v, p, e) => {+ if (!Array.isArray(v)) {+ e.push(`${p}: expected an array`);+ return;+ }+ if (v.length > MAX_CARD_LIST_LENGTH) {+ e.push(`${p}: more than ${MAX_CARD_LIST_LENGTH} items`);+ return;+ }+ v.forEach((x, i) => item(x, `${p}[${i}]`, e));+ };++const none = {} as const;++const basis = obj<CardBasis>({+ required: { kind: oneOf(CARD_BASIS_KINDS), source: str },+ optional: none,+});++const ref = obj<CardRef>(+ {+ required: { type: oneOf(CARD_REF_TYPES), id: str },+ optional: { start_line: line, end_line: line },+ },+ (r, p, e) => {+ const hasStart = Object.hasOwn(r, "start_line");+ const hasEnd = Object.hasOwn(r, "end_line");+ if ((hasStart || hasEnd) && r.type !== "file" && r.type !== "symbol") {+ e.push(`${p}: line numbers only apply to file and symbol refs`);+ }+ if (hasEnd && !hasStart) e.push(`${p}.end_line: requires start_line`);+ if (hasStart && hasEnd && (r.end_line as number) < (r.start_line as number)) {+ e.push(`${p}.end_line: before start_line`);+ }+ },+);++type CardOf<K extends EvidenceCardKind> = Extract<EvidenceCard, { kind: K }>;+type CardBase = Omit<CardOf<"answer">, "question" | "kind"> & { kind: EvidenceCardKind };++const BASE: CardSpec<CardBase> = {+ required: {+ schema_version: (v, p, e) => {+ if (v !== EVIDENCE_CARD_SCHEMA_VERSION) {+ e.push(`${p}: expected ${EVIDENCE_CARD_SCHEMA_VERSION}`);+ }+ },+ kind: oneOf(EVIDENCE_CARD_KINDS),+ title: str,+ facts: list(obj<CardFact>({ required: { label: str, value, basis }, optional: { ref } })),+ evidence: list(+ obj<CardEvidenceRow>({ required: { statement: str, basis }, optional: { refs: list(ref) } }),+ ),+ links: list(obj<CardLink>({ required: { label: str, ref }, optional: none })),+ generated_at: timestamp,+ },+ optional: {+ summary: str,+ confidence: oneOf(CARD_CONFIDENCE_LEVELS),+ repo: obj<{ id: string; name: string }>({ required: { id: str, name: str }, optional: none }),+ },+};++/** A kind's spec: the base checks plus the kind's own, typed against the card. */+function kindSpec<T extends CardBase>(+ required: Omit<CardSpec<T>["required"], keyof CardBase>,+ optional: Omit<CardSpec<T>["optional"], keyof CardBase>,+): Check {+ return obj<T>({+ required: { ...BASE.required, ...required },+ optional: { ...BASE.optional, ...optional },+ } as CardSpec<T>);+}++const CARD_CHECKS: { [K in EvidenceCardKind]: Check } = {+ answer: kindSpec<CardOf<"answer">>({ question: str }, none),+ change: kindSpec<CardOf<"change">>({ change: ref }, none),+ component: kindSpec<CardOf<"component">>({ component: ref }, none),+ scope: kindSpec<CardOf<"scope">>({ request: str }, none),+ suspects: kindSpec<SuspectsCard>(+ { incident: str },+ {+ window: obj<NonNullable<SuspectsCard["window"]>>({+ required: { since: timestamp, until: timestamp },+ optional: none,+ }),+ },+ ),+ event: kindSpec<CardOf<"event">>({ event_type: str, occurred_at: timestamp }, none),+};++/** Validates one card, returning every problem found rather than the first. */+export function validateEvidenceCard(input: unknown): CardValidation {+ const errors: string[] = [];+ const kind = isRec(input) && Object.hasOwn(input, "kind") ? input.kind : undefined;+ if (typeof kind !== "string" || !(EVIDENCE_CARD_KINDS as readonly string[]).includes(kind)) {+ errors.push(`card.kind: expected one of ${EVIDENCE_CARD_KINDS.join(", ")}`);+ return { ok: false, errors };+ }+ CARD_CHECKS[kind as EvidenceCardKind](input, "card", errors);+ return errors.length ? { ok: false, errors } : { ok: true, card: input as EvidenceCard };+}++/**+ * Keeps the valid cards of an untrusted list and drops the rest. Only the first+ * `MAX_CARDS_PER_MESSAGE` items are read.+ */+export function parseEvidenceCards(input: unknown): EvidenceCard[] {+ if (!Array.isArray(input)) return [];+ return input.slice(0, MAX_CARDS_PER_MESSAGE).flatMap((item) => {+ const result = validateEvidenceCard(item);+ return result.ok ? [result.card] : [];+ });+}diff --git a/packages/types/package.json b/packages/types/package.jsonindex c8bcf2b23..043bd8902 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -18,6 +18,7 @@"./doc-drift": "./src/doc-drift.ts","./symbols": "./src/symbols.ts","./chat": "./src/chat.ts",+ "./cards": "./src/cards.ts","./workspace": "./src/workspace.ts","./blast-radius": "./src/blast-radius.ts","./risk-semantics": "./src/risk-semantics.ts",diff --git a/packages/types/src/cards.ts b/packages/types/src/cards.tsnew file mode 100644index 000000000..d39f936f5--- /dev/null+++ b/packages/types/src/cards.ts@@ -0,0 +1,140 @@+/**+ * Evidence cards: a renderer-neutral, layout-free summary of one finding.+ *+ * A card is data, not a UI tree. It carries facts, evidence rows and links,+ * and every fact and evidence row says how it is known (`CardBasis`). There is+ * no layout, colour or host vocabulary here, and links are entity refs rather+ * than URLs, so each renderer (the web app, or a chat or ticket mapper outside+ * this repo) builds URLs for its own host. Cards describe changes and+ * components, never people: no field names an author, owner or reviewer.+ *+ * `schema_version` changes whenever a field is added or removed, because the+ * validator in `@repowise-dev/api-client/cards` rejects unknown fields.+ */++export const EVIDENCE_CARD_SCHEMA_VERSION = 1 as const;++export const EVIDENCE_CARD_KINDS = [+ "answer",+ "change",+ "component",+ "scope",+ "suspects",+ "event",+] as const;+export type EvidenceCardKind = (typeof EVIDENCE_CARD_KINDS)[number];++/**+ * How a value is known: `measured` from the index, git or a coverage report;+ * `inferred` from the graph or a heuristic; `declared` by the repo's own+ * config or files; `unresolved` when the evidence could not be read.+ */+export const CARD_BASIS_KINDS = ["measured", "inferred", "declared", "unresolved"] as const;+export type CardBasisKind = (typeof CARD_BASIS_KINDS)[number];++export interface CardBasis {+ kind: CardBasisKind;+ /** What produced the value, e.g. `git history`, `get_risk`, `CODEOWNERS`. */+ source: string;+}++export const CARD_REF_TYPES = [+ "repo",+ "file",+ "symbol",+ "module",+ "component",+ "commit",+ "change",+ "decision",+] as const;+export type CardRefType = (typeof CARD_REF_TYPES)[number];++/** An entity a card points at. Never a URL; the renderer resolves it. */+export interface CardRef {+ type: CardRefType;+ /** Path for a file, qualified id for a symbol, sha for a commit. */+ id: string;+ /** 1-based line range, for file and symbol refs. */+ start_line?: number;+ end_line?: number;+}++export const CARD_CONFIDENCE_LEVELS = ["high", "medium", "low"] as const;+export type CardConfidence = (typeof CARD_CONFIDENCE_LEVELS)[number];++/** One labelled value. A number is left unformatted for the renderer. */+export interface CardFact {+ label: string;+ value: string | number;+ basis: CardBasis;+ ref?: CardRef;+}++/** One checkable statement and the entities it rests on. */+export interface CardEvidenceRow {+ statement: string;+ basis: CardBasis;+ refs?: CardRef[];+}++export interface CardLink {+ label: string;+ ref: CardRef;+}++interface EvidenceCardBase<K extends EvidenceCardKind> {+ schema_version: typeof EVIDENCE_CARD_SCHEMA_VERSION;+ kind: K;+ title: string;+ /** Plain text; renderers must not need markdown to show it. */+ summary?: string;+ confidence?: CardConfidence;+ facts: CardFact[];+ evidence: CardEvidenceRow[];+ links: CardLink[];+ repo?: { id: string; name: string };+ /** ISO 8601 timestamp. */+ generated_at: string;+}++/** An answer to a question about the code. */+export interface AnswerCard extends EvidenceCardBase<"answer"> {+ question: string;+}++/** One commit or change, with the evidence a reviewer checks. */+export interface ChangeCard extends EvidenceCardBase<"change"> {+ change: CardRef;+}++/** One named component and what is known about it. */+export interface ComponentCard extends EvidenceCardBase<"component"> {+ component: CardRef;+}++/** What a described piece of work would touch. */+export interface ScopeCard extends EvidenceCardBase<"scope"> {+ request: string;+}++/** Changes that could explain an incident. Evidence rows are in rank order. */+export interface SuspectsCard extends EvidenceCardBase<"suspects"> {+ incident: string;+ window?: { since: string; until: string };+}++/** Something that happened in the repo, such as a health change on a component. */+export interface EventCard extends EvidenceCardBase<"event"> {+ event_type: string;+ /** ISO 8601 timestamp. */+ occurred_at: string;+}++export type EvidenceCard =+ | AnswerCard+ | ChangeCard+ | ComponentCard+ | ScopeCard+ | SuspectsCard+ | EventCard;diff --git a/packages/types/src/chat.ts b/packages/types/src/chat.tsindex 9333d5b9c..ed4179870 100644--- a/packages/types/src/chat.ts+++ b/packages/types/src/chat.ts@@ -11,6 +11,7 @@ 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";// ---------------------------------------------------------------------------// Product context surrounding a chat composer@@ -124,6 +125,8 @@ export interface ChatMessage {truncated?: boolean;/** Next steps derived from the artifacts this turn produced. */follow_ups?: ChatSuggestion[];+ /** Evidence cards for this turn, unvalidated until parsed. */+ cards?: unknown[];};created_at: string;}@@ -157,6 +160,8 @@ export interface ChatUIMessage {truncated?: boolean;/** Next steps this turn earned. Absent on a turn that called no tool. */followUps?: ChatSuggestion[];+ /** Validated evidence cards for this turn. */+ cards?: EvidenceCard[];}// ---------------------------------------------------------------------------diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex c72e4a0dc..55489eacd 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -18,6 +18,7 @@ export * from "./dead-code.js";export * from "./doc-drift.js";export * from "./symbols.js";export * from "./chat.js";+export * from "./cards.js";export * from "./workspace.js";export * from "./blast-radius.js";export * from "./risk-semantics.js";diff --git a/packages/ui/__tests__/cards/evidence-card.test.tsx b/packages/ui/__tests__/cards/evidence-card.test.tsxnew file mode 100644index 000000000..d62c035fe--- /dev/null+++ b/packages/ui/__tests__/cards/evidence-card.test.tsx@@ -0,0 +1,127 @@+import { describe, expect, it } from "vitest";+import { render, screen, within } from "@testing-library/react";+import type { EvidenceCard } from "@repowise-dev/types/cards";+import type { ChatUIMessage } from "@repowise-dev/types/chat";+import { EvidenceCardView, cardRefHref } from "../../src/cards/evidence-card.js";+import { ChatMessage } from "../../src/chat/chat-message.js";++const CHANGE: EvidenceCard = {+ schema_version: 1,+ kind: "change",+ title: "Session store rewrite",+ summary: "Moves sessions to the new store.",+ confidence: "medium",+ change: { type: "commit", id: "4c1e31f0a2b3" },+ facts: [+ { label: "Files touched", value: 1200, basis: { kind: "measured", source: "git history" } },+ {+ label: "Component",+ value: "auth",+ basis: { kind: "declared", source: ".repowise/components.yaml" },+ ref: { type: "component", id: "auth" },+ },+ ],+ evidence: [+ {+ statement: "Store is imported by 14 modules",+ basis: { kind: "inferred", source: "import graph" },+ refs: [{ type: "file", id: "src/auth/session.py", start_line: 10, end_line: 42 }],+ },+ ],+ links: [+ { label: "Store class", ref: { type: "symbol", id: "src/auth/session.py::Store" } },+ { label: "Payments", ref: { type: "component", id: "payments" } },+ ],+ generated_at: "2026-10-14T09:30:00Z",+};++const href = (ref: Parameters<typeof cardRefHref>[0]) => cardRefHref(ref, "/repos/r1");++describe("EvidenceCardView", () => {+ it("is a labelled region carrying its kind, confidence and subject", () => {+ render(<EvidenceCardView card={CHANGE} buildRefHref={href} />);+ const card = screen.getByRole("region", { name: "Session store rewrite" });+ expect(card).toHaveAttribute("data-card-kind", "change");+ expect(within(card).getByText(/Change · medium confidence/)).toBeInTheDocument();+ expect(within(card).getByRole("link", { name: "4c1e31f" })).toHaveAttribute(+ "href",+ "/repos/r1/commits?commit=4c1e31f0a2b3",+ );+ });++ it("spells out every basis in text, with its source", () => {+ const { container } = render(<EvidenceCardView card={CHANGE} />);+ expect(screen.getByText(/Measured · git history/)).toBeInTheDocument();+ expect(screen.getByText(/Declared · \.repowise\/components\.yaml/)).toBeInTheDocument();+ expect(screen.getByText(/Inferred · import graph/)).toBeInTheDocument();+ expect(container.querySelectorAll("[data-card-basis]")).toHaveLength(3);+ });++ it("formats numbers, and links refs the host can route", () => {+ render(<EvidenceCardView card={CHANGE} buildRefHref={href} />);+ expect(screen.getByText((1200).toLocaleString())).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "session.py:10-42" })).toHaveAttribute(+ "href",+ "/repos/r1/files/src/auth/session.py",+ );+ expect(screen.getByRole("link", { name: "Store class" })).toHaveAttribute(+ "href",+ `/repos/r1/symbols/${encodeURIComponent("src/auth/session.py::Store")}`,+ );+ // No dashboard route for a component: text, not a dead link.+ expect(screen.queryByRole("link", { name: "Payments" })).toBeNull();+ expect(screen.getByText("Payments")).toBeInTheDocument();+ });++ it("renders refs as text when the host gives no resolver", () => {+ render(<EvidenceCardView card={CHANGE} />);+ expect(screen.queryAllByRole("link")).toHaveLength(0);+ });++ it("numbers suspect rows, which arrive in rank order", () => {+ const suspects: EvidenceCard = {+ ...CHANGE,+ kind: "suspects",+ incident: "Checkout errors",+ } as EvidenceCard;+ render(<EvidenceCardView card={suspects} />);+ expect(screen.getByRole("list", { name: "Evidence" }).className).toContain("list-decimal");+ expect(screen.getByText("Checkout errors")).toBeInTheDocument();+ });++ it("keeps list semantics on the styled lists", () => {+ render(<EvidenceCardView card={CHANGE} />);+ expect(screen.getByRole("list", { name: "Evidence" })).toHaveAttribute("role", "list");+ expect(screen.getByRole("list", { name: "Links" })).toHaveAttribute("role", "list");+ });++ it("uses theme tokens only", () => {+ const { container } = render(<EvidenceCardView card={CHANGE} buildRefHref={href} />);+ expect(container.innerHTML).not.toMatch(/#[0-9a-fA-F]{3,8}\b|rgb\(/);+ });+});++describe("ChatMessage cards", () => {+ const message: ChatUIMessage = {+ id: "a1",+ role: "assistant",+ text: "Here is the change.",+ toolCalls: [],+ isStreaming: false,+ cards: [CHANGE],+ };++ it("renders a finished turn's cards with the chat link prefix", () => {+ render(<ChatMessage message={message} repoId="r1" linkPrefix="/w/acme" />);+ expect(screen.getByRole("region", { name: "Session store rewrite" })).toBeInTheDocument();+ expect(screen.getByRole("link", { name: "session.py:10-42" })).toHaveAttribute(+ "href",+ "/w/acme/files/src/auth/session.py",+ );+ });++ it("holds cards back while the turn streams", () => {+ render(<ChatMessage message={{ ...message, isStreaming: true }} repoId="r1" />);+ expect(screen.queryByRole("region", { name: "Session store rewrite" })).toBeNull();+ });+});diff --git a/packages/ui/package.json b/packages/ui/package.jsonindex 1fa4067ba..82edb1399 100644--- a/packages/ui/package.json+++ b/packages/ui/package.json@@ -62,6 +62,8 @@"./wiki/wiki-mdx-preprocess": "./src/wiki/wiki-mdx-preprocess.ts","./wiki/wiki-links-types": "./src/wiki/wiki-links-types.ts","./wiki/*": "./src/wiki/*.tsx",+ "./cards": "./src/cards/index.ts",+ "./cards/*": "./src/cards/*.tsx","./chat": "./src/chat/index.ts","./chat/*": "./src/chat/*.tsx","./dashboard/attention-href": "./src/dashboard/attention-href.ts",diff --git a/packages/ui/src/cards/evidence-card.tsx b/packages/ui/src/cards/evidence-card.tsxnew file mode 100644index 000000000..3260c5199--- /dev/null+++ b/packages/ui/src/cards/evidence-card.tsx@@ -0,0 +1,208 @@+import { useId } from "react";+import type {+ CardBasis,+ CardBasisKind,+ CardRef,+ EvidenceCard,+ EvidenceCardKind,+} from "@repowise-dev/types/cards";+import { fileEntityPath, symbolEntityPath } from "../shared/entity/routes";++const KIND_LABEL: Record<EvidenceCardKind, string> = {+ answer: "Answer",+ change: "Change",+ component: "Component",+ scope: "Scope",+ suspects: "Suspects",+ event: "Event",+};++const BASIS_LABEL: Record<CardBasisKind, string> = {+ measured: "Measured",+ inferred: "Inferred",+ declared: "Declared",+ unresolved: "Unresolved",+};++/**+ * The dashboard route for a card ref, or undefined when the dashboard has no+ * page for that ref type (it is then shown as plain text).+ */+export function cardRefHref(ref: CardRef, prefix: string): string | undefined {+ const id = encodeURIComponent(ref.id);+ switch (ref.type) {+ case "file":+ return fileEntityPath(prefix, ref.id);+ case "symbol":+ return symbolEntityPath(prefix, ref.id);+ case "decision":+ return `${prefix}/decisions/${id}`;+ case "commit":+ return `${prefix}/commits?commit=${id}`;+ default:+ return undefined;+ }+}++function refLabel(ref: CardRef): string {+ const name =+ ref.type === "file"+ ? (ref.id.split("/").pop() ?? ref.id)+ : ref.type === "commit"+ ? ref.id.slice(0, 7)+ : ref.id;+ if (!ref.start_line) return name;+ return ref.end_line && ref.end_line !== ref.start_line+ ? `${name}:${ref.start_line}-${ref.end_line}`+ : `${name}:${ref.start_line}`;+}++function subject(card: EvidenceCard): string | CardRef {+ switch (card.kind) {+ case "answer":+ return card.question;+ case "change":+ return card.change;+ case "component":+ return card.component;+ case "scope":+ return card.request;+ case "suspects":+ return card.incident;+ case "event":+ return card.event_type;+ }+}++type RefHref = (ref: CardRef) => string | undefined;++function RefView({ cardRef, buildRefHref }: { cardRef: CardRef; buildRefHref?: RefHref | undefined }) {+ const href = buildRefHref?.(cardRef);+ const label = refLabel(cardRef);+ const className = "font-mono text-xs [overflow-wrap:anywhere]";+ return href ? (+ <a+ href={href}+ title={cardRef.id}+ className={`${className} text-[var(--color-accent-primary)] rounded-sm underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]`}+ >+ {label}+ </a>+ ) : (+ <code title={cardRef.id} className={`${className} text-[var(--color-text-secondary)]`}>+ {label}+ </code>+ );+}++/** Basis is spelled out, never colour-coded, so it reads the same in every theme. */+function BasisNote({ basis }: { basis: CardBasis }) {+ return (+ <span data-card-basis={basis.kind} className="text-xs text-[var(--color-text-tertiary)]">+ <span className="sr-only">Basis: </span>+ {BASIS_LABEL[basis.kind]} · {basis.source}+ </span>+ );+}++export interface EvidenceCardViewProps {+ card: EvidenceCard;+ /** Resolves a ref to a link; refs it returns undefined for render as text. */+ buildRefHref?: RefHref;+}++export function EvidenceCardView({ card, buildRefHref }: EvidenceCardViewProps) {+ const titleId = useId();+ const about = subject(card);+ return (+ <section+ aria-labelledby={titleId}+ data-card-kind={card.kind}+ className="min-w-0 space-y-2.5 rounded-lg border border-[var(--color-border-default)] bg-[var(--color-bg-surface)] p-3 text-sm text-[var(--color-text-primary)]"+ >+ <header className="space-y-0.5">+ <p className="text-xs text-[var(--color-text-tertiary)]">+ {KIND_LABEL[card.kind]}+ {card.confidence && <> · {card.confidence} confidence</>}+ </p>+ <h3 id={titleId} className="font-medium [overflow-wrap:anywhere]">+ {card.title}+ </h3>+ <p className="text-xs text-[var(--color-text-secondary)] [overflow-wrap:anywhere]">+ {typeof about === "string" ? about : <RefView cardRef={about} buildRefHref={buildRefHref} />}+ </p>+ </header>++ {card.summary && <p className="text-[var(--color-text-secondary)]">{card.summary}</p>}++ {card.facts.length > 0 && (+ <dl className="grid grid-cols-[minmax(0,auto)_minmax(0,1fr)] gap-x-3 gap-y-1.5">+ {card.facts.map((fact, i) => (+ <div key={i} className="contents">+ <dt className="text-[var(--color-text-secondary)]">{fact.label}</dt>+ <dd className="min-w-0 space-x-2">+ <span className="tabular-nums">+ {typeof fact.value === "number" ? fact.value.toLocaleString() : fact.value}+ </span>+ {fact.ref && <RefView cardRef={fact.ref} buildRefHref={buildRefHref} />}+ <BasisNote basis={fact.basis} />+ </dd>+ </div>+ ))}+ </dl>+ )}++ {card.evidence.length > 0 && (+ <ul role="list" aria-label="Evidence" className={card.kind === "suspects" ? "list-decimal space-y-1.5 pl-5" : "space-y-1.5"}>+ {card.evidence.map((row, i) => (+ <li key={i} className="min-w-0">+ <p className="[overflow-wrap:anywhere]">{row.statement}</p>+ <p className="flex flex-wrap items-baseline gap-x-2">+ <BasisNote basis={row.basis} />+ {row.refs?.map((ref, j) => (+ <RefView key={j} cardRef={ref} buildRefHref={buildRefHref} />+ ))}+ </p>+ </li>+ ))}+ </ul>+ )}++ {card.links.length > 0 && (+ <ul role="list" aria-label="Links" className="flex flex-wrap gap-x-3 gap-y-1">+ {card.links.map((link, i) => {+ const href = buildRefHref?.(link.ref);+ return (+ <li key={i} className="text-xs">+ {href ? (+ <a href={href} className="text-[var(--color-accent-primary)] rounded-sm underline-offset-2 hover:underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-[var(--color-accent-primary)]">+ {link.label}+ </a>+ ) : (+ <span className="text-[var(--color-text-secondary)]">{link.label}</span>+ )}+ </li>+ );+ })}+ </ul>+ )}+ </section>+ );+}++export function EvidenceCardList({+ cards,+ buildRefHref,+}: {+ cards: EvidenceCard[];+ buildRefHref?: RefHref;+}) {+ if (cards.length === 0) return null;+ return (+ <div className="space-y-2">+ {cards.map((card, i) => (+ <EvidenceCardView key={i} card={card} {...(buildRefHref ? { buildRefHref } : {})} />+ ))}+ </div>+ );+}diff --git a/packages/ui/src/cards/index.ts b/packages/ui/src/cards/index.tsnew file mode 100644index 000000000..2a08cc6ee--- /dev/null+++ b/packages/ui/src/cards/index.ts@@ -0,0 +1 @@+export * from "./evidence-card";diff --git a/packages/ui/src/chat/chat-message.tsx b/packages/ui/src/chat/chat-message.tsxindex a6cefc0b7..58d839db8 100644--- a/packages/ui/src/chat/chat-message.tsx+++ b/packages/ui/src/chat/chat-message.tsx@@ -8,6 +8,7 @@ import { MessageActions } from "./message-actions";import { CHAT_STAGES, chatStage } from "./chat-stage";import { Markdown } from "../shared/markdown";import { SourceCitations, type SourceReference } from "./source-citations";+import { EvidenceCardList, cardRefHref } from "../cards/evidence-card";import type { ChatArtifact, ChatUIMessage } from "@repowise-dev/types/chat";interface ChatMessageProps {@@ -104,6 +105,14 @@ function ChatMessageImpl({<Markdown content={message.text} density={dock ? "narrow" : "reading"} streaming={message.isStreaming} fill />)}+ {/* Only stored messages carry cards for now; the stream sends none. */}+ {!message.isStreaming && message.cards && (+ <EvidenceCardList+ cards={message.cards}+ buildRefHref={(ref) => cardRefHref(ref, linkPrefix ?? `/repos/${repoId}`)}+ />+ )}+{!message.isStreaming && message.toolCalls.length > 0 && (<SourceCitationstoolCalls={message.toolCalls}diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex 631b4b5ba..1b822eb05 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -31,6 +31,7 @@ export default defineConfig({"@repowise-dev/types/doc-drift": path.resolve(__dirname, "../types/src/doc-drift.ts"),"@repowise-dev/types/symbols": path.resolve(__dirname, "../types/src/symbols.ts"),"@repowise-dev/types/chat": path.resolve(__dirname, "../types/src/chat.ts"),+ "@repowise-dev/types/cards": path.resolve(__dirname, "../types/src/cards.ts"),"@repowise-dev/types/workspace": path.resolve(__dirname, "../types/src/workspace.ts"),"@repowise-dev/types/blast-radius": path.resolve(__dirname, "../types/src/blast-radius.ts"),"@repowise-dev/types/jobs": path.resolve(__dirname, "../types/src/jobs.ts"),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 4e29e734d..19ca0b23c 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@@ -213,4 +213,42 @@ describe("toChatUiMessages grounding and truncation", () => {expect(toChatUiMessages(stored)[0]).not.toHaveProperty("followUps");});++ it("keeps the stored cards that validate and drops the rest", () => {+ const card = {+ schema_version: 1,+ kind: "answer",+ title: "Where sessions live",+ question: "Where are sessions stored?",+ facts: [],+ evidence: [+ {+ statement: "Store owns session state",+ basis: { kind: "inferred", source: "import graph" },+ },+ ],+ links: [],+ generated_at: "2026-10-14T00:00:00Z",+ };+ const stored: ChatMessageResponse[] = [+ {+ id: "m1",+ conversation_id: "c1",+ role: "assistant",+ content: { text: "x", cards: [card, { kind: "answer", author: "someone" }] },+ created_at: "2026-10-14T00:00:00Z",+ },+ {+ id: "m2",+ conversation_id: "c1",+ role: "assistant",+ content: { text: "y", cards: [{ kind: "unknown" }] },+ created_at: "2026-10-14T00:00:00Z",+ },+ ];++ const [withCards, withoutCards] = toChatUiMessages(stored);+ expect(withCards?.cards).toEqual([card]);+ expect(withoutCards).not.toHaveProperty("cards");+ });});diff --git a/packages/web/src/lib/chat/to-chat-ui-messages.ts b/packages/web/src/lib/chat/to-chat-ui-messages.tsindex 74e6739eb..d9c654afa 100644--- a/packages/web/src/lib/chat/to-chat-ui-messages.ts+++ b/packages/web/src/lib/chat/to-chat-ui-messages.ts@@ -1,6 +1,13 @@import type { ChatMessageResponse } from "@/lib/api/types";import type { ChatUIMessage } from "@repowise-dev/types/chat";import { getLegacyChatArtifactType } from "@repowise-dev/ui/chat";+import { parseEvidenceCards } from "@repowise-dev/api-client/cards";++/** Stored cards are untrusted wire data; only the ones that validate render. */+function storedCards(message: ChatMessageResponse): Pick<ChatUIMessage, "cards"> {+ const cards = parseEvidenceCards(message.content.cards);+ return cards.length ? { cards } : {};+}/** Normalize stored API messages into the same shape produced while streaming. */export function toChatUiMessages(@@ -56,5 +63,6 @@ export function toChatUiMessages(...(message.content.follow_ups?.length? { followUps: message.content.follow_ups }: {}),+ ...storedCards(message),}));}