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): chat view parts (table, chart, section) with validator and server twin (#3728)
Raghav Chamadiya4dcfda9f06a3
diff --git a/packages/api-client/package.json b/packages/api-client/package.jsonindex 197ccb93e..41a278de7 100644--- a/packages/api-client/package.json+++ b/packages/api-client/package.json@@ -49,6 +49,7 @@"./security": "./src/security.ts","./stats": "./src/stats.ts","./symbols": "./src/symbols.ts",+ "./views": "./src/views.ts","./workspace": "./src/workspace.ts"},"publishConfig": {diff --git a/packages/api-client/src/cards.ts b/packages/api-client/src/cards.tsindex 951131060..4aa7e4632 100644--- a/packages/api-client/src/cards.ts+++ b/packages/api-client/src/cards.ts@@ -1,29 +1,37 @@/*** 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.+ * renderer can run on a payload before trusting it. Validation is strict; see+ * `./validation` for the shared rules.*/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";+import {+ basis,+ constant,+ isRec,+ list,+ none,+ obj,+ oneOf,+ ref,+ str,+ timestamp,+ value,+ type Check,+ type Spec,+} from "./validation";+export * from "@repowise-dev/types/cards";export type CardValidation =@@ -35,144 +43,29 @@ 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`);- }- },-);+/** Public name of the shared `Spec<T>`, kept for existing imports. */+export type CardSpec<T> = Spec<T>;type CardOf<K extends EvidenceCardKind> = Extract<EvidenceCard, { kind: K }>;type CardBase = Omit<CardOf<"answer">, "question" | "kind"> & { kind: EvidenceCardKind };-const BASE: CardSpec<CardBase> = {+const BASE: Spec<CardBase> = {required: {- schema_version: (v, p, e) => {- if (v !== EVIDENCE_CARD_SCHEMA_VERSION) {- e.push(`${p}: expected ${EVIDENCE_CARD_SCHEMA_VERSION}`);- }- },+ schema_version: constant(EVIDENCE_CARD_SCHEMA_VERSION),kind: oneOf(EVIDENCE_CARD_KINDS),title: str,- facts: list(obj<CardFact>({ required: { label: str, value, basis }, optional: { ref } })),+ facts: list(+ obj<CardFact>({ required: { label: str, value, basis }, optional: { ref } }),+ MAX_CARD_LIST_LENGTH,+ ),evidence: list(- obj<CardEvidenceRow>({ required: { statement: str, basis }, optional: { refs: list(ref) } }),+ obj<CardEvidenceRow>({+ required: { statement: str, basis },+ optional: { refs: list(ref, MAX_CARD_LIST_LENGTH) },+ }),+ MAX_CARD_LIST_LENGTH,),- links: list(obj<CardLink>({ required: { label: str, ref }, optional: none })),+ links: list(obj<CardLink>({ required: { label: str, ref }, optional: none }), MAX_CARD_LIST_LENGTH),generated_at: timestamp,},optional: {@@ -184,13 +77,13 @@ const BASE: CardSpec<CardBase> = {/** 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>,+ required: Omit<Spec<T>["required"], keyof CardBase>,+ optional: Omit<Spec<T>["optional"], keyof CardBase>,): Check {return obj<T>({required: { ...BASE.required, ...required },optional: { ...BASE.optional, ...optional },- } as CardSpec<T>);+ } as Spec<T>);}const CARD_CHECKS: { [K in EvidenceCardKind]: Check } = {diff --git a/packages/api-client/src/validation.ts b/packages/api-client/src/validation.tsnew file mode 100644index 000000000..9ba862592--- /dev/null+++ b/packages/api-client/src/validation.ts@@ -0,0 +1,180 @@+/**+ * Dependency-free validation primitives shared by the evidence card and view+ * part validators.+ *+ * Objects are checked strictly: unknown fields are rejected, so a payload can+ * never carry data its schema does not name (a person field, a renderer hint)+ * and a valid payload round-trips through JSON unchanged. Only own keys count,+ * so a prototype can neither supply a required field nor smuggle in an+ * inherited one. A check reports every problem it reaches; a value of the+ * wrong shape (not an object, a list over its cap) stops the checks beneath it.+ *+ * Numbers are finite and within +/-MAX_WIRE_NUMBER, so every accepted number+ * survives a JSON round trip in both TypeScript and Python unchanged.+ */++import {+ CARD_BASIS_KINDS,+ CARD_REF_TYPES,+ type CardBasis,+ type CardRef,+} from "@repowise-dev/types/cards";++export type Rec = Record<string, unknown>;+export 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 type without a check here fails to compile.+ */+export interface Spec<T> {+ required: { [K in RequiredKeys<T>]: Check };+ optional: { [K in OptionalKeys<T>]: Check };+}++export const isRec = (v: unknown): v is Rec =>+ typeof v === "object" && v !== null && !Array.isArray(v);++export const str: Check = (v, p, e) => {+ if (typeof v !== "string" || v.length === 0) e.push(`${p}: expected a non-empty string`);+};+export const bool: Check = (v, p, e) => {+ if (typeof v !== "boolean") e.push(`${p}: expected a boolean`);+};+/** 2^53 - 1: the largest integer both JSON readers keep exact. */+export const MAX_WIRE_NUMBER = Number.MAX_SAFE_INTEGER;+/** A finite number within +/-MAX_WIRE_NUMBER. */+export const isFiniteNumber = (v: unknown): v is number =>+ typeof v === "number" && Number.isFinite(v) && Math.abs(v) <= MAX_WIRE_NUMBER;+const isWireInteger = (v: unknown): v is number => Number.isInteger(v) && isFiniteNumber(v);+export const line: Check = (v, p, e) => {+ if (!isWireInteger(v) || v < 1) e.push(`${p}: expected a positive integer`);+};+export const oneOf =+ (values: readonly string[]): Check =>+ (v, p, e) => {+ if (typeof v !== "string" || !values.includes(v)) {+ e.push(`${p}: expected one of ${values.join(", ")}`);+ }+ };+export const matches =+ (pattern: RegExp, what: string): Check =>+ (v, p, e) => {+ if (typeof v !== "string" || !pattern.test(v)) e.push(`${p}: expected ${what}`);+ };+export const constant =+ (expected: string | number): Check =>+ (v, p, e) => {+ if (v !== expected) e.push(`${p}: expected ${expected}`);+ };+export const nullable =+ (check: Check): Check =>+ (v, p, e) => {+ if (v !== null) check(v, p, e);+ };+export const count: Check = (v, p, e) => {+ if (!isWireInteger(v) || v < 0) e.push(`${p}: expected a non-negative integer`);+};+export const ratio: Check = (v, p, e) => {+ if (!isFiniteNumber(v) || v < 0 || v > 1) e.push(`${p}: expected a number from 0 to 1`);+};+export const value: Check = (v, p, e) => {+ if (!(typeof v === "string" || isFiniteNumber(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+ );+}+export 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. */+export function obj<T>(spec: Spec<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);+ };+}++/** An array of at most `max` items, each checked. */+export const list =+ (item: Check, max: number): Check =>+ (v, p, e) => {+ if (!Array.isArray(v)) {+ e.push(`${p}: expected an array`);+ return;+ }+ if (v.length > max) {+ e.push(`${p}: more than ${max} items`);+ return;+ }+ v.forEach((x, i) => item(x, `${p}[${i}]`, e));+ };++export const none = {} as const;++/** Values listed more than once, each reported once. */+export function duplicates<T>(items: readonly T[]): T[] {+ const seen = new Set<T>();+ const repeated = new Set<T>();+ for (const item of items) (seen.has(item) ? repeated : seen).add(item);+ return [...repeated];+}++export const BASIS_SPEC: Spec<CardBasis> = {+ required: { kind: oneOf(CARD_BASIS_KINDS), source: str },+ optional: none,+};+export const basis = obj(BASIS_SPEC);++export const REF_SPEC: Spec<CardRef> = {+ required: { type: oneOf(CARD_REF_TYPES), id: str },+ optional: { start_line: line, end_line: line },+};+export const ref = obj(REF_SPEC, (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`);+ }+});diff --git a/packages/api-client/src/views.test.ts b/packages/api-client/src/views.test.tsnew file mode 100644index 000000000..2eef26159--- /dev/null+++ b/packages/api-client/src/views.test.ts@@ -0,0 +1,189 @@+import { readFileSync } from "node:fs";++import { describe, expect, it } from "vitest";++import { CARD_BASIS_KINDS, CARD_REF_TYPES } from "./cards";+import { BASIS_SPEC, MAX_WIRE_NUMBER, REF_SPEC, type Spec } from "./validation";+import {+ CHART_SORT_ORDERS,+ CHART_TYPES,+ VIEW_REGISTRY,+ VIEW_COVERAGE_METRICS,+ VIEW_KINDS,+ VIEW_LIMITS,+ VIEW_SCHEMA_VERSION,+ parseViewParts,+ validateViewPart,+ validateViewParts,+ type ViewPart,+} from "./views";+import { COVERAGE_SPEC, SOURCE_SPEC } from "./views/base";+import { CHART_SPEC } from "./views/chart";+import { NARRATIVE_SPEC, SECTION_SPEC } from "./views/section";+import { COLUMN_SPEC, TABLE_DATA_SPEC, TABLE_SPEC } from "./views/table";++type Json = Record<string, unknown>;+interface Derived {+ from: string;+ drop?: string[];+ set?: Json;+ grow?: Record<string, number>;+}+interface Fixture {+ vocabulary: Json;+ limits: Json;+ fields: Record<string, string[]>;+ valid: Record<string, ViewPart>;+ invalid: Array<Derived & { name: string; error: string }>;+ valid_variants: Array<Derived & { name: string }>;+ valid_lists: Array<{ name: string; items: Derived[] }>;+ invalid_lists: Array<{ name: string; items: Derived[]; repeat?: number; error: string }>;+}++const fixture = JSON.parse(+ readFileSync(new URL("../../types/fixtures/views.conformance.json", import.meta.url), "utf-8"),+) as Fixture;++/** The parent of a dotted path's last segment, and that segment. */+function locate(root: unknown, path: string): [Json, string] {+ const parts = path.split(".");+ const last = parts.pop()!;+ const parent = parts.reduce<unknown>((node, key) => (node as Json)[key], root);+ return [parent as Json, last];+}++function derive({ from, drop = [], set = {}, grow = {} }: Derived): unknown {+ const part = structuredClone(fixture.valid[from]) as unknown;+ for (const path of drop) {+ const [parent, key] = locate(part, path);+ delete parent[key];+ }+ for (const [path, value] of Object.entries(set)) {+ const [parent, key] = locate(part, path);+ parent[key] = structuredClone(value);+ }+ for (const [path, length] of Object.entries(grow)) {+ const [parent, key] = locate(part, path);+ const items = parent[key] as unknown[];+ parent[key] = Array.from({ length }, () => structuredClone(items[0]));+ }+ return part;+}++const SPECS: Record<string, Spec<never>> = {+ CardBasis: BASIS_SPEC,+ CardRef: REF_SPEC,+ ViewSource: SOURCE_SPEC,+ ViewCoverage: COVERAGE_SPEC,+ ViewColumn: COLUMN_SPEC,+ ViewTableData: TABLE_DATA_SPEC,+ NarrativeBlock: NARRATIVE_SPEC,+ TableView: TABLE_SPEC,+ ChartView: CHART_SPEC,+ SectionView: SECTION_SPEC,+} as unknown as Record<string, Spec<never>>;++describe("view part contract shared with the server", () => {+ it("uses the shared vocabulary and limits", () => {+ expect({+ schema_version: VIEW_SCHEMA_VERSION,+ max_wire_number: MAX_WIRE_NUMBER,+ view_kinds: VIEW_KINDS,+ chart_types: CHART_TYPES,+ coverage_metrics: VIEW_COVERAGE_METRICS,+ sort_orders: CHART_SORT_ORDERS,+ basis_kinds: CARD_BASIS_KINDS,+ ref_types: CARD_REF_TYPES,+ }).toEqual(fixture.vocabulary);+ expect(VIEW_LIMITS).toEqual(fixture.limits);+ });++ it.each(Object.entries(fixture.fields))("checks exactly the shared fields of %s", (name, fields) => {+ const spec = SPECS[name]!;+ expect(Object.keys({ ...spec.required, ...spec.optional }).sort()).toEqual([...fields].sort());+ });++ it("has a valid fixture for every kind", () => {+ const kinds = new Set(Object.values(fixture.valid).map((v) => v.kind));+ expect([...kinds].sort()).toEqual([...VIEW_KINDS].sort());+ });++ it.each(Object.entries(fixture.valid))("accepts %s", (_id, view) => {+ expect(validateViewPart(view)).toEqual({ ok: true, view });+ });++ it.each(Object.entries(fixture.valid))("round-trips %s through JSON unchanged", (_id, view) => {+ const wire = JSON.parse(JSON.stringify(view)) as unknown;+ expect(wire).toEqual(view);+ expect(validateViewPart(wire)).toEqual({ ok: true, view });+ });++ it.each(fixture.valid_variants.map((c) => [c.name, c] as const))("accepts the variant: %s", (_name, c) => {+ const view = derive(c);+ expect(validateViewPart(view)).toEqual({ ok: true, view });+ });++ it.each(fixture.invalid.map((c) => [c.name, c] as const))("rejects %s", (_name, c) => {+ const result = validateViewPart(derive(c));+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.errors.join("\n")).toContain(c.error);+ });++ it.each(fixture.valid_lists.map((c) => [c.name, c] as const))("accepts the list: %s", (_name, c) => {+ const views = c.items.map(derive);+ expect(validateViewParts(views)).toEqual({ ok: true, views });+ });++ it.each(fixture.invalid_lists.map((c) => [c.name, c] as const))("rejects the list: %s", (_name, c) => {+ const items = c.items.map(derive);+ const views = c.repeat ? Array.from({ length: c.repeat }, () => items[0]) : items;+ const result = validateViewParts(views);+ expect(result.ok).toBe(false);+ if (!result.ok) expect(result.errors.join("\n")).toContain(c.error);+ });+});++describe("view part validator", () => {+ const table = fixture.valid.t1!;++ it.each([+ [+ "NaN cell",+ { ...table, rows: [{ path: "a.py", churn: Number.NaN, health: 1 }], total_rows: 1, truncated: false },+ ],+ ["infinite coverage", { ...table, coverage: { metric: "test_reach", ratio: Number.POSITIVE_INFINITY } }],+ ["optional key set to undefined", { ...table, summary: undefined }],+ ["inherited name as a field", { ...table, constructor: "x" }],+ [+ "required field only on the prototype",+ Object.assign(Object.create({ title: "From the prototype" }), (({ title: _t, ...rest }) => rest)(table)),+ ],+ ["own __proto__", JSON.parse(`{"__proto__": {"x": 1}, ${JSON.stringify(table).slice(1)}`)],+ ])("rejects %s", (_name, view) => {+ expect(validateViewPart(view).ok).toBe(false);+ });++ it("needs a registry entry for every view kind", () => {+ // @ts-expect-error a kind without an entry fails to compile+ const missing: typeof VIEW_REGISTRY = { table: VIEW_REGISTRY.table, chart: VIEW_REGISTRY.chart };+ // @ts-expect-error isData is typed from the part, so a data kind cannot say false+ const wrong: typeof VIEW_REGISTRY.table = { ...VIEW_REGISTRY.table, isData: false };+ expect([missing, wrong]).toHaveLength(2);+ });++ it("marks exactly the kinds with provenance as data", () => {+ const data = Object.entries(VIEW_REGISTRY).filter(([, entry]) => entry.isData);+ expect(data.map(([kind]) => kind)).toEqual(["table", "chart"]);+ });++ it("keeps what a renderer can show from an untrusted list", () => {+ const { t1, c1, c2, s1 } = fixture.valid as Record<string, ViewPart>;+ const dangling = { ...s1!, id: "s2", view_ids: ["missing"] };+ const parsed = parseViewParts([t1, { kind: "pie" }, c1, { ...c2!, id: "t1" }, s1, dangling]);+ expect(parsed.map((v) => v.id)).toEqual(["t1", "c1", "s1"]);+ expect(parseViewParts(undefined)).toEqual([]);+ expect(parseViewParts(Array.from({ length: VIEW_LIMITS.parts + 5 }, (_, i) => ({ ...t1!, id: `t${i}` })))).toHaveLength(+ VIEW_LIMITS.parts,+ );+ });+});diff --git a/packages/api-client/src/views.ts b/packages/api-client/src/views.tsnew file mode 100644index 000000000..0a275bf46--- /dev/null+++ b/packages/api-client/src/views.ts@@ -0,0 +1,112 @@+/**+ * Chat view parts: the schema re-exported, plus a dependency-free validator a+ * renderer runs on a payload before trusting it.+ *+ * `VIEW_REGISTRY` is the kind registry: one entry per `ViewKind`, each from its+ * own module under `./views/`, declaring the kind's check, whether it is a+ * data part, and which other parts it names. The list-level rules below only+ * iterate the registry, so a new kind never edits them. A kind in+ * `ViewPartsByKind` without an entry here fails to compile.+ */++import {+ VIEW_LIMITS,+ type ViewKind,+ type ViewPart,+ type ViewPartsByKind,+} from "@repowise-dev/types/views";++import { duplicates, isRec } from "./validation";+import type { PartReference, ViewKindEntry } from "./views/base";+import { CHART_KIND } from "./views/chart";+import { SECTION_KIND } from "./views/section";+import { TABLE_KIND } from "./views/table";++export * from "@repowise-dev/types/views";+export type { PartReference, ViewKindEntry } from "./views/base";++export const VIEW_REGISTRY: { [K in ViewKind]: ViewKindEntry<K> } = {+ table: TABLE_KIND,+ chart: CHART_KIND,+ section: SECTION_KIND,+};+export const VIEW_KINDS = Object.keys(VIEW_REGISTRY) as ViewKind[];++export type ViewValidation =+ | { ok: true; view: ViewPart }+ | { ok: false; errors: string[] };++export type ViewListValidation =+ | { ok: true; views: ViewPart[] }+ | { ok: false; errors: string[] };++const entryOf = <K extends ViewKind>(part: ViewPartsByKind[K]): ViewKindEntry<K> =>+ VIEW_REGISTRY[part.kind as K];++function checkPart(input: unknown, path: string, errors: string[]): void {+ const kind = isRec(input) && Object.hasOwn(input, "kind") ? input.kind : undefined;+ if (typeof kind !== "string" || !Object.hasOwn(VIEW_REGISTRY, kind)) {+ errors.push(`${path}.kind: expected one of ${VIEW_KINDS.join(", ")}`);+ return;+ }+ VIEW_REGISTRY[kind as ViewKind].check(input, path, errors);+}++const dataIdsOf = (views: ViewPart[]): Set<string> =>+ new Set(views.filter((v) => entryOf(v).isData).map((v) => v.id));++/** References a part makes that are not data parts in `dataIds`, as errors. */+function unresolved(part: ViewPart, dataIds: ReadonlySet<string>, path: string): string[] {+ const refs: PartReference[] = entryOf(part).references?.(part as never) ?? [];+ return refs+ .filter(([id]) => !dataIds.has(id))+ .map(([id, at]) => `${path}${at}: no data part with id ${id}`);+}++/**+ * Validates one part. Errors name every problem the checks reach; a value of+ * the wrong shape stops the checks beneath it.+ */+export function validateViewPart(input: unknown): ViewValidation {+ const errors: string[] = [];+ checkPart(input, "view", errors);+ return errors.length ? { ok: false, errors } : { ok: true, view: input as ViewPart };+}++/**+ * Validates the parts of one turn or report together: each part, unique ids,+ * and that every id a part names is a data part in the same list.+ */+export function validateViewParts(input: unknown): ViewListValidation {+ if (!Array.isArray(input)) return { ok: false, errors: ["views: expected an array"] };+ if (input.length > VIEW_LIMITS.parts) {+ return { ok: false, errors: [`views: more than ${VIEW_LIMITS.parts} items`] };+ }+ const errors: string[] = [];+ input.forEach((part, i) => checkPart(part, `views[${i}]`, errors));+ if (errors.length) return { ok: false, errors };++ const views = input as ViewPart[];+ for (const id of duplicates(views.map((v) => v.id))) errors.push(`views: duplicate id ${id}`);+ const dataIds = dataIdsOf(views);+ views.forEach((v, i) => errors.push(...unresolved(v, dataIds, `views[${i}]`)));+ return errors.length ? { ok: false, errors } : { ok: true, views };+}++/**+ * Keeps what a renderer can show from an untrusted list: the valid parts among+ * the first `VIEW_LIMITS.parts`, the first part for each id, and only the+ * parts whose references all resolve to a kept data part.+ */+export function parseViewParts(input: unknown): ViewPart[] {+ if (!Array.isArray(input)) return [];+ const seen = new Set<string>();+ const kept = input.slice(0, VIEW_LIMITS.parts).flatMap((item) => {+ const result = validateViewPart(item);+ if (!result.ok || seen.has(result.view.id)) return [];+ seen.add(result.view.id);+ return [result.view];+ });+ const dataIds = dataIdsOf(kept);+ return kept.filter((v) => unresolved(v, dataIds, "").length === 0);+}diff --git a/packages/api-client/src/views/base.ts b/packages/api-client/src/views/base.tsnew file mode 100644index 000000000..451c30ea8--- /dev/null+++ b/packages/api-client/src/views/base.ts@@ -0,0 +1,86 @@+/**+ * What every view kind shares: identity and provenance checks, and the shape+ * of a kind's registry entry.+ */++import {+ VIEW_COVERAGE_METRICS,+ VIEW_SCHEMA_VERSION,+ type ViewCoverage,+ type ViewKind,+ type ViewPartBase,+ type ViewPartsByKind,+ type ViewProvenance,+ type ViewSource,+} from "@repowise-dev/types/views";++import {+ basis,+ bool,+ constant,+ matches,+ none,+ nullable,+ obj,+ oneOf,+ ratio,+ str,+ type Check,+ type Spec,+} from "../validation";++export const PART_ID = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$/;+export const partId = matches(PART_ID, "a part id (letters, digits, _ . : -, at most 64)");++export const SOURCE_SPEC: Spec<ViewSource> = {+ required: {+ artifact_id: str,+ tool_name: str,+ args_hash: matches(/^[0-9a-f]{8,128}$/, "a lowercase hex digest"),+ },+ optional: none,+};++export const COVERAGE_SPEC: Spec<ViewCoverage> = {+ required: { metric: oneOf(VIEW_COVERAGE_METRICS), ratio },+ optional: none,+};++/** The fields of `ViewPartBase`, with `kind` pinned to one kind. */+export function baseSpec<K extends string>(kind: K): Spec<ViewPartBase<K>> {+ return {+ required: {+ schema_version: constant(VIEW_SCHEMA_VERSION),+ kind: constant(kind),+ id: partId,+ title: str,+ },+ optional: { summary: str },+ };+}++export const PROVENANCE_SPEC: Spec<ViewProvenance> = {+ required: {+ source: obj(SOURCE_SPEC),+ basis,+ stale: bool,+ as_of: nullable(matches(/^[0-9a-f]{7,64}$/, "a lowercase commit sha")),+ },+ optional: { coverage: obj(COVERAGE_SPEC) },+};++/** An id another part names, and the path (relative to the part) it is named at. */+export type PartReference = readonly [id: string, path: string];++/** One view kind's entry in `VIEW_REGISTRY`. */+export interface ViewKindEntry<K extends ViewKind> {+ /** Checks one part of this kind on its own. */+ check: Check;+ /**+ * A data part carries provenance and is what other parts may name. Typed+ * from the part, so it cannot disagree with whether the kind has `source`.+ */+ isData: ViewPartsByKind[K] extends ViewProvenance ? true : false;+ /** Ids of data parts this part names; each must be in the same list. */+ references?: (part: ViewPartsByKind[K]) => PartReference[];+}diff --git a/packages/api-client/src/views/chart.ts b/packages/api-client/src/views/chart.tsnew file mode 100644index 000000000..32ff43203--- /dev/null+++ b/packages/api-client/src/views/chart.ts@@ -0,0 +1,133 @@+/**+ * The `chart` view kind. Charts plot their own table, so these rules only+ * check that the chart reads that table honestly: axes name real columns,+ * plotted values are numbers in one unit, a donut is a whole of two to five+ * non-negative parts with a positive total, a stacked bar is not all zeros,+ * and a stated sort order is the order the rows are in (a sorted chart may+ * not hold nulls in its series, since a null has no place in the order).+ */++import {+ CHART_SORT_ORDERS,+ CHART_TYPES,+ VIEW_LIMITS,+ type ChartType,+ type ChartView,+} from "@repowise-dev/types/views";++import {+ duplicates,+ isFiniteNumber,+ isRec,+ list,+ obj,+ oneOf,+ str,+ type Rec,+ type Spec,+} from "../validation";+import { PROVENANCE_SPEC, baseSpec, type ViewKindEntry } from "./base";+import { columnKeys, tableData } from "./table";++/** Fewest and most series each chart type plots. */+const SERIES_BOUNDS: { [T in ChartType]: [number, number] } = {+ bar: [1, VIEW_LIMITS.chart_series],+ line: [1, VIEW_LIMITS.chart_series],+ stacked_bar: [2, VIEW_LIMITS.chart_series],+ donut: [1, 1],+};+/** Chart types whose values are parts of a whole, so never negative. */+const PARTS_OF_A_WHOLE: ReadonlySet<ChartType> = new Set(["stacked_bar", "donut"]);++const base = baseSpec("chart");+export const CHART_SPEC: Spec<ChartView> = {+ required: {+ ...base.required,+ ...PROVENANCE_SPEC.required,+ chart_type: oneOf(CHART_TYPES),+ data: tableData,+ x: str,+ series: list(str, VIEW_LIMITS.chart_series),+ summary: str,+ },+ optional: { ...PROVENANCE_SPEC.optional, sort: oneOf(CHART_SORT_ORDERS) },+};++function chartRules(v: Rec, p: string, e: string[]): void {+ const keyList = columnKeys(v.data);+ const data = v.data as Rec;+ if (keyList === null || !Array.isArray(data.rows) || !Array.isArray(v.series)) return;+ const keys = new Set(keyList);+ const rows = data.rows.filter(isRec);+ const series = v.series.filter((s): s is string => typeof s === "string");+ const plotted = series.filter((s) => keys.has(s) && s !== v.x);+ const type = v.chart_type as ChartType;++ if (typeof v.x === "string" && !keys.has(v.x)) e.push(`${p}.x: not a column of data`);+ series.forEach((s, i) => {+ if (!keys.has(s)) e.push(`${p}.series[${i}]: not a column of data`);+ else if (s === v.x) e.push(`${p}.series[${i}]: is the x column`);+ });+ for (const s of duplicates(series)) e.push(`${p}.series: duplicate ${s}`);++ const bounds = SERIES_BOUNDS[type];+ if (bounds && (series.length < bounds[0] || series.length > bounds[1])) {+ const want = bounds[0] === bounds[1] ? `${bounds[0]}` : `${bounds[0]} to ${bounds[1]}`;+ e.push(`${p}.series: a ${type} chart plots ${want} series`);+ }+ if (rows.length > VIEW_LIMITS.chart_points) {+ e.push(`${p}.data.rows: a chart plots at most ${VIEW_LIMITS.chart_points} rows`);+ }++ const columns = new Map(+ (data.columns as unknown[]).filter(isRec).map((c) => [c.key, c] as const),+ );+ const units = new Set(plotted.map((s) => columns.get(s)?.unit ?? null));+ if (units.size > 1) e.push(`${p}.series: plotted columns must share one unit`);++ const sorted = v.sort === "asc" || v.sort === "desc";+ let total = 0;+ rows.forEach((r, i) => {+ if (typeof v.x === "string" && r[v.x] === null) e.push(`${p}.data.rows[${i}].${v.x}: x is null`);+ for (const s of plotted) {+ const cell = r[s];+ if (cell === undefined) continue;+ if (cell === null) {+ if (type === "donut") e.push(`${p}.data.rows[${i}].${s}: a donut part is null`);+ else if (sorted) e.push(`${p}.data.rows[${i}].${s}: a sorted chart has no nulls`);+ } else if (!isFiniteNumber(cell)) {+ e.push(`${p}.data.rows[${i}].${s}: plotted values must be numbers`);+ } else if (cell < 0 && PARTS_OF_A_WHOLE.has(type)) {+ e.push(`${p}.data.rows[${i}].${s}: a ${type} value cannot be negative`);+ } else {+ total += cell;+ }+ }+ });++ if (PARTS_OF_A_WHOLE.has(type) && rows.length > 0 && total <= 0) {+ e.push(`${p}.data.rows: a ${type} needs a positive total`);+ }+ if (type === "donut") {+ const { donut_min_parts: min, donut_max_parts: max } = VIEW_LIMITS;+ if (rows.length < min || rows.length > max) {+ e.push(`${p}.data.rows: a donut has ${min} to ${max} parts`);+ }+ if (data.truncated === true) e.push(`${p}.data.truncated: a donut must show the whole`);+ }++ if (sorted) {+ const totals = rows.map((r) =>+ plotted.reduce((sum, s) => sum + (isFiniteNumber(r[s]) ? (r[s] as number) : 0), 0),+ );+ const sign = v.sort === "asc" ? 1 : -1;+ if (totals.some((t, i) => i > 0 && sign * (t - totals[i - 1]!) < 0)) {+ e.push(`${p}.sort: rows are not in ${v.sort} order of their series total`);+ }+ }+}++export const CHART_KIND: ViewKindEntry<"chart"> = {+ check: obj(CHART_SPEC, chartRules),+ isData: true,+};diff --git a/packages/api-client/src/views/section.ts b/packages/api-client/src/views/section.tsnew file mode 100644index 000000000..ddd3e7695--- /dev/null+++ b/packages/api-client/src/views/section.ts@@ -0,0 +1,43 @@+/**+ * The `section` view kind. The parts it names are checked where the whole+ * list is visible (`validateViewParts`, through `references`); here only+ * their shape.+ */++import { VIEW_LIMITS, type NarrativeBlock, type SectionView } from "@repowise-dev/types/views";++import { duplicates, list, none, obj, str, type Rec, type Spec } from "../validation";+import { baseSpec, partId, type ViewKindEntry } from "./base";++export const NARRATIVE_SPEC: Spec<NarrativeBlock> = {+ required: { text: str, cites: list(partId, VIEW_LIMITS.parts) },+ optional: none,+};++const base = baseSpec("section");+export const SECTION_SPEC: Spec<SectionView> = {+ required: {+ ...base.required,+ narrative: list(obj(NARRATIVE_SPEC), VIEW_LIMITS.narrative_blocks),+ view_ids: list(partId, VIEW_LIMITS.section_views),+ },+ optional: base.optional,+};++function sectionRules(v: Rec, p: string, e: string[]): void {+ const narrative = Array.isArray(v.narrative) ? v.narrative : [];+ const ids = Array.isArray(v.view_ids) ? v.view_ids : [];+ if (narrative.length === 0 && ids.length === 0) e.push(`${p}: a section needs narrative or views`);+ for (const id of duplicates(ids)) e.push(`${p}.view_ids: duplicate ${String(id)}`);+}++export const SECTION_KIND: ViewKindEntry<"section"> = {+ check: obj(SECTION_SPEC, sectionRules),+ isData: false,+ references: (part) => [+ ...part.view_ids.map((id, j) => [id, `.view_ids[${j}]`] as const),+ ...part.narrative.flatMap((block, j) =>+ block.cites.map((id, k) => [id, `.narrative[${j}].cites[${k}]`] as const),+ ),+ ],+};diff --git a/packages/api-client/src/views/table.ts b/packages/api-client/src/views/table.tsnew file mode 100644index 000000000..3b41d1411--- /dev/null+++ b/packages/api-client/src/views/table.ts@@ -0,0 +1,97 @@+/** The `table` view kind, and the table data a chart plots. */++import {+ VIEW_LIMITS,+ type TableView,+ type ViewColumn,+ type ViewTableData,+} from "@repowise-dev/types/views";++import {+ basis,+ bool,+ count,+ duplicates,+ isFiniteNumber,+ isRec,+ list,+ matches,+ obj,+ ref,+ str,+ type Check,+ type Rec,+ type Spec,+} from "../validation";+import { PROVENANCE_SPEC, baseSpec, type ViewKindEntry } from "./base";++export const COLUMN_SPEC: Spec<ViewColumn> = {+ required: { key: matches(/^[a-z][a-z0-9_]{0,63}$/, "a lowercase column key"), label: str },+ optional: { unit: str, basis },+};++const cell: Check = (v, p, e) => {+ if (v === null || typeof v === "string" || isFiniteNumber(v)) return;+ if (isRec(v)) ref(v, p, e);+ else e.push(`${p}: expected a string, a finite number, null or a ref`);+};++const row: Check = (v, p, e) => {+ if (!isRec(v)) {+ e.push(`${p}: expected an object`);+ return;+ }+ for (const key of Object.keys(v)) cell(v[key], `${p}.${key}`, e);+};++/** Column keys of a table data object, or null when its columns are unreadable. */+export function columnKeys(data: unknown): string[] | null {+ if (!isRec(data) || !Array.isArray(data.columns)) return null;+ return data.columns.map((c) => (isRec(c) ? c.key : undefined)).filter((k): k is string => typeof k === "string");+}++export const TABLE_DATA_SPEC: Spec<ViewTableData> = {+ required: {+ columns: list(obj(COLUMN_SPEC), VIEW_LIMITS.columns),+ rows: list(row, VIEW_LIMITS.rows),+ total_rows: count,+ truncated: bool,+ },+ optional: {},+};++/** Rules across the fields of table data: row keys, totals, truncation. */+export function tableDataRules(v: Rec, p: string, e: string[]): void {+ const keys = columnKeys(v) ?? [];+ if (Array.isArray(v.columns) && v.columns.length === 0) e.push(`${p}.columns: at least one column`);+ for (const key of duplicates(keys)) e.push(`${p}.columns: duplicate key ${String(key)}`);+ if (!Array.isArray(v.rows)) return;+ const known = new Set(keys);+ v.rows.forEach((r, i) => {+ if (!isRec(r)) return;+ for (const key of known) if (!Object.hasOwn(r, key)) e.push(`${p}.rows[${i}].${key}: required`);+ for (const key of Object.keys(r)) {+ if (!known.has(key)) e.push(`${p}.rows[${i}].${key}: unknown column`);+ }+ });+ if (Number.isInteger(v.total_rows) && typeof v.truncated === "boolean") {+ const total = v.total_rows as number;+ if (total < v.rows.length) e.push(`${p}.total_rows: fewer than the rows given`);+ else if (v.truncated !== total > v.rows.length) {+ e.push(`${p}.truncated: must be true exactly when total_rows exceeds the rows given`);+ }+ }+}++export const tableData = obj(TABLE_DATA_SPEC, tableDataRules);++const base = baseSpec("table");+export const TABLE_SPEC: Spec<TableView> = {+ required: { ...base.required, ...PROVENANCE_SPEC.required, ...TABLE_DATA_SPEC.required },+ optional: { ...base.optional, ...PROVENANCE_SPEC.optional },+};++export const TABLE_KIND: ViewKindEntry<"table"> = {+ check: obj(TABLE_SPEC, tableDataRules),+ isData: true,+};diff --git a/packages/server/src/repowise/server/schemas/__init__.py b/packages/server/src/repowise/server/schemas/__init__.pyindex 3ed7f6773..7a26403fa 100644--- a/packages/server/src/repowise/server/schemas/__init__.py+++ b/packages/server/src/repowise/server/schemas/__init__.py@@ -124,6 +124,7 @@ if TYPE_CHECKING:EpisodeListResponse,EpisodeSummary,)+ from .evidence import CardBasis, CardReffrom .external_systems import (ExternalSystemEntry,ExternalSystemsResponse,@@ -288,6 +289,7 @@ if TYPE_CHECKING:SetApiKeyRequest,WebhookResponse,)+ from .views import ChartView, SectionView, TableView, ViewPartListfrom .workspace import (WorkspaceArchitectureResponse,WorkspaceBlastRadiusResponse,@@ -441,6 +443,7 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"DocDriftSummaryResponse",),"episodes": ("EpisodeCountsResponse", "EpisodeDetail", "EpisodeListResponse", "EpisodeSummary"),+ "evidence": ("CardBasis", "CardRef"),"external_systems": ("ExternalSystemEntry", "ExternalSystemsResponse"),"git": ("AgentTrendBucket",@@ -623,6 +626,7 @@ _EXPORTS: dict[str, tuple[str, ...]] = {"WorkspaceUnmatchedConsumer","WorkspaceUnresolvedLink",),+ "views": ("ChartView", "SectionView", "TableView", "ViewPartList"),"zoom": ("ZoomMapResponse", "ZoomMetricsResponse", "ZoomNodeResponse", "ZoomRelationResponse"),}@@ -671,10 +675,13 @@ __all__ = ["C4SystemResponse","CallerCalleeEntry","CallersCalleesResponse",+ "CardBasis",+ "CardRef","ChangeFeaturesResponse","ChangelogEntryModel","ChangelogResponse","ChangelogSectionModel",+ "ChartView","ChatArtifactEnvelope","ChatMessageResponse","ChatRequest",@@ -861,6 +868,7 @@ __all__ = ["SavingsResponse","SearchRequest","SearchResultResponse",+ "SectionView","SecurityFindingResponse","SecuritySummaryResponse","SetActiveProviderRequest",@@ -868,10 +876,12 @@ __all__ = ["SymbolImportanceComponents","SymbolNodeSummary","SymbolResponse",+ "TableView","TransitiveEntry","UnclusteredFiles","UpdateMcpToolsRequest","VersionResponse",+ "ViewPartList","WebhookResponse","WorkspaceArchitectureResponse","WorkspaceBlastRadiusResponse",diff --git a/packages/server/src/repowise/server/schemas/evidence.py b/packages/server/src/repowise/server/schemas/evidence.pynew file mode 100644index 000000000..75790324a--- /dev/null+++ b/packages/server/src/repowise/server/schemas/evidence.py@@ -0,0 +1,77 @@+"""Evidence primitives shared by renderer-neutral contracts.++Twin of ``packages/types/src/evidence.ts`` (how a value is known, and which+entity it points at), validated as strictly as the TypeScript validator in+``@repowise-dev/api-client``: unknown fields, coerced types, non-finite+numbers and an optional field sent as null are all rejected, so a payload+either side accepts the other accepts too.++Numbers are bounded by ``MAX_WIRE_NUMBER`` (2^53 - 1), the largest integer a+JavaScript reader keeps exact. Integer fields are sent as JSON integers: strict+mode rejects ``5.0`` and ``1e3`` there, which a JavaScript reader cannot tell+apart from ``5`` and ``1000``.+"""++from __future__ import annotations++from typing import Annotated, Any, Literal, get_args++from pydantic import BaseModel, ConfigDict, Field, model_validator++MAX_WIRE_NUMBER = 2**53 - 1+WireInt = Annotated[int, Field(ge=-MAX_WIRE_NUMBER, le=MAX_WIRE_NUMBER)]+WireFloat = Annotated[float, Field(ge=-MAX_WIRE_NUMBER, le=MAX_WIRE_NUMBER)]+++class StrictContract(BaseModel):+ """A wire contract shared with TypeScript: strict, closed, absent over null."""++ model_config = ConfigDict(extra="forbid", strict=True, allow_inf_nan=False)++ @model_validator(mode="before")+ @classmethod+ def _optional_means_absent(cls, data: Any) -> Any:+ # TypeScript optional fields are absent, never null.+ if isinstance(data, dict):+ for name, field in cls.model_fields.items():+ if not field.is_required() and name in data and data[name] is None:+ raise ValueError(f"{name}: omit an optional field rather than send null")+ return data+++CardBasisKind = Literal["measured", "inferred", "declared", "unresolved"]+CARD_BASIS_KINDS: tuple[str, ...] = get_args(CardBasisKind)++CardRefType = Literal[+ "repo", "file", "symbol", "module", "component", "commit", "change", "decision"+]+CARD_REF_TYPES: tuple[str, ...] = get_args(CardRefType)+++class CardBasis(StrictContract):+ kind: CardBasisKind+ source: str = Field(min_length=1)+++class CardRef(StrictContract):+ """An entity a card or view points at. Never a URL; the renderer resolves it."""++ type: CardRefType+ id: str = Field(min_length=1)+ start_line: int | None = Field(default=None, ge=1, le=MAX_WIRE_NUMBER)+ end_line: int | None = Field(default=None, ge=1, le=MAX_WIRE_NUMBER)++ @model_validator(mode="after")+ def _line_rules(self) -> CardRef:+ has_lines = self.start_line is not None or self.end_line is not None+ if has_lines and self.type not in ("file", "symbol"):+ raise ValueError("line numbers only apply to file and symbol refs")+ if self.end_line is not None and self.start_line is None:+ raise ValueError("end_line requires start_line")+ if (+ self.start_line is not None+ and self.end_line is not None+ and self.end_line < self.start_line+ ):+ raise ValueError("end_line is before start_line")+ return selfdiff --git a/packages/server/src/repowise/server/schemas/views.py b/packages/server/src/repowise/server/schemas/views.pynew file mode 100644index 000000000..f413ea2ce--- /dev/null+++ b/packages/server/src/repowise/server/schemas/views.py@@ -0,0 +1,274 @@+"""Chat view parts: tables, charts and report sections.++Twin of ``packages/types/src/views.ts``; read that module for what each field+means. View builders produce these from tool results already in a chat turn,+so every data part names its source result, basis, coverage and index commit.++``ViewPart`` is the kind registry: a discriminated union with one model per+kind, from which ``VIEW_MODELS`` and ``VIEW_KINDS`` are derived. Each model+declares ``is_data`` (true for kinds with provenance) and ``references()``+(ids of data parts it names); ``ViewPartList`` only iterates those. A new kind+is one model plus one union line here, and its cases in+``packages/types/fixtures/views.conformance.json``, which both this module's+tests and the TypeScript validator's run.+"""++from __future__ import annotations++from collections import Counter+from itertools import pairwise+from typing import Annotated, ClassVar, Literal, get_args++from pydantic import Field, RootModel, field_validator, model_validator++from repowise.server.schemas.evidence import (+ MAX_WIRE_NUMBER,+ CardBasis,+ CardRef,+ StrictContract,+ WireFloat,+ WireInt,+)++VIEW_SCHEMA_VERSION = 1++ChartType = Literal["bar", "stacked_bar", "line", "donut"]+CHART_TYPES: tuple[str, ...] = get_args(ChartType)++ViewCoverageMetric = Literal["attribution", "test_reach"]+VIEW_COVERAGE_METRICS: tuple[str, ...] = get_args(ViewCoverageMetric)++ChartSortOrder = Literal["asc", "desc"]+CHART_SORT_ORDERS: tuple[str, ...] = get_args(ChartSortOrder)++#: Size caps; a payload over any of them is rejected, not cut.+VIEW_LIMITS: dict[str, int] = {+ "parts": 50,+ "columns": 20,+ "rows": 500,+ "chart_points": 100,+ "chart_series": 8,+ "donut_min_parts": 2,+ "donut_max_parts": 5,+ "narrative_blocks": 50,+ "section_views": 20,+}++NonEmpty = Annotated[str, Field(min_length=1)]+PartId = Annotated[str, Field(pattern=r"^[A-Za-z0-9][A-Za-z0-9_.:-]{0,63}$")]+ViewCell = str | WireInt | WireFloat | CardRef | None+++def _duplicates(items: list[str]) -> list[str]:+ return sorted(item for item, n in Counter(items).items() if n > 1)+++class ViewSource(StrictContract):+ artifact_id: NonEmpty+ tool_name: NonEmpty+ args_hash: str = Field(pattern=r"^[0-9a-f]{8,128}$")+++class ViewCoverage(StrictContract):+ metric: ViewCoverageMetric+ ratio: float = Field(ge=0, le=1)+++class ViewPartBase(StrictContract):+ #: Data parts carry provenance and are what other parts may name.+ is_data: ClassVar[bool] = False++ schema_version: Literal[1]+ id: PartId+ title: NonEmpty+ summary: NonEmpty | None = None++ @field_validator("schema_version", mode="before")+ @classmethod+ def _not_a_bool(cls, value: object) -> object:+ # Literal[1] alone accepts True, which the TypeScript side rejects.+ if isinstance(value, bool):+ raise ValueError(f"expected {VIEW_SCHEMA_VERSION}")+ return value++ def references(self) -> list[str]:+ """Ids of data parts this part names; each must be in the same list."""+ return []+++class ViewProvenance(StrictContract):+ is_data: ClassVar[bool] = True++ source: ViewSource+ basis: CardBasis+ coverage: ViewCoverage | None = None+ stale: bool+ as_of: Annotated[str, Field(pattern=r"^[0-9a-f]{7,64}$")] | None+++class ViewColumn(StrictContract):+ key: str = Field(pattern=r"^[a-z][a-z0-9_]{0,63}$")+ label: NonEmpty+ unit: NonEmpty | None = None+ basis: CardBasis | None = None+++class ViewTableData(StrictContract):+ columns: list[ViewColumn] = Field(max_length=VIEW_LIMITS["columns"])+ rows: list[dict[str, ViewCell]] = Field(max_length=VIEW_LIMITS["rows"])+ total_rows: int = Field(ge=0, le=MAX_WIRE_NUMBER)+ truncated: bool++ @model_validator(mode="after")+ def _table_rules(self) -> ViewTableData:+ keys = [c.key for c in self.columns]+ if not keys:+ raise ValueError("a table needs at least one column")+ if dupes := _duplicates(keys):+ raise ValueError(f"duplicate column keys: {dupes}")+ known = set(keys)+ for i, row in enumerate(self.rows):+ if set(row) != known:+ raise ValueError(f"rows[{i}] keys differ from the column keys")+ if self.total_rows < len(self.rows):+ raise ValueError("total_rows is fewer than the rows given")+ if self.truncated != (self.total_rows > len(self.rows)):+ raise ValueError("truncated must be true exactly when total_rows exceeds the rows")+ return self+++class TableView(ViewTableData, ViewProvenance, ViewPartBase):+ kind: Literal["table"]+++_SERIES_BOUNDS: dict[str, tuple[int, int]] = {+ "bar": (1, VIEW_LIMITS["chart_series"]),+ "line": (1, VIEW_LIMITS["chart_series"]),+ "stacked_bar": (2, VIEW_LIMITS["chart_series"]),+ "donut": (1, 1),+}+_PARTS_OF_A_WHOLE = frozenset({"stacked_bar", "donut"})+++class ChartView(ViewProvenance, ViewPartBase):+ """A chart over its own table; see ``ChartView`` in views.ts for the rules."""++ kind: Literal["chart"]+ chart_type: ChartType+ data: ViewTableData+ x: NonEmpty+ series: list[NonEmpty] = Field(max_length=VIEW_LIMITS["chart_series"])+ sort: ChartSortOrder | None = None+ summary: NonEmpty++ @model_validator(mode="after")+ def _chart_rules(self) -> ChartView:+ columns = {c.key: c for c in self.data.columns}+ rows = self.data.rows+ kind = self.chart_type+ if self.x not in columns:+ raise ValueError("x is not a column of data")+ for s in self.series:+ if s not in columns:+ raise ValueError(f"series {s!r} is not a column of data")+ if s == self.x:+ raise ValueError(f"series {s!r} is the x column")+ if _duplicates(self.series):+ raise ValueError("series repeats a column")+ low, high = _SERIES_BOUNDS[kind]+ if not low <= len(self.series) <= high:+ raise ValueError(f"a {kind} chart plots {low} to {high} series")+ if len(rows) > VIEW_LIMITS["chart_points"]:+ raise ValueError(f"a chart plots at most {VIEW_LIMITS['chart_points']} rows")+ if len({columns[s].unit for s in self.series}) > 1:+ raise ValueError("plotted columns must share one unit")+ total: float = 0+ for i, row in enumerate(rows):+ if row[self.x] is None:+ raise ValueError(f"rows[{i}]: x is null")+ for s in self.series:+ cell = row[s]+ if cell is None:+ if kind == "donut":+ raise ValueError(f"rows[{i}].{s}: a donut part is null")+ if self.sort is not None:+ raise ValueError(f"rows[{i}].{s}: a sorted chart has no nulls")+ elif not isinstance(cell, (int, float)):+ raise ValueError(f"rows[{i}].{s}: plotted values must be numbers")+ elif cell < 0 and kind in _PARTS_OF_A_WHOLE:+ raise ValueError(f"rows[{i}].{s}: a {kind} value cannot be negative")+ else:+ total += cell+ if kind in _PARTS_OF_A_WHOLE and rows and total <= 0:+ raise ValueError(f"a {kind} needs a positive total")+ if kind == "donut":+ low, high = VIEW_LIMITS["donut_min_parts"], VIEW_LIMITS["donut_max_parts"]+ if not low <= len(rows) <= high:+ raise ValueError(f"a donut has {low} to {high} parts")+ if self.data.truncated:+ raise ValueError("a donut must show the whole")+ if self.sort is not None:+ totals = [_row_total(row, self.series) for row in rows]+ sign = 1 if self.sort == "asc" else -1+ if any(sign * (b - a) < 0 for a, b in pairwise(totals)):+ raise ValueError(f"rows are not in {self.sort} order of their series total")+ return self+++def _row_total(row: dict[str, ViewCell], series: list[str]) -> float:+ """A row's numeric series values summed in series order, as the TypeScript side sums."""+ total: float = 0+ for s in series:+ cell = row[s]+ if isinstance(cell, (int, float)):+ total += cell+ return total+++class NarrativeBlock(StrictContract):+ text: NonEmpty+ cites: list[PartId] = Field(max_length=VIEW_LIMITS["parts"])+++class SectionView(ViewPartBase):+ kind: Literal["section"]+ narrative: list[NarrativeBlock] = Field(max_length=VIEW_LIMITS["narrative_blocks"])+ view_ids: list[PartId] = Field(max_length=VIEW_LIMITS["section_views"])++ @model_validator(mode="after")+ def _section_rules(self) -> SectionView:+ if not self.narrative and not self.view_ids:+ raise ValueError("a section needs narrative or views")+ if _duplicates(self.view_ids):+ raise ValueError("view_ids repeats a part")+ return self++ def references(self) -> list[str]:+ return [*self.view_ids, *(cite for block in self.narrative for cite in block.cites)]+++# The kind registry. A new kind is one model added here.+ViewPart = Annotated[TableView | ChartView | SectionView, Field(discriminator="kind")]++VIEW_MODELS: tuple[type[ViewPartBase], ...] = get_args(get_args(ViewPart)[0])+VIEW_KINDS: tuple[str, ...] = tuple(+ get_args(model.model_fields["kind"].annotation)[0] for model in VIEW_MODELS+)+++class ViewPartList(RootModel[list[ViewPart]]):+ """The parts of one turn or report: unique ids, and every id a part names+ is a data part in the same list."""++ root: list[ViewPart] = Field(max_length=VIEW_LIMITS["parts"])++ @model_validator(mode="after")+ def _references_resolve(self) -> ViewPartList:+ if dupes := _duplicates([part.id for part in self.root]):+ raise ValueError(f"duplicate part ids: {dupes}")+ data_ids = {part.id for part in self.root if part.is_data}+ for part in self.root:+ missing = [ref for ref in dict.fromkeys(part.references()) if ref not in data_ids]+ if missing:+ raise ValueError(f"part {part.id!r} names no data part: {missing}")+ return selfdiff --git a/packages/types/fixtures/views.conformance.json b/packages/types/fixtures/views.conformance.jsonnew file mode 100644index 000000000..cc2517dfb--- /dev/null+++ b/packages/types/fixtures/views.conformance.json@@ -0,0 +1,264 @@+{+ "about": "Shared conformance cases for chat view parts. The TypeScript validator (packages/api-client/src/views.test.ts) and the server models (tests/unit/server/test_view_parts_contract.py) both run every case, so they accept and reject the same payloads. An invalid case copies a valid part (from), then applies drop (paths), set (path to value) and grow (path to length, repeating the array's first item). Paths are dotted; numeric segments index arrays. error is the substring the TypeScript validator reports. valid_variants are accepted by both sides but not round-tripped (JSON writes -0 as 0). Strings have no maximum length, only non-empty, so UTF-16 units and code points agree; ids and column keys are ASCII patterns. Numbers stay within +/-(2^53 - 1).",+ "vocabulary": {+ "schema_version": 1,+ "max_wire_number": 9007199254740991,+ "view_kinds": ["table", "chart", "section"],+ "chart_types": ["bar", "stacked_bar", "line", "donut"],+ "coverage_metrics": ["attribution", "test_reach"],+ "sort_orders": ["asc", "desc"],+ "basis_kinds": ["measured", "inferred", "declared", "unresolved"],+ "ref_types": ["repo", "file", "symbol", "module", "component", "commit", "change", "decision"]+ },+ "limits": {+ "parts": 50,+ "columns": 20,+ "rows": 500,+ "chart_points": 100,+ "chart_series": 8,+ "donut_min_parts": 2,+ "donut_max_parts": 5,+ "narrative_blocks": 50,+ "section_views": 20+ },+ "fields": {+ "CardBasis": ["kind", "source"],+ "CardRef": ["type", "id", "start_line", "end_line"],+ "ViewSource": ["artifact_id", "tool_name", "args_hash"],+ "ViewCoverage": ["metric", "ratio"],+ "ViewColumn": ["key", "label", "unit", "basis"],+ "ViewTableData": ["columns", "rows", "total_rows", "truncated"],+ "NarrativeBlock": ["text", "cites"],+ "TableView": ["schema_version", "kind", "id", "title", "summary", "source", "basis", "coverage", "stale", "as_of", "columns", "rows", "total_rows", "truncated"],+ "ChartView": ["schema_version", "kind", "id", "title", "summary", "source", "basis", "coverage", "stale", "as_of", "chart_type", "data", "x", "series", "sort"],+ "SectionView": ["schema_version", "kind", "id", "title", "summary", "narrative", "view_ids"]+ },+ "valid": {+ "t1": {+ "schema_version": 1,+ "kind": "table",+ "id": "t1",+ "title": "Hotspots",+ "summary": "Two of three hotspots shown.",+ "source": { "artifact_id": "a1", "tool_name": "get_health", "args_hash": "3f2a9c1b7d4e5f60" },+ "basis": { "kind": "measured", "source": "git history" },+ "coverage": { "metric": "test_reach", "ratio": 0.75 },+ "stale": false,+ "as_of": "4c1e31f",+ "columns": [+ { "key": "path", "label": "File" },+ { "key": "churn", "label": "Commits, 90 days", "unit": "commits" },+ { "key": "health", "label": "Health", "unit": "score", "basis": { "kind": "inferred", "source": "health engine" } }+ ],+ "rows": [+ { "path": { "type": "file", "id": "auth/session.py" }, "churn": 41, "health": 4.2 },+ { "path": { "type": "file", "id": "billing/invoice.py", "start_line": 10, "end_line": 42 }, "churn": 17, "health": null }+ ],+ "total_rows": 3,+ "truncated": true+ },+ "c1": {+ "schema_version": 1,+ "kind": "chart",+ "id": "c1",+ "title": "Changes by component",+ "summary": "Payments changed most this month.",+ "source": { "artifact_id": "a2", "tool_name": "get_overview", "args_hash": "0011aabbccddeeff" },+ "basis": { "kind": "measured", "source": "git history" },+ "stale": false,+ "as_of": "4c1e31f",+ "chart_type": "bar",+ "data": {+ "columns": [+ { "key": "component", "label": "Component" },+ { "key": "changes", "label": "Changes", "unit": "changes" }+ ],+ "rows": [+ { "component": { "type": "component", "id": "payments" }, "changes": 12 },+ { "component": "auth", "changes": 7 },+ { "component": "search", "changes": 3 }+ ],+ "total_rows": 3,+ "truncated": false+ },+ "x": "component",+ "series": ["changes"],+ "sort": "desc"+ },+ "c2": {+ "schema_version": 1,+ "kind": "chart",+ "id": "c2",+ "title": "Test reach by component",+ "summary": "Auth has more inferred than measured reach.",+ "source": { "artifact_id": "a3", "tool_name": "get_risk", "args_hash": "deadbeef" },+ "basis": { "kind": "measured", "source": "coverage report" },+ "coverage": { "metric": "test_reach", "ratio": 0.62 },+ "stale": false,+ "as_of": "4c1e31f2a9b8c7d6e5f4a3b2c1d0e9f8a7b6c5d4",+ "chart_type": "stacked_bar",+ "data": {+ "columns": [+ { "key": "component", "label": "Component" },+ { "key": "measured", "label": "Measured", "unit": "files" },+ { "key": "inferred", "label": "Inferred", "unit": "files", "basis": { "kind": "inferred", "source": "import graph" } }+ ],+ "rows": [+ { "component": "payments", "measured": 4, "inferred": 2 },+ { "component": "auth", "measured": 3, "inferred": 5 }+ ],+ "total_rows": 2,+ "truncated": false+ },+ "x": "component",+ "series": ["measured", "inferred"],+ "sort": "asc"+ },+ "c3": {+ "schema_version": 1,+ "kind": "chart",+ "id": "c3",+ "title": "Commits per week",+ "summary": "Commit volume peaked in week 40.",+ "source": { "artifact_id": "a4", "tool_name": "get_overview", "args_hash": "abcdef0123456789" },+ "basis": { "kind": "measured", "source": "git history" },+ "stale": true,+ "as_of": null,+ "chart_type": "line",+ "data": {+ "columns": [+ { "key": "week", "label": "Week" },+ { "key": "commits", "label": "Commits", "unit": "commits" }+ ],+ "rows": [+ { "week": "2026-W39", "commits": 10 },+ { "week": "2026-W40", "commits": 14.5 },+ { "week": "2026-W41", "commits": null }+ ],+ "total_rows": 3,+ "truncated": false+ },+ "x": "week",+ "series": ["commits"]+ },+ "c4": {+ "schema_version": 1,+ "kind": "chart",+ "id": "c4",+ "title": "Dead code by tier",+ "summary": "Most findings are low confidence.",+ "source": { "artifact_id": "a5", "tool_name": "get_dead_code", "args_hash": "0123abcd" },+ "basis": { "kind": "inferred", "source": "reachability graph" },+ "stale": false,+ "as_of": "4c1e31f",+ "chart_type": "donut",+ "data": {+ "columns": [+ { "key": "tier", "label": "Tier" },+ { "key": "files", "label": "Files", "unit": "files" }+ ],+ "rows": [+ { "tier": "high", "files": 12 },+ { "tier": "medium", "files": 30 },+ { "tier": "low", "files": 0 }+ ],+ "total_rows": 3,+ "truncated": false+ },+ "x": "tier",+ "series": ["files"]+ },+ "s1": {+ "schema_version": 1,+ "kind": "section",+ "id": "s1",+ "title": "Where change concentrates",+ "summary": "Payments leads on change volume.",+ "narrative": [+ { "text": "Payments had the most changes this month.", "cites": ["c1"] },+ { "text": "The table lists the files behind it.", "cites": [] }+ ],+ "view_ids": ["t1", "c1"]+ }+ },+ "invalid": [+ { "name": "unknown kind", "from": "t1", "set": { "kind": "pie" }, "error": "view.kind" },+ { "name": "missing kind", "from": "t1", "drop": ["kind"], "error": "view.kind" },+ { "name": "wrong schema version", "from": "t1", "set": { "schema_version": 2 }, "error": "view.schema_version" },+ { "name": "boolean schema version", "from": "s1", "set": { "schema_version": true }, "error": "view.schema_version" },+ { "name": "missing source", "from": "t1", "drop": ["source"], "error": "view.source: required" },+ { "name": "missing basis", "from": "c1", "drop": ["basis"], "error": "view.basis: required" },+ { "name": "source without args hash", "from": "t1", "drop": ["source.args_hash"], "error": "view.source.args_hash: required" },+ { "name": "args hash not hex", "from": "t1", "set": { "source.args_hash": "XYZ" }, "error": "view.source.args_hash" },+ { "name": "unknown basis kind", "from": "t1", "set": { "basis.kind": "guessed" }, "error": "view.basis.kind" },+ { "name": "person field", "from": "t1", "set": { "author": "[email protected]" }, "error": "view.author: unknown field" },+ { "name": "person field on a column", "from": "t1", "set": { "columns.0.owner": "someone" }, "error": "view.columns[0].owner: unknown field" },+ { "name": "optional field sent as null", "from": "t1", "set": { "summary": null }, "error": "view.summary" },+ { "name": "as_of not a sha", "from": "t1", "set": { "as_of": "HEAD" }, "error": "view.as_of" },+ { "name": "as_of missing", "from": "t1", "drop": ["as_of"], "error": "view.as_of: required" },+ { "name": "stale not a boolean", "from": "t1", "set": { "stale": "no" }, "error": "view.stale" },+ { "name": "coverage above one", "from": "t1", "set": { "coverage.ratio": 1.5 }, "error": "view.coverage.ratio" },+ { "name": "unknown coverage metric", "from": "t1", "set": { "coverage.metric": "ownership" }, "error": "view.coverage.metric" },+ { "name": "bad part id", "from": "t1", "set": { "id": "has space" }, "error": "view.id" },+ { "name": "bad column key", "from": "t1", "set": { "columns.0.key": "Path Name" }, "error": "view.columns[0].key" },+ { "name": "row missing a column", "from": "t1", "drop": ["rows.0.churn"], "error": "view.rows[0].churn: required" },+ { "name": "row with an extra column", "from": "t1", "set": { "rows.0.author": "x" }, "error": "view.rows[0].author: unknown column" },+ { "name": "boolean cell", "from": "t1", "set": { "rows.0.churn": true }, "error": "view.rows[0].churn" },+ { "name": "object cell that is not a ref", "from": "t1", "set": { "rows.0.path": { "url": "https://example.com" } }, "error": "view.rows[0].path" },+ { "name": "ref cell with lines on a commit", "from": "t1", "set": { "rows.0.path": { "type": "commit", "id": "abc1234", "start_line": 1 } }, "error": "line numbers only apply" },+ { "name": "duplicate column key", "from": "t1", "set": { "columns.1.key": "path" }, "error": "duplicate key path" },+ { "name": "no columns", "from": "t1", "set": { "columns": [], "rows": [], "total_rows": 0, "truncated": false }, "error": "at least one column" },+ { "name": "truncated that does not match the totals", "from": "t1", "set": { "truncated": false }, "error": "view.truncated" },+ { "name": "total below the rows given", "from": "t1", "set": { "total_rows": 1 }, "error": "view.total_rows" },+ { "name": "rows over the cap", "from": "t1", "grow": { "rows": 501 }, "set": { "total_rows": 501, "truncated": false }, "error": "view.rows: more than 500 items" },+ { "name": "columns over the cap", "from": "t1", "grow": { "columns": 21 }, "error": "view.columns: more than 20 items" },+ { "name": "series naming a missing column", "from": "c1", "set": { "series": ["nope"] }, "error": "view.series[0]: not a column of data" },+ { "name": "x naming a missing column", "from": "c1", "set": { "x": "nope" }, "error": "view.x: not a column of data" },+ { "name": "series that is the x column", "from": "c1", "set": { "series": ["component"] }, "error": "is the x column" },+ { "name": "stacked bar with one series", "from": "c2", "set": { "series": ["measured"] }, "error": "a stacked_bar chart plots 2 to 8 series" },+ { "name": "series over the cap", "from": "c1", "set": { "series": ["a", "b", "c", "d", "e", "f", "g", "h", "i"] }, "error": "view.series: more than 8 items" },+ { "name": "unknown chart type", "from": "c1", "set": { "chart_type": "pie" }, "error": "view.chart_type" },+ { "name": "chart without a summary", "from": "c1", "drop": ["summary"], "error": "view.summary: required" },+ { "name": "string plotted as a value", "from": "c1", "set": { "data.rows.0.changes": "12" }, "error": "plotted values must be numbers" },+ { "name": "null x value", "from": "c1", "set": { "data.rows.0.component": null }, "error": "x is null" },+ { "name": "sort that the rows contradict", "from": "c1", "set": { "sort": "asc" }, "error": "view.sort: rows are not in asc order" },+ { "name": "negative stacked value", "from": "c2", "set": { "data.rows.0.measured": -1 }, "error": "cannot be negative" },+ { "name": "series in different units", "from": "c2", "set": { "data.columns.2.unit": "lines" }, "error": "share one unit" },+ { "name": "chart points over the cap", "from": "c3", "grow": { "data.rows": 101 }, "set": { "data.total_rows": 101 }, "error": "a chart plots at most 100 rows" },+ { "name": "donut with six parts", "from": "c4", "grow": { "data.rows": 6 }, "set": { "data.total_rows": 6 }, "error": "a donut has 2 to 5 parts" },+ { "name": "donut over truncated data", "from": "c4", "set": { "data.total_rows": 10, "data.truncated": true }, "error": "a donut must show the whole" },+ { "name": "donut with a null part", "from": "c4", "set": { "data.rows.0.files": null }, "error": "a donut part is null" },+ { "name": "empty section", "from": "s1", "set": { "narrative": [], "view_ids": [] }, "error": "a section needs narrative or views" },+ { "name": "section repeating a view", "from": "s1", "set": { "view_ids": ["t1", "t1"] }, "error": "view.view_ids: duplicate t1" },+ { "name": "citation that is not a part id", "from": "s1", "set": { "narrative.0.cites": ["bad id"] }, "error": "view.narrative[0].cites[0]" },+ { "name": "section carrying provenance", "from": "s1", "set": { "stale": false }, "error": "view.stale: unknown field" },+ {"name": "as_of an impossible date", "from": "t1", "set": {"as_of": "2026-02-30T09:30:00Z"}, "error": "view.as_of"},+ {"name": "args hash with a trailing newline", "from": "t1", "set": {"source.args_hash": "3f2a9c1b7d4e5f60\n"}, "error": "view.source.args_hash"},+ {"name": "id with a non-BMP character", "from": "t1", "set": {"id": "t😀"}, "error": "view.id"},+ {"name": "cell beyond 2^53 - 1", "from": "t1", "set": {"rows.0.churn": 9007199254740992}, "error": "view.rows[0].churn"},+ {"name": "total_rows beyond 2^53 - 1", "from": "t1", "set": {"total_rows": 9007199254740992}, "error": "view.total_rows"},+ {"name": "line number beyond 2^53 - 1", "from": "t1", "set": {"rows.1.path.end_line": 9007199254740992}, "error": "view.rows[1].path.end_line"},+ {"name": "null in a sorted series", "from": "c1", "set": {"data.rows.2.changes": null}, "error": "a sorted chart has no nulls"},+ {"name": "donut with a zero total", "from": "c4", "set": {"data.rows.0.files": 0, "data.rows.1.files": 0}, "error": "a donut needs a positive total"},+ {"name": "stacked bar of all zeros", "from": "c2", "set": {"data.rows.0.measured": 0, "data.rows.0.inferred": 0, "data.rows.1.measured": 0, "data.rows.1.inferred": 0}, "error": "a stacked_bar needs a positive total"}+ ],+ "valid_variants": [+ { "name": "non-BMP title and summary", "from": "t1", "set": { "title": "😀", "summary": "Payments 💳 leads" } },+ { "name": "negative zero in a line", "from": "c3", "set": { "data.rows.0.commits": -0 } },+ { "name": "negative zero donut part", "from": "c4", "set": { "data.rows.2.files": -0.0 } },+ { "name": "largest wire integer", "from": "t1", "set": { "rows.0.churn": 9007199254740991, "rows.1.path.end_line": 9007199254740991 } },+ { "name": "smallest wire integer", "from": "c3", "set": { "data.rows.0.commits": -9007199254740991 } },+ { "name": "line chart with a null and no sort", "from": "c3", "set": { "data.rows.0.commits": null } }+ ],+ "valid_lists": [+ { "name": "every valid part together", "items": [{ "from": "t1" }, { "from": "c1" }, { "from": "c2" }, { "from": "c3" }, { "from": "c4" }, { "from": "s1" }] },+ { "name": "no parts", "items": [] }+ ],+ "invalid_lists": [+ { "name": "duplicate ids", "items": [{ "from": "t1" }, { "from": "c1", "set": { "id": "t1" } }], "error": "views: duplicate id t1" },+ { "name": "section naming a part not in the list", "items": [{ "from": "t1" }, { "from": "s1" }], "error": "no data part with id c1" },+ { "name": "section naming a section", "items": [{ "from": "t1" }, { "from": "c1" }, { "from": "s1" }, { "from": "s1", "set": { "id": "s2", "view_ids": ["s1"], "narrative": [] } }], "error": "views[3].view_ids[0]: no data part with id s1" },+ { "name": "an invalid part", "items": [{ "from": "t1", "set": { "kind": "pie" } }], "error": "views[0].kind" },+ { "name": "parts over the cap", "items": [{ "from": "t1" }], "repeat": 51, "error": "views: more than 50 items" }+ ]+}diff --git a/packages/types/package.json b/packages/types/package.jsonindex 043bd8902..2727dfa8f 100644--- a/packages/types/package.json+++ b/packages/types/package.json@@ -19,6 +19,7 @@"./symbols": "./src/symbols.ts","./chat": "./src/chat.ts","./cards": "./src/cards.ts",+ "./views": "./src/views.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.tsindex d39f936f5..ca8ec4100 100644--- a/packages/types/src/cards.ts+++ b/packages/types/src/cards.ts@@ -12,6 +12,17 @@* validator in `@repowise-dev/api-client/cards` rejects unknown fields.*/+import type { CardBasis, CardRef } from "./evidence.js";++export {+ CARD_BASIS_KINDS,+ CARD_REF_TYPES,+ type CardBasis,+ type CardBasisKind,+ type CardRef,+ type CardRefType,+} from "./evidence.js";+export const EVIDENCE_CARD_SCHEMA_VERSION = 1 as const;export const EVIDENCE_CARD_KINDS = [@@ -24,42 +35,6 @@ export const EVIDENCE_CARD_KINDS = [] 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];diff --git a/packages/types/src/evidence.ts b/packages/types/src/evidence.tsnew file mode 100644index 000000000..af75ae512--- /dev/null+++ b/packages/types/src/evidence.ts@@ -0,0 +1,42 @@+/**+ * Evidence primitives shared by every renderer-neutral contract (evidence+ * cards, chat view parts): how a value is known, and which entity it points+ * at. Not a published subpath: reached through `@repowise-dev/types/cards`+ * (which re-exports them) and imported by `views.ts`.+ */++/**+ * 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 or view 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;+}diff --git a/packages/types/src/index.ts b/packages/types/src/index.tsindex 55489eacd..07dab22f5 100644--- a/packages/types/src/index.ts+++ b/packages/types/src/index.ts@@ -19,6 +19,7 @@ export * from "./doc-drift.js";export * from "./symbols.js";export * from "./chat.js";export * from "./cards.js";+export * from "./views.js";export * from "./workspace.js";export * from "./blast-radius.js";export * from "./risk-semantics.js";diff --git a/packages/types/src/views.ts b/packages/types/src/views.tsnew file mode 100644index 000000000..7e7686cfc--- /dev/null+++ b/packages/types/src/views.ts@@ -0,0 +1,157 @@+/**+ * Chat view parts: tables, charts and report sections a chat turn returns+ * next to its evidence cards.+ *+ * The model never writes a number into a view. A server-side builder makes+ * each table or chart from a tool result already in the turn, so every data+ * part names that result (`source`), says how its values are known (`basis`),+ * carries coverage when the tool reports one, and the index commit it was+ * read at (`as_of`). Like cards, parts are layout-free data that describe+ * changes and components, never people, and entities are refs, not URLs.+ *+ * A new kind is: its interface plus one `ViewPartsByKind` line here; its+ * module under `api-client/src/views/` plus one `VIEW_REGISTRY` line; its+ * model plus one `ViewPart` union line in `repowise.server.schemas.views`;+ * and its cases in `packages/types/fixtures/views.conformance.json`. Maps+ * keyed by `ViewKind` (validator, renderers) fail to compile until filled.+ * `schema_version` changes whenever a field is added or removed, because both+ * validators reject unknown fields.+ */++import type { CardBasis, CardRef } from "./evidence.js";++export const VIEW_SCHEMA_VERSION = 1 as const;++/** Chart forms. A new form is added with its builder, never as a general grammar. */+export const CHART_TYPES = ["bar", "stacked_bar", "line", "donut"] as const;+export type ChartType = (typeof CHART_TYPES)[number];++/** What a coverage ratio measures. */+export const VIEW_COVERAGE_METRICS = ["attribution", "test_reach"] as const;+export type ViewCoverageMetric = (typeof VIEW_COVERAGE_METRICS)[number];++export const CHART_SORT_ORDERS = ["asc", "desc"] as const;+export type ChartSortOrder = (typeof CHART_SORT_ORDERS)[number];++/**+ * Size caps; a payload over any of them is rejected, not cut. Strings have no+ * length cap beyond being non-empty; ids and column keys are ASCII patterns.+ */+export const VIEW_LIMITS = {+ /** Parts one turn or report may hold. */+ parts: 50,+ columns: 20,+ rows: 500,+ /** Rows a chart may plot. */+ chart_points: 100,+ chart_series: 8,+ /** Rows a donut needs at least and at most. */+ donut_min_parts: 2,+ donut_max_parts: 5,+ narrative_blocks: 50,+ section_views: 20,+} as const;++/** The tool result a part was built from. */+export interface ViewSource {+ /** The artifact id the turn assigned to the tool result. */+ artifact_id: string;+ tool_name: string;+ /** Lowercase hex digest of the tool's arguments. */+ args_hash: string;+}++/** Share of the underlying data the tool could account for. */+export interface ViewCoverage {+ metric: ViewCoverageMetric;+ /** 0 to 1. */+ ratio: number;+}++export interface ViewPartBase<K extends string> {+ schema_version: typeof VIEW_SCHEMA_VERSION;+ kind: K;+ /** Unique within one turn or report; sections and narrative cite parts by it. */+ id: string;+ /** Caption; a section's heading. */+ title: string;+ /** Plain text. */+ summary?: string;+}++/** Where a data part's values came from. Sections carry none of their own. */+export interface ViewProvenance {+ source: ViewSource;+ basis: CardBasis;+ coverage?: ViewCoverage;+ /** True when the tool reported its index as behind the code it read. */+ stale: boolean;+ /** Index commit the data was read at; null when the tool did not report one. */+ as_of: string | null;+}++export interface ViewColumn {+ /** Lowercase identifier; row objects are keyed by it. */+ key: string;+ label: string;+ unit?: string;+ /** Overrides the part's basis for this column. */+ basis?: CardBasis;+}++/**+ * One cell. A ref renders as a link to the entity; a number stays unformatted.+ * Every number on the wire is finite and within +/-(2^53 - 1), and integer+ * fields (`total_rows`, line numbers) are sent as JSON integers, never `5.0`.+ */+export type ViewCell = string | number | null | CardRef;++/** Rows keyed by column key; every row has exactly the columns' keys. */+export interface ViewTableData {+ columns: ViewColumn[];+ rows: Array<Record<string, ViewCell>>;+ /** Rows the source held; more than `rows.length` exactly when `truncated`. */+ total_rows: number;+ truncated: boolean;+}++export interface TableView extends ViewPartBase<"table">, ViewProvenance, ViewTableData {}++/**+ * A chart over its own table, which renderers also show as the data view.+ * `x` and every `series` entry are column keys; series values are numbers in+ * one shared unit. `sort` states the rows' order by the sum of their series+ * values (absent means source order) and is checked, not trusted.+ */+export interface ChartView extends ViewPartBase<"chart">, ViewProvenance {+ chart_type: ChartType;+ data: ViewTableData;+ x: string;+ series: string[];+ sort?: ChartSortOrder;+ /** Required: a chart always comes with its text summary. */+ summary: string;+}++/** One paragraph of report narrative and the parts its facts rest on. */+export interface NarrativeBlock {+ text: string;+ /** Ids of parts in the same turn or report. */+ cites: string[];+}++/** A report section: a heading, narrative, and the data parts it shows, in order. */+export interface SectionView extends ViewPartBase<"section"> {+ narrative: NarrativeBlock[];+ /** Ids of table or chart parts in the same turn or report. */+ view_ids: string[];+}++/** The kind registry: one entry per view kind. */+export interface ViewPartsByKind {+ table: TableView;+ chart: ChartView;+ section: SectionView;+}+export type ViewKind = keyof ViewPartsByKind;+export type ViewPart = ViewPartsByKind[ViewKind];diff --git a/packages/ui/vitest.config.ts b/packages/ui/vitest.config.tsindex 1b822eb05..cdf60ab42 100644--- a/packages/ui/vitest.config.ts+++ b/packages/ui/vitest.config.ts@@ -32,6 +32,7 @@ export default defineConfig({"@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/views": path.resolve(__dirname, "../types/src/views.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/tests/unit/server/test_view_parts_contract.py b/tests/unit/server/test_view_parts_contract.pynew file mode 100644index 000000000..a6b2178e4--- /dev/null+++ b/tests/unit/server/test_view_parts_contract.py@@ -0,0 +1,143 @@+"""The server's view part models accept and reject what the TypeScript validator does.++Both sides run ``packages/types/fixtures/views.conformance.json``; the+TypeScript half is ``packages/api-client/src/views.test.ts``. View parts are+not on an HTTP route yet, so ``scripts/generate_http_types.py`` cannot carry+them; this shared fixture is what keeps the two from drifting.+"""++from __future__ import annotations++import copy+import json+import math+from pathlib import Path+from typing import Any++import pytest+from pydantic import TypeAdapter, ValidationError++from repowise.server.schemas import evidence, views++_FIXTURE = (+ Path(__file__).resolve().parents[3] / "packages" / "types" / "fixtures" / "views.conformance.json"+)+FIXTURE: dict[str, Any] = json.loads(_FIXTURE.read_text(encoding="utf-8"))+PART = TypeAdapter(views.ViewPart)+++def _locate(root: Any, path: str) -> tuple[Any, Any]:+ *parents, last = path.split(".")+ node = root+ for key in parents:+ node = node[int(key)] if isinstance(node, list) else node[key]+ return node, int(last) if isinstance(node, list) else last+++def _derive(case: dict[str, Any]) -> dict[str, Any]:+ part = copy.deepcopy(FIXTURE["valid"][case["from"]])+ for path in case.get("drop", []):+ parent, key = _locate(part, path)+ del parent[key]+ for path, value in case.get("set", {}).items():+ parent, key = _locate(part, path)+ parent[key] = copy.deepcopy(value)+ for path, length in case.get("grow", {}).items():+ parent, key = _locate(part, path)+ parent[key] = [copy.deepcopy(parent[key][0]) for _ in range(length)]+ return part+++def test_the_vocabulary_and_limits_are_shared() -> None:+ assert {+ "schema_version": views.VIEW_SCHEMA_VERSION,+ "max_wire_number": evidence.MAX_WIRE_NUMBER,+ "view_kinds": list(views.VIEW_KINDS),+ "chart_types": list(views.CHART_TYPES),+ "coverage_metrics": list(views.VIEW_COVERAGE_METRICS),+ "sort_orders": list(views.CHART_SORT_ORDERS),+ "basis_kinds": list(evidence.CARD_BASIS_KINDS),+ "ref_types": list(evidence.CARD_REF_TYPES),+ } == FIXTURE["vocabulary"]+ assert FIXTURE["limits"] == views.VIEW_LIMITS++[email protected](("name", "fields"), sorted(FIXTURE["fields"].items()))+def test_each_model_has_exactly_the_shared_fields(name: str, fields: list[str]) -> None:+ model = getattr(views, name, None) or getattr(evidence, name)+ assert sorted(model.model_fields) == sorted(fields)+++def test_every_kind_has_a_valid_fixture() -> None:+ assert {part["kind"] for part in FIXTURE["valid"].values()} == set(views.VIEW_KINDS)++[email protected]("part_id", sorted(FIXTURE["valid"]))+def test_a_valid_part_is_accepted_and_round_trips(part_id: str) -> None:+ wire = FIXTURE["valid"][part_id]+ model = PART.validate_python(wire)+ assert PART.dump_python(model, mode="json", exclude_unset=True) == wire+ assert PART.validate_json(json.dumps(wire)) == model++[email protected]("case", FIXTURE["valid_variants"], ids=lambda c: c["name"])+def test_a_valid_variant_is_accepted(case: dict[str, Any]) -> None:+ PART.validate_python(_derive(case))+ PART.validate_json(json.dumps(_derive(case)))++[email protected]("case", FIXTURE["invalid"], ids=lambda c: c["name"])+def test_an_invalid_part_is_rejected(case: dict[str, Any]) -> None:+ with pytest.raises(ValidationError):+ PART.validate_python(_derive(case))++[email protected]("case", FIXTURE["valid_lists"], ids=lambda c: c["name"])+def test_a_valid_list_is_accepted(case: dict[str, Any]) -> None:+ items = [_derive(item) for item in case["items"]]+ assert len(views.ViewPartList.model_validate(items).root) == len(items)++[email protected]("case", FIXTURE["invalid_lists"], ids=lambda c: c["name"])+def test_an_invalid_list_is_rejected(case: dict[str, Any]) -> None:+ items = [_derive(item) for item in case["items"]]+ if "repeat" in case:+ items = [items[0]] * case["repeat"]+ with pytest.raises(ValidationError):+ views.ViewPartList.model_validate(items)++[email protected]("bad", [math.nan, math.inf])+def test_non_finite_numbers_are_rejected(bad: float) -> None:+ """JSON cannot carry these, so they are not in the shared fixture."""+ table = copy.deepcopy(FIXTURE["valid"]["t1"])+ table["rows"][0]["churn"] = bad+ with pytest.raises(ValidationError):+ PART.validate_python(table)+ table = copy.deepcopy(FIXTURE["valid"]["t1"])+ table["coverage"]["ratio"] = bad+ with pytest.raises(ValidationError):+ PART.validate_python(table)+++ ("field", "value"),+ [("total_rows", 3.0), ("total_rows", 1e3), ("total_rows", 10**400), ("cell", 10**400)],+)+def test_integers_arrive_as_bounded_json_integers(field: str, value: object) -> None:+ """Python-only: a JavaScript reader sees 3.0 as 3, so the wire sends ints."""+ table = copy.deepcopy(FIXTURE["valid"]["t1"])+ if field == "cell":+ table["rows"][0]["churn"] = value+ else:+ table[field] = value+ with pytest.raises(ValidationError):+ PART.validate_python(table)+++def test_the_registry_is_the_discriminated_union() -> None:+ assert [(model.__name__, model.is_data) for model in views.VIEW_MODELS] == [+ ("TableView", True),+ ("ChartView", True),+ ("SectionView", False),+ ]