diff --git a/client/e2e/capabilities.spec.ts b/client/e2e/capabilities.spec.ts new file mode 100644 index 00000000..c5d8e03a --- /dev/null +++ b/client/e2e/capabilities.spec.ts @@ -0,0 +1,81 @@ +// Browser smoke for the Capabilities view: a repo with docs/capabilities/*.yaml opens on its +// capability treemap, a capability with no linked test is marked, a click shows its promise and +// files, and a repo with no map keeps normal Srcly (no Capabilities switch). +import { expect, test } from "@playwright/test"; +import { execFileSync } from "node:child_process"; +import fs from "node:fs"; +import os from "node:os"; +import path from "node:path"; +import { fileURLToPath } from "node:url"; + +const here = path.dirname(fileURLToPath(import.meta.url)); +const SHOTS = path.resolve(here, "../../tmp/e2e"); +fs.mkdirSync(SHOTS, { recursive: true }); + +const AREA = `notes: + title: Notes + promise: Write and read notes. + +note-editor: + parent: notes + title: Edit a note + promise: Typing in a note saves it. + implementation: [src/editor.ts] + tests: [src/editor.test.ts] + +note-export: + parent: notes + title: Export a note + promise: Download a note as Markdown. + implementation: [src/export.ts] +`; + +function makeRepo(withMap: boolean): string { + const dir = path.join(fs.mkdtempSync(path.join(os.tmpdir(), "srcly-e2e-caps-")), "repo"); + const files: Record = { + "src/editor.ts": Array.from({ length: 40 }, (_, i) => `export const e${i} = ${i};`).join("\n") + "\n", + "src/editor.test.ts": `import { e1 } from "./editor";\ntest("saves", () => expect(e1).toBe(1));\n`, + "src/export.ts": Array.from({ length: 20 }, (_, i) => `export const x${i} = ${i};`).join("\n") + "\n", + "src/legacy.ts": "export const old = 1;\n", + }; + if (withMap) files["docs/capabilities/notes.yaml"] = AREA; + for (const [rel, text] of Object.entries(files)) { + fs.mkdirSync(path.dirname(path.join(dir, rel)), { recursive: true }); + fs.writeFileSync(path.join(dir, rel), text); + } + const git = (...args: string[]) => execFileSync("git", ["-C", dir, ...args], { stdio: "ignore" }); + git("init", "-q", "-b", "main"); + git("-c", "user.email=e2e@example.com", "-c", "user.name=e2e", "add", "."); + git("-c", "user.email=e2e@example.com", "-c", "user.name=e2e", "commit", "-q", "-m", "init"); + return dir; +} + +test("a repo with a map opens on its capabilities; one without keeps the treemap", async ({ page }) => { + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + const mapped = makeRepo(true); + + await page.goto(`/?${new URLSearchParams({ repo: mapped })}`); + const view = page.locator('[data-view="capabilities"]'); + await expect(view).toHaveAttribute("data-cap-status", "checked", { timeout: 60_000 }); + await expect(page).toHaveURL(/view=capabilities/); + + // The editor links a test; the export claims code and links none. + await expect(page.locator('[data-capability="note-editor"]')).toHaveAttribute("data-test-level", /solid|some|thin/); + await expect(page.locator('[data-capability="note-export"]')).toHaveAttribute("data-test-level", "none"); + await expect(page.locator('[data-cap-area="__unclaimed"]')).toBeVisible(); + await expect(page.locator("[data-cap-errors]")).toContainText("note-export"); + + await page.locator('[data-capability="note-export"]').click(); + const detail = page.locator('[data-cap-detail="note-export"]'); + await expect(detail).toContainText("Download a note as Markdown."); + await expect(detail.locator('[data-cap-role="implementation"]')).toContainText("src/export.ts"); + await expect(page).toHaveURL(/cap=note-export/); + await page.screenshot({ path: path.join(SHOTS, "capabilities.png") }); + + const plain = makeRepo(false); + await page.goto(`/?${new URLSearchParams({ repo: plain })}`); + await expect(page.locator('[data-view-option="treemap"]')).toHaveAttribute("aria-checked", "true", { timeout: 60_000 }); + await expect(page.locator('[data-view-option="capabilities"]')).toHaveCount(0); + expect(errors).toEqual([]); +}); diff --git a/client/src/components/Treemap.tsx b/client/src/components/Treemap.tsx index d3865927..3bd88191 100644 --- a/client/src/components/Treemap.tsx +++ b/client/src/components/Treemap.tsx @@ -1,6 +1,7 @@ import { createEffect, createMemo, + createResource, createSignal, lazy, onCleanup, @@ -23,13 +24,15 @@ import { useTreemapTooltip } from "../viz/treemap/hooks/useTreemapTooltip"; import { atFromTreePath, baseName, folderOf } from "../navigation/location"; import { addAnchorPatch, refsPatch, tracePatch } from "../navigation/nodeActions"; import NodeActionsMenu, { type NodeMenuTarget } from "../navigation/NodeActionsMenu"; -import { go, location } from "../navigation/store"; +import { go, location, replace } from "../navigation/store"; +import { fetchCapabilities } from "../viz/capabilities/model"; import { buildMetricsIndex } from "../viz/deps/metrics"; import { linkedPathFor, setHoverFrom } from "../utils/hoverLink"; const DependencyView = lazy(() => import("../viz/deps/DependencyView")); const ScatterView = lazy(() => import("../viz/scatter/ScatterView")); const ChangeLensView = lazy(() => import("../changelens/ChangeLensView")); +const CapabilitiesView = lazy(() => import("../viz/capabilities/CapabilitiesView")); interface TreemapProps { data: any; @@ -67,7 +70,30 @@ export default function Treemap(props: TreemapProps) { const showScatter = () => location().view === "scatter"; /** The treemap canvas is covered by another view. */ const showChanges = () => location().view === "changes"; - const covered = () => showDependencyGraph() || showScatter() || showChanges(); + const showCapabilities = () => location().view === "capabilities"; + // Until the map's status is known, a URL with no view could still land on Capabilities: + // hold the treemap canvas (under a second) instead of flashing it and switching away. + const viewAsked = new URLSearchParams(window.location.search).has("view"); + const deciding = () => !viewAsked && !capMap() && capabilities.state !== "errored" && location().view === "treemap"; + const covered = () => showDependencyGraph() || showScatter() || showChanges() || showCapabilities() || deciding(); + // The capabilities map (docs/capabilities/*.yaml), read again with each new scan of the root. + const [capabilities] = createResource( + () => (props.data ? { root: props.rootPath, data: props.data } : null), + ({ root }) => fetchCapabilities(root), + ); + // Read the value only once it exists: a first read of a resource suspends the boundary above it. + const capMap = () => (capabilities.state === "ready" || capabilities.state === "refreshing" ? capabilities.latest : undefined); + const hasCapabilities = () => capMap()?.status === "checked"; + // A repo with a map opens on it, unless the URL already names a view; one without stays on the treemap. + let landed = false; + createEffect(() => { + const map = capMap(); + if (!map || landed) return; + landed = true; + const asked = new URLSearchParams(window.location.search).has("view"); + if (map.status === "checked" && !asked && location().view === "treemap") replace({ view: "capabilities" }); + else if (map.status !== "checked" && location().view === "capabilities") replace({ view: "treemap" }); + }); const [menu, setMenu] = createSignal(null); const openTileMenu = (event: MouseEvent, tile: TreemapTile) => { @@ -247,6 +273,7 @@ export default function Treemap(props: TreemapProps) { setShowMetricPopover={setShowMetricPopover} view={() => location().view} onViewChange={(view) => go({ view })} + hasCapabilities={hasCapabilities} />
@@ -271,6 +298,9 @@ export default function Treemap(props: TreemapProps) { + + + Math.round(n).toLocaleString("en-US"); +const LABEL_PX = 18; + +function readParam(name: string): string | null { + return new URLSearchParams(window.location.search).get(name); +} + +/** Keep the selection and zoom in the URL (replace: a view setting, not a place). */ +function writeParam(name: string, value: string | null) { + const params = new URLSearchParams(window.location.search); + if (value) params.set(name, value); + else params.delete(name); + window.history.replaceState(window.history.state, "", `${window.location.pathname}?${params}${window.location.hash}`); +} + +/** + * The snapshot view of a repo's capabilities map: each product area is a box of its + * capabilities, sized by allocated LOC and colored by how much test code each links. A click + * selects a capability and the rail shows its promise, files and tests; an area's label zooms in. + */ +export default function CapabilitiesView(props: { + map: CapMap | undefined; + onOpenAt: (at: string, line?: number) => void; +}) { + let box: HTMLDivElement | undefined; + const [size, setSize] = createSignal({ w: 0, h: 0 }); + const [zoom, setZoomSignal] = createSignal(readParam("capzoom")); + const [selected, setSelectedSignal] = createSignal(readParam("cap")); + const setZoom = (id: string | null) => { + setZoomSignal(id); + writeParam("capzoom", id); + }; + const select = (id: string | null) => { + setSelectedSignal(id); + writeParam("cap", id); + }; + + onMount(() => { + if (!box) return; + const ro = new ResizeObserver(([e]) => e && setSize({ w: e.contentRect.width, h: e.contentRect.height })); + ro.observe(box); + onCleanup(() => ro.disconnect()); + }); + + const byId = createMemo(() => new Map((props.map?.nodes ?? []).map((n) => [n.id, n]))); + const focus = () => { + const z = zoom(); + return z && byId().get(z)?.children.length ? z : null; + }; + const boxes = createMemo(() => { + const m = props.map; + const { w, h } = size(); + if (!m || m.status !== "checked" || w < 10 || h < 10) return null; + return layout(m, focus(), w, h, LABEL_PX); + }); + const current = (): CapNode | null => { + const id = selected(); + return (id && byId().get(id)) || null; + }; + const crumb = (id: string | null): CapNode[] => { + const out: CapNode[] = []; + for (let n = id ? byId().get(id) : undefined; n; n = n.parent ? byId().get(n.parent) : undefined) out.unshift(n); + return out; + }; + const weak = createMemo(() => (props.map?.nodes ?? []).filter((n) => ["thin", "none"].includes(testLevel(n))).length); + const errors = () => (props.map?.diagnostics ?? []).filter((d) => d.severity === "error"); + + return ( +
+ +
+ + + {(n) => ( + <> + +
+ + {(loc) => ( + + {props.map!.nodes.length} capabilities · {loc().claimed_pct}% of code claimed · {weak()} with thin or no tests + + )} + +
+ Tests / 100 LOC + + {(l) => ( + + + {l.label} + + )} + +
+
+ +
+ +
Reading the capabilities map…
+
+ +
+ {props.map?.status === "no-map" + ? "This repo has no docs/capabilities/*.yaml files, so there is no capabilities map to show." + : `The capabilities map could not be read: ${props.map?.reason ?? "unknown reason"}.`} +
+
+ + {(lay) => ( + <> + + {(g) => { + const n = () => byId().get(g.id); + const unclaimed = g.id === UNCLAIMED; + const canZoom = () => !unclaimed && (n()?.children.length ?? 0) > 0 && g.id !== focus(); + return ( +
+ +
+ ); + }} +
+ t.id !== UNCLAIMED)}> + {(t) => { + const n = () => byId().get(t.id)!; + const level = () => testLevel(n()); + return ( + + ); + }} + + + )} +
+
+ + +
+ ); +} + +function LevelChip(props: { node: CapNode }) { + const level = () => testLevel(props.node); + const label = () => { + const t = props.node.tests; + if (level() === "group") return "No code of its own"; + if (level() === "none") return "No linked test"; + return `${t.lines_per_100_loc} test lines / 100 LOC`; + }; + return ( + + + ); +} + +function Overview(props: { map: CapMap | undefined; onSelect: (id: string) => void }) { + const areas = () => + (props.map?.roots ?? []) + .map((id) => props.map!.nodes.find((n) => n.id === id)!) + .sort((a, b) => b.loc.total - a.loc.total); + return ( + +
+

Product areas

+

+ Select a capability to read its promise, files and tests. An area's label zooms into it. +

+
+ + {(a) => ( + + )} + +
+
+
+ ); +} + +function RefRow(props: { r: CapRef; onOpenAt: (at: string, line?: number) => void }) { + const names = () => props.r.only ?? []; + return ( +
  • + + + + + {(a, i) => ( + <> + {i() > 0 ? ", " : ""} + + + )} + + + +
  • + ); +} + +function Detail(props: { + node: CapNode; + byId: Map; + crumb: CapNode[]; + onSelect: (id: string | null) => void; + onOpenAt: (at: string, line?: number) => void; +}) { + const role = (r: CapRef["role"]) => props.node.refs.filter((x) => x.role === r); + const kids = () => props.node.children.map((c) => props.byId.get(c)!).sort((a, b) => b.loc.total - a.loc.total); + const t = () => props.node.tests; + return ( +
    +
    + + + {(c) => ( + <> + +
    +

    + {props.node.title} + + planned + +

    +

    {props.node.promise}

    +
    + + + {fmt(props.node.loc.total)} LOC · {props.node.loc.files} files + {props.node.loc.shared_files ? ` (${props.node.loc.shared_files} shared)` : ""} + +
    + 0}> +
    + Linked tests: {fmt(t().unit_lines)} unit lines, {fmt(t().e2e_lines)} e2e lines +
    +
    + +

    Capabilities inside

    +
    + + {(k) => ( + + )} + +
    +
    + + {([r, label]) => ( + +

    {label}

    +
      + {(x) => } +
    +
    + )} +
    + +

    Docs

    +
      + + {(d) => } + +
    +
    +
    docs/capabilities/{props.node.file.split("/").pop()}
    +
    + ); +} + +function Unclaimed(props: { map: CapMap | undefined; onOpenAt: (at: string, line?: number) => void }) { + return ( +
    +

    Unclaimed code

    +

    + {fmt(props.map?.loc?.unclaimed ?? 0)} LOC in {fmt(props.map?.loc?.unclaimed_files ?? 0)} files that no capability claims. + A new file here fails srcly capabilities check. +

    +
      + + {(u) => ( +
    • + {fmt(u.loc)} + +
    • + )} +
      +
    +
    + ); +} diff --git a/client/src/viz/capabilities/model.ts b/client/src/viz/capabilities/model.ts new file mode 100644 index 00000000..d5789274 --- /dev/null +++ b/client/src/viz/capabilities/model.ts @@ -0,0 +1,135 @@ +/** + * The capabilities map as `GET /api/capabilities` serves it (`server/app/services/capabilities/check.py`), + * and the two things the view derives from it: how well each capability's tests are linked, and the + * treemap layout. Sizes are allocated LOC: a shared file splits equally among its claimants. + */ +import * as d3 from "d3"; + +export type CapRef = { + role: "entry" | "implementation" | "tests"; + path: string; + exists: boolean; + class?: string; + resolves: boolean; + only?: { name: string; resolved: { line: number; end_line: number; detail: string } | null; candidates: unknown[] }[]; +}; + +export type CapNode = { + id: string; + file: string; + title: string; + promise: string; + parent: string | null; + children: string[]; + state: "built" | "planned"; + tasks: string[]; + docs: string[]; + refs: CapRef[]; + loc: { direct: number; total: number; files: number; shared_files: number }; + tests: { linked: number; resolved: number; unit_lines: number; e2e_lines: number; lines_per_100_loc: number | null }; +}; + +export type CapDiagnostic = { rule: string; severity: "error" | "review" | "warning"; message: string; file?: string; node?: string; path?: string; suggestion?: string }; + +export type CapMap = { + status: "checked" | "no-map" | "unavailable"; + reason?: string; + ok: boolean; + area_files?: string[]; + nodes: CapNode[]; + roots?: string[]; + diagnostics: CapDiagnostic[]; + loc?: { eligible: number; claimed: number; unclaimed: number; eligible_files: number; claimed_files: number; unclaimed_files: number; claimed_pct: number | null }; + unclaimed?: { path: string; loc: number; new: boolean }[]; +}; + +export async function fetchCapabilities(root: string): Promise { + const res = await fetch(`/api/capabilities?path=${encodeURIComponent(root)}`); + if (!res.ok) return { status: "unavailable", reason: `The server answered ${res.status}.`, ok: false, nodes: [], diagnostics: [] }; + return (await res.json()) as CapMap; +} + +/** + * How much test code a capability links, per 100 allocated LOC of its own code. A size of what is + * linked, not coverage. `group`: the node claims no code of its own. + */ +export type TestLevel = "none" | "thin" | "some" | "solid" | "group"; + +export const TEST_LEVELS: { id: TestLevel; label: string; hint: string }[] = [ + { id: "solid", label: "25+", hint: "25 or more linked test lines per 100 LOC" }, + { id: "some", label: "5–25", hint: "5 to 25 linked test lines per 100 LOC" }, + { id: "thin", label: "Under 5", hint: "Fewer than 5 linked test lines per 100 LOC" }, + { id: "none", label: "No test", hint: "Claims code but links no test that resolves" }, +]; + +export function testLevel(n: CapNode): TestLevel { + const ratio = n.tests.lines_per_100_loc; + if (ratio === null || n.loc.direct <= 0) return "group"; + if (n.tests.resolved === 0) return "none"; + return ratio < 5 ? "thin" : ratio < 25 ? "some" : "solid"; +} + +/** Fill and edge for each level, from the theme tokens. */ +// The `-subtle` tokens are near the page color, too faint to read as a fill across a whole map. +const tint = (token: string, pct: number) => `color-mix(in oklab, var(${token}) ${pct}%, var(--plc-surface))`; +export const LEVEL_STYLE: Record = { + solid: { bg: tint("--plc-success", 24), edge: "var(--plc-success)" }, + some: { bg: tint("--plc-accent", 18), edge: "var(--plc-accent)" }, + thin: { bg: tint("--plc-warning", 26), edge: "var(--plc-warning)" }, + none: { bg: tint("--plc-error", 26), edge: "var(--plc-error)" }, + group: { bg: "var(--plc-surface-subtle)", edge: "var(--plc-border-strong)" }, +}; + +export const UNCLAIMED = "__unclaimed"; + +export type Box = { id: string; own: boolean; x: number; y: number; w: number; h: number; value: number }; +export type Layout = { groups: Box[]; tiles: (Box & { group: string })[] }; + +/** + * Two levels under `focus` (null: every root area, plus Unclaimed): each child is a group box with + * a label strip, and its children are tiles. A group's own code is one more tile ("own files"), and + * a child with no children of its own fills its group as one tile. + */ +export function layout(map: CapMap, focus: string | null, width: number, height: number, label = 18): Layout { + const byId = new Map(map.nodes.map((n) => [n.id, n])); + const top = focus ? (byId.get(focus)?.children ?? []) : (map.roots ?? []); + type Datum = { id: string; own?: boolean; value?: number; children?: Datum[] }; + const group = (id: string): Datum => { + const n = byId.get(id)!; + const kids: Datum[] = n.children.map((c) => ({ id: c, value: byId.get(c)!.loc.total })); + if (n.loc.direct > 0 || !kids.length) kids.push({ id, own: true, value: n.loc.direct }); + return { id, children: kids }; + }; + const groups: Datum[] = top.map(group); + if (focus) { + const n = byId.get(focus); + if (n && n.loc.direct > 0) groups.push({ id: focus, children: [{ id: focus, own: true, value: n.loc.direct }] }); + } else if (map.loc && map.loc.unclaimed > 0) { + groups.push({ id: UNCLAIMED, children: [{ id: UNCLAIMED, own: true, value: map.loc.unclaimed }] }); + } + const root = d3 + .hierarchy({ id: "", children: groups }) + .sum((d) => (d.children ? 0 : Math.max(0, d.value ?? 0))) + .sort((a, b) => (b.value ?? 0) - (a.value ?? 0)); + d3 + .treemap() + .size([width, height]) + .tile(d3.treemapSquarify) + .paddingOuter((d) => (d.depth === 1 ? 1 : 0)) + .paddingTop((d) => (d.depth === 1 ? label : 0)) + .paddingInner((d) => (d.depth === 0 ? 2 : 1))(root); + const box = (d: d3.HierarchyRectangularNode): Box => ({ + id: d.data.id, + own: !!d.data.own, + x: d.x0, + y: d.y0, + w: Math.max(0, d.x1 - d.x0), + h: Math.max(0, d.y1 - d.y0), + value: d.value ?? 0, + }); + const rect = root as d3.HierarchyRectangularNode; + return { + groups: (rect.children ?? []).filter((g) => (g.value ?? 0) > 0).map(box), + tiles: (rect.children ?? []).flatMap((g) => (g.children ?? []).filter((t) => (t.value ?? 0) > 0).map((t) => ({ ...box(t), group: g.data.id }))), + }; +} diff --git a/client/src/viz/treemap/components/TreemapHeader.tsx b/client/src/viz/treemap/components/TreemapHeader.tsx index 146863e1..79b1c2a3 100644 --- a/client/src/viz/treemap/components/TreemapHeader.tsx +++ b/client/src/viz/treemap/components/TreemapHeader.tsx @@ -1,5 +1,5 @@ import { For, Show, type Accessor } from "solid-js"; -import { ChartScatter, GitCommitHorizontal, GitFork, LayoutGrid } from "lucide-solid"; +import { Blocks, ChartScatter, GitCommitHorizontal, GitFork, LayoutGrid } from "lucide-solid"; import { metricLabel, type MetricId, @@ -34,28 +34,32 @@ export type TreemapHeaderProps = { view: Accessor; onViewChange: (view: View) => void; + /** The repo has a capabilities map, so the Capabilities view is offered. */ + hasCapabilities: Accessor; }; const VIEWS: { id: View; label: string; icon: typeof GitFork }[] = [ + { id: "capabilities", label: "Capabilities", icon: Blocks }, { id: "treemap", label: "Treemap", icon: LayoutGrid }, { id: "graph", label: "Graph", icon: GitFork }, { id: "scatter", label: "2x2", icon: ChartScatter }, { id: "changes", label: "Changes", icon: GitCommitHorizontal }, ]; -const VIEW_IDS = VIEWS.map((v) => v.id); - export default function TreemapHeader(props: TreemapHeaderProps) { + // A repo with no capabilities map shows normal Srcly: no Capabilities switch. + const views = () => VIEWS.filter((v) => v.id !== "capabilities" || props.hasCapabilities()); + const viewIds = () => views().map((v) => v.id); return (
    {/* One switch for both projections of the same place. */}
    segmentedKeyDown(e, VIEW_IDS, props.view(), props.onViewChange)} + onKeyDown={(e) => segmentedKeyDown(e, viewIds(), props.view(), props.onViewChange)} class="flex shrink-0 rounded-md border border-[var(--plc-border)] bg-[var(--plc-surface-muted)] p-0.5" > - + {(v) => (