diff --git a/README.md b/README.md index 04419f7a..32cedf6e 100644 --- a/README.md +++ b/README.md @@ -48,8 +48,11 @@ uvx srcly scan . --out .srcly/tree.json uvx srcly hotspots . --metric complexity --limit 25 uvx srcly explain . --at client/src uvx srcly explain . --at "client/src/App.tsx::App" +uvx srcly changes . --window 7d ``` +`srcly changes` lists the code chunks a branch or a time window edited (`--window branch|24h|7d|custom`, `--mode touched|net`), with before → after complexity and what to review first. The app shows the same result in its **Changes** view. + By default, `uvx srcly report` writes compact artifacts intended to be safe for agents to inspect: - `report.md` — human-readable summary, the top files and functions by one metric (`--metric`, default the profile's lead metric, e.g. `complexity`), the profile's findings queue, and a compact tree breakdown. diff --git a/client/e2e/changes.spec.ts b/client/e2e/changes.spec.ts new file mode 100644 index 00000000..3a4d2d0c --- /dev/null +++ b/client/e2e/changes.spec.ts @@ -0,0 +1,64 @@ +// Browser smoke for the Changes view on the Change Lens acceptance repo +// (server/tests/fixtures/change_lens_repo.py): open Changes, select a chunk, +// read its diff, and see the reverted chunk leave when Net is picked. +import { expect, test, type Page } 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 }); + +let repo = ""; +test.beforeAll(() => { + const dir = fs.mkdtempSync(path.join(os.tmpdir(), "srcly-e2e-lens-")); + repo = execFileSync("uv", ["run", "--directory", path.resolve(here, "../../server"), "python", "-m", "tests.fixtures.change_lens_repo", path.join(dir, "repo")], { + encoding: "utf8", + }) + .trim() + .split("\n") + .pop()!; +}); + +const chunk = (page: Page, id: string) => page.locator(`[data-chunk="${id}"]`); +const lensReady = (page: Page) => expect(page.locator("[data-change-lens]")).toHaveAttribute("data-lens-state", "ready", { timeout: 60_000 }); + +test.describe("Changes view on the acceptance repo", () => { + test("only edits, a chunk's diff, and reverted work in Touched but not Net", async ({ page }) => { + const errors: string[] = []; + page.on("pageerror", (error) => errors.push(error.message)); + await page.goto(`/?${new URLSearchParams({ repo, view: "changes" })}`); + await lensReady(page); + + // Only edits: the edited functions, not the untouched ones of the same large file. + await expect(chunk(page, "src/worker.ts::retryJob")).toBeVisible(); + await expect(chunk(page, "src/scheduler.ts::isIdle")).toHaveCount(0); + await expect(chunk(page, "src/scheduler.ts::pickNext")).toHaveAttribute("data-state", "reverted"); + + // A click selects the chunk: the breadcrumbs and the inspector follow it. + await chunk(page, "src/worker.ts::retryJob").click(); + await expect(chunk(page, "src/worker.ts::retryJob")).toHaveAttribute("data-selected", ""); + await expect(page.locator('[data-crumb="src/worker.ts"]')).toBeVisible(); + const inspector = page.locator('[data-chunk-inspector="src/worker.ts::retryJob"]'); + await expect(inspector.locator('[data-metric="complexity"]')).toContainText("5"); + + // Open diff shows the chunk's own lines. + await inspector.locator('[data-action="open-diff"]').click(); + const diff = page.locator("[data-hunk-diff]"); + await expect(diff.locator('[data-line="add"]').first()).toBeVisible(); + await expect(diff).toContainText("retryJob"); + await expect(diff).not.toContainText("parseArgs"); + await page.screenshot({ path: path.join(SHOTS, "changes-diff.png") }); + + // Net drops the reverted chunk and keeps the selection. + await page.locator('[data-lens-group="mode"] [data-lens-option="net"]').click(); + await expect(chunk(page, "src/scheduler.ts::pickNext")).toHaveCount(0); + await lensReady(page); + await expect(chunk(page, "src/worker.ts::retryJob")).toHaveAttribute("data-selected", ""); + await page.screenshot({ path: path.join(SHOTS, "changes-net.png") }); + expect(errors).toEqual([]); + }); +}); diff --git a/client/src/changelens/ChangeLensView.tsx b/client/src/changelens/ChangeLensView.tsx index 635d1269..dc73f9bb 100644 --- a/client/src/changelens/ChangeLensView.tsx +++ b/client/src/changelens/ChangeLensView.tsx @@ -2,7 +2,7 @@ // It owns the fetches and the URL state; the map and the panel pieces get // everything through props. -import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show, type JSX } from "solid-js"; +import { createEffect, createMemo, createSignal, For, on, onCleanup, onMount, Show, untrack, type JSX } from "solid-js"; import { ArrowRight } from "lucide-solid"; import { Button } from "../components/ui/Button"; import { atFromTreePath, baseName, splitAt } from "../navigation/location"; @@ -13,7 +13,7 @@ import { plural, timeLimits } from "./labels"; import { inScope, type RepoNode } from "./layout"; import Legend from "./Legend"; import LensMap from "./LensMap"; -import { ChunkInspector, CommitRail, HunkDiff, ReviewBuckets } from "./slots"; +import { ChunkInspector, CommitRail, HunkDiff, ReviewBuckets } from "./panel"; import type { ChangeLensPayload, LensChunk, LensHunkDiff } from "./types"; import { lens, setLens } from "./urlState"; import WindowBar from "./WindowBar"; @@ -29,12 +29,19 @@ interface ScanNode { metrics?: { loc?: number; file_count?: number }; } -/** The scan tree as folders and files with repo-relative paths, and each folder's file count. */ -function repoTree(data: ScanNode | null, root: string): { tree: RepoNode | null; fileCounts: Map } { +/** `at` (relative to the scan root) as a repo path, when the scan root is the folder `scope` of the repo. */ +export const repoPath = (scope: string, at: string) => (scope && at ? `${scope}/${at}` : scope || at); + +/** A repo path as an `at` relative to the scan root. Every payload path lies under the scope. */ +export const scanPath = (scope: string, path: string) => (scope && inScope(path, scope) ? path.slice(scope.length + 1) : path); + +/** The scan tree as folders and files with repo paths, and each folder's file count. */ +function repoTree(data: ScanNode | null, root: string, scope: string): { tree: RepoNode | null; fileCounts: Map } { const fileCounts = new Map(); const walk = (node: ScanNode): RepoNode | null => { - const path = atFromTreePath(node.path, root); - if (path === null) return null; + const at = atFromTreePath(node.path, root); + if (at === null) return null; + const path = repoPath(scope, at); if (node.type === "file") return { name: node.name, path, loc: node.metrics?.loc ?? 0 }; if (node.type !== "folder") return null; const children = (node.children ?? []).map(walk).filter((c): c is RepoNode => c !== null && (!c.children || c.children.length > 0)); @@ -45,6 +52,13 @@ function repoTree(data: ScanNode | null, root: string): { tree: RepoNode | null; return { tree: data ? walk(data) : null, fileCounts }; } +/** `5 of 43 files · 2 deleted`: the total counts files at head, so deleted files are counted apart. */ +function fileCount(p: ChangeLensPayload): string { + const deleted = p.files.filter((f) => f.status === "deleted").length; + const kept = `${(p.summary.filesEdited - deleted).toLocaleString("en-US")} of ${plural(p.summary.filesTotal, "file")}`; + return deleted ? `${kept} · ${deleted} deleted` : kept; +} + function Message(props: { title: string; children?: JSX.Element; state: string }) { return (
@@ -99,11 +113,36 @@ export default function ChangeLensView(props: { }; createEffect(on(query, load)); - const scope = () => splitAt(location().at).file; - const scan = createMemo(() => repoTree(props.data, props.rootPath)); + // Payload paths are repo paths; `location().at` is relative to the scan root, which can be a folder of the repo. + const base = () => payload()?.selection.scope ?? ""; + /** The folder or file the map is zoomed to, as a repo path. */ + const scope = () => repoPath(base(), splitAt(location().at).file); + const scan = createMemo(() => repoTree(props.data, props.rootPath, base())); const selected = createMemo(() => payload()?.chunks.find((c) => c.id === lens().chunk) ?? null); const commit = createMemo(() => payload()?.commits.find((c) => c.sha === lens().commit) ?? null); const inView = createMemo(() => payload()?.chunks.filter((c) => inScope(c.path, scope())).length ?? 0); + const zoom = (path: string) => go({ at: scanPath(base(), path) }); + + let lastSelected: LensChunk | null = null; + createEffect(() => { + if (selected()) lastSelected = selected(); + }); + // A new result keeps the selected chunk and commit when they still exist. A range chunk's id holds its + // lines, which differ between touched and net: it moves to the range of the same file that overlaps it. + createEffect( + on(payload, (p) => { + if (!p) return; + const s = lens(); + const patch: { chunk?: string | null; commit?: string | null } = {}; + if (s.chunk && !p.chunks.some((c) => c.id === s.chunk)) { + const old = lastSelected; + const twin = old && p.chunks.find((c) => c.path === old.path && c.kind === old.kind && c.startLine <= old.endLine && old.startLine <= c.endLine); + patch.chunk = twin?.id ?? null; + } + if (s.commit && !p.commits.some((c) => c.sha === s.commit)) patch.commit = null; + if (Object.keys(patch).length) setLens(patch, "step"); + }) + ); // --- the open diff ---------------------------------------------------------------- const [hunk, setHunk] = createSignal<{ chunk: string; commit?: string } | null>(null); @@ -111,11 +150,21 @@ export default function ChangeLensView(props: { const [diffError, setDiffError] = createSignal(); const [diffLoading, setDiffLoading] = createSignal(false); let diffRequest = 0; + // The diff reloads when a new result arrives, not when the query changes: until then the chunk may not exist. createEffect( - on([hunk, query], ([h, q]) => { + on([hunk, payload], ([h, p]) => { const id = ++diffRequest; + const q = untrack(query); setDiffError(undefined); - if (!h || !q) { + if (h && p && !p.chunks.some((c) => c.id === h.chunk)) { + setHunk(null); + return; + } + if (h?.commit && p && !p.commits.some((c) => c.sha === h.commit)) { + setHunk({ chunk: h.chunk }); + return; + } + if (!h || !q || !p) { setDiff(null); setDiffLoading(false); return; @@ -136,12 +185,24 @@ export default function ChangeLensView(props: { ); }) ); + /** The selected commit's step when that commit changed the chunk, else the whole window. */ + const stepOf = (chunk: string) => (commit()?.chunkIds.includes(chunk) ? commit()!.sha : undefined); const openHunk = (chunk: string, sha?: string) => { - setHunk({ chunk, commit: sha }); + setHunk({ chunk, commit: sha ?? stepOf(chunk) }); if (lens().chunk !== chunk) setLens({ chunk }); }; - /** From the map: the selected commit's step when that commit changed the chunk, else the whole window. */ - const openFromMap = (chunk: string) => openHunk(chunk, commit()?.chunkIds.includes(chunk) ? commit()!.sha : undefined); + const openFromMap = (chunk: string) => openHunk(chunk); + // An open diff follows the selected commit. + createEffect( + on( + commit, + () => { + const open = untrack(hunk); + if (open) setHunk({ chunk: open.chunk, commit: stepOf(open.chunk) }); + }, + { defer: true } + ) + ); // An open diff follows the selection, so the arrow keys step through diffs. createEffect( on( @@ -149,7 +210,7 @@ export default function ChangeLensView(props: { (chunk) => { const open = hunk(); if (!open || open.chunk === chunk) return; - setHunk(chunk ? { chunk } : null); + setHunk(chunk ? { chunk, commit: stepOf(chunk) } : null); }, { defer: true } ) @@ -170,11 +231,12 @@ export default function ChangeLensView(props: { const crumbs = createMemo(() => { const out: { label: string; at: string; inScope: boolean }[] = [{ label: baseName(props.rootPath) || "repo", at: "", inScope: true }]; const chunk = selected(); - const path = chunk && inScope(chunk.path, scope()) ? chunk.path : scope(); + const here = scanPath(base(), scope()); + const path = chunk && inScope(chunk.path, scope()) ? scanPath(base(), chunk.path) : here; const parts = path ? path.split("/") : []; parts.forEach((label, i) => { const at = parts.slice(0, i + 1).join("/"); - out.push({ label, at, inScope: inScope(scope(), at) }); + out.push({ label, at, inScope: inScope(here, at) }); }); return out; }); @@ -186,7 +248,7 @@ export default function ChangeLensView(props: { {/* What the window resolved to. One fixed-height row at rest; notes wrap under it. */} -
+
{loading() ? "Reading the history of this window…" : " "}}> {(p) => ( <> @@ -209,7 +271,8 @@ export default function ChangeLensView(props: { )} - + {/* Out of the flow, so the line never wraps differently while a window loads. */} + {loading() && payload() ? "Updating…" : ""}
@@ -242,7 +305,7 @@ export default function ChangeLensView(props: { {(p) => (
- {/* The diff opens over the map and its legend; the commit rail under them stays in reach. */} + {/* The diff opens under the map, which shrinks to make room, so the selected chunk stays in view. */}
- {plural(p().summary.filesEdited, "file")} of {p().summary.filesTotal.toLocaleString("en-US")} · {plural(p().summary.chunks, "chunk")} · {p().summary.churnLines.toLocaleString("en-US")} lines churned / {p().summary.netLines.toLocaleString("en-US")} net + {fileCount(p())} · {plural(p().summary.chunks, "chunk")} · {p().summary.churnLines.toLocaleString("en-US")} lines churned / {p().summary.netLines.toLocaleString("en-US")} net {p().summary.reverted ? ` · ${p().summary.reverted} reverted` : ""}
-
+
scan().fileCounts.get(folder) ?? null} onSelect={(chunk, how) => setLens({ chunk }, how)} onOpen={openFromMap} - onZoom={(at) => go({ at })} + onZoom={zoom} />
- No edits under {scope()} in this window.{" "} + No edits under {scanPath(base(), scope())} in this window.{" "} @@ -312,7 +375,7 @@ export default function ChangeLensView(props: {
-
+
setHunk(null)} />
@@ -326,7 +389,7 @@ export default function ChangeLensView(props: { setLens({ chunk })} />
- props.onOpenAt(chunk.path, chunk.startLine)} /> + props.onOpenAt(scanPath(base(), chunk.path), chunk.startLine)} />
diff --git a/client/src/changelens/Legend.tsx b/client/src/changelens/Legend.tsx index 95d947fc..a06439bf 100644 --- a/client/src/changelens/Legend.tsx +++ b/client/src/changelens/Legend.tsx @@ -19,7 +19,7 @@ export default function Legend(props: { lens: Lens; layout: LensLayout }) { const domain = () => metricDef(props.lens.metric)?.color_domain ?? [0, 10, 50]; const value = (n: number) => formatMetricValue(props.lens.metric, n); return ( -
+
{metricLabel(props.lens.metric)} {props.lens.color === "delta" ? "delta" : "now"} @@ -56,7 +56,7 @@ export default function Legend(props: { lens: Lens; layout: LensLayout }) { )} - + {props.layout === "edits" ? "Area: changed lines · dots: commits that touched the chunk" : "Area: file LOC · bands: edited chunks at their lines"}
diff --git a/client/src/changelens/LensMap.tsx b/client/src/changelens/LensMap.tsx index 06b31277..9114893e 100644 --- a/client/src/changelens/LensMap.tsx +++ b/client/src/changelens/LensMap.tsx @@ -2,13 +2,13 @@ // boxes: the layout memo depends on the data, the size, the scope and the // collapsed groups only, so a color change repaints fills and moves nothing. -import { createMemo, createSignal, For, onCleanup, onMount, Show, type JSX } from "solid-js"; +import { createEffect, createMemo, createSignal, For, onCleanup, onMount, Show, untrack, type JSX } from "solid-js"; import { ChevronDown, ChevronRight } from "lucide-solid"; import type { Rect } from "../compare/treemapLayout"; import { metricLabel } from "../utils/metricsStore"; import { STATE_GLYPH, tileLook, type Lens, type TileLook } from "./colors"; import { beforeAfter, folderLabel, matchNote, plural, signed, STATUS_LABEL } from "./labels"; -import { inScope, layoutEdits, layoutRepo, neighbour, repoTreeFromFiles, type ChunkTile, type GroupTile, type RepoFileTile, type RepoNode } from "./layout"; +import { inScope, layoutEdits, pooledChunks, layoutRepo, neighbour, repoTreeFromFiles, type ChunkTile, type GroupTile, type RepoFileTile, type RepoNode } from "./layout"; import { WORKTREE, type ChangeLensPayload, type LensChunk, type LensCommit } from "./types"; import type { LensLayout } from "./urlState"; @@ -59,6 +59,15 @@ export default function LensMap(props: { let host: HTMLDivElement | undefined; const [size, setSize] = createSignal({ width: 0, height: 0 }); const [collapsed, setCollapsed] = createSignal>(new Set()); + // Files whose pooled smaller chunks the user opened. + const [expanded, setExpanded] = createSignal>(new Set()); + // A selected chunk leaves its pool and stays out, so a later click elsewhere moves nothing. + const [kept, setKept] = createSignal>(new Set()); + createEffect(() => { + const id = props.selected; + if (id && !untrack(kept).has(id)) setKept((prev) => new Set(prev).add(id)); + }); + const pooled = createMemo(() => (props.layout === "edits" ? pooledChunks(props.payload.chunks, size(), props.scope, expanded(), kept()) : new Set())); const [hover, setHover] = createSignal(null); onMount(() => { @@ -71,7 +80,7 @@ export default function LensMap(props: { onCleanup(() => observer.disconnect()); }); - const edits = createMemo(() => (props.layout === "edits" ? layoutEdits(props.payload.chunks, size(), props.scope, collapsed()) : null)); + const edits = createMemo(() => (props.layout === "edits" ? layoutEdits(props.payload.chunks, size(), props.scope, collapsed(), pooled()) : null)); const repo = createMemo(() => props.layout === "repo" ? layoutRepo(props.tree ?? repoTreeFromFiles(props.payload.files), props.payload.files, props.payload.chunks, size(), props.scope) : null ); @@ -80,12 +89,14 @@ export default function LensMap(props: { const inCommit = createMemo(() => (props.commit ? new Set(props.commit.chunkIds) : null)); const dimmed = (id: string) => Boolean(inCommit() && !inCommit()!.has(id)); + const flip = (set: ReadonlySet, path: string) => { + const next = new Set(set); + if (!next.delete(path)) next.add(path); + return next; + }; + /** A pool tile opens its file's smaller chunks; any other group folds or unfolds. */ const toggle = (path: string) => - setCollapsed((prev) => { - const next = new Set(prev); - if (!next.delete(path)) next.add(path); - return next; - }); + path.endsWith("#more") ? setExpanded((prev) => flip(prev, path.slice(0, -"#more".length))) : setCollapsed((prev) => flip(prev, path)); const groupStats = (group: GroupTile) => { const files = props.payload.files.filter((f) => inScope(f.path, group.path)); @@ -181,6 +192,48 @@ export default function LensMap(props: { ); }; + const byId = createMemo(() => new Map(props.payload.chunks.map((c) => [c.id, c]))); + + /** A file's smaller chunks as one tile: a count, their lines, and their names on hover. A click opens them. */ + const PoolBox = (p: { group: GroupTile }) => { + const g = p.group; + const chunks = createMemo(() => g.chunkIds.map((id) => byId().get(id)!).filter(Boolean)); + const lines = createMemo(() => chunks().reduce((n, c) => [n[0] + c.added, n[1] + c.deleted], [0, 0])); + const holdsSelection = () => Boolean(props.selected && g.chunkIds.includes(props.selected)); + const isDim = () => Boolean(inCommit()) && g.chunkIds.every(dimmed); + const w = widthOf(g.rect); + const h = heightOf(g.rect); + return ( + + ); + }; + const GroupBox = (p: { group: GroupTile; repo?: boolean }) => { const g = p.group; const stats = createMemo(() => groupStats(g)); @@ -306,7 +359,7 @@ export default function LensMap(props: { {(l) => ( <> - {(group) => } + {(group) => (group.kind === "pool" ? : )} {(tile) => } )} diff --git a/client/src/changelens/WindowBar.tsx b/client/src/changelens/WindowBar.tsx index 499200c9..a9fa8617 100644 --- a/client/src/changelens/WindowBar.tsx +++ b/client/src/changelens/WindowBar.tsx @@ -185,8 +185,8 @@ function WindowPicker(props: { state: LensState; onChange: (patch: Partial void }) { +/** Which metric drives the color, and whether it shows the value now or its change. */ +function MetricMenu(props: { metricIds: string[]; selected: string; onSelect: (id: string) => void; color: ColorMode; onColor: (c: ColorMode) => void }) { const [open, setOpen] = createSignal(false); return ( ( - )} > - + +
+ Color by + +
+
No metric has a value in this window.
}> {(id) => ( )} +
); @@ -241,8 +250,13 @@ export default function WindowBar(props: { state: LensState; metricIds: string[] props.onChange({ mode })} /> props.onChange({ layout })} /> - props.onChange({ metric })} /> - props.onChange({ color })} /> + props.onChange({ metric })} + color={props.state.color} + onColor={(color) => props.onChange({ color })} + /> ); } diff --git a/client/src/changelens/api.ts b/client/src/changelens/api.ts index a7704cb0..4fa44aac 100644 --- a/client/src/changelens/api.ts +++ b/client/src/changelens/api.ts @@ -1,5 +1,8 @@ -// Fetches for the Changes view. `?clmock=1` answers from sample.ts instead of -// the server (`clmock=empty|nogit|error` show the other states). +// Fetches for the Changes view. +// +// The view never sends `ref` or `worktree`: it reads the checked-out branch +// (HEAD) and includes uncommitted edits, which is what "after a coding +// session" means. Custom windows pick other revisions through base and head. import type { ChangeLensPayload, LensHunkDiff, LensMode, LensWindow } from "./types"; @@ -23,9 +26,6 @@ export class LensError extends Error { } } -export const mockKind = (): string | null => - typeof window === "undefined" ? null : new URLSearchParams(window.location.search).get("clmock"); - function params(q: LensQuery): URLSearchParams { const p = new URLSearchParams({ path: q.path, window: q.window, mode: q.mode }); if (q.window === "custom") { @@ -51,23 +51,9 @@ async function getJson(url: string): Promise { throw new LensError(res.status, reason); } -const pause = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms)); - -export async function fetchChangeLens(q: LensQuery): Promise { - const mock = mockKind(); - if (!mock) return getJson(`/api/change-lens?${params(q)}`); - await pause(120); - if (mock === "nogit") throw new LensError(409, `${q.path} is not inside a git repository.`); - if (mock === "error") throw new LensError(500, "git log failed: fatal: bad revision 'HEAD'"); - const sample = await import("./sample"); - return mock === "empty" ? sample.emptyPayload(q) : sample.samplePayload(q); -} +export const fetchChangeLens = (q: LensQuery) => getJson(`/api/change-lens?${params(q)}`); -export async function fetchHunk(q: LensQuery, chunk: string, commit?: string): Promise { - if (mockKind()) { - await pause(120); - return (await import("./sample")).sampleHunk(q, chunk, commit); - } +export function fetchHunk(q: LensQuery, chunk: string, commit?: string): Promise { const p = params(q); p.set("chunk", chunk); if (commit) p.set("commit", commit); diff --git a/client/src/changelens/changelens.test.ts b/client/src/changelens/changelens.test.ts index 552a8d59..cfd6dae3 100644 --- a/client/src/changelens/changelens.test.ts +++ b/client/src/changelens/changelens.test.ts @@ -3,8 +3,9 @@ import { parseLocation, toSearch } from "../navigation/location"; import { ADDED_FILL, tileLook } from "./colors"; import { folderLabel } from "./labels"; import { bandRect, flooredWeights, layoutEdits, MIN_TILE_AREA, MIN_TILE_SIDE } from "./layout"; -import { samplePayload } from "./sample"; -import type { LensChunk } from "./types"; +import touched from "./fixture.json"; +import net from "./fixture.net.json"; +import type { ChangeLensPayload, LensChunk } from "./types"; import { DEFAULT_LENS, parseLens, serializeLens, type LensState } from "./urlState"; const chunk = (over: Partial): LensChunk => ({ @@ -61,18 +62,18 @@ describe("only-edits packing", () => { }); it("collapses a group in place and zooms to a scope", () => { - const chunks = samplePayload({ path: "/repo", window: "branch", mode: "touched" }).chunks; + const chunks = (touched as ChangeLensPayload).chunks; const size = { width: 1200, height: 700 }; const open = layoutEdits(chunks, size); - const folded = layoutEdits(chunks, size, "", new Set(["server/tests"])); + const folded = layoutEdits(chunks, size, "", new Set(["src/worker.ts"])); const rect = (l: typeof open, path: string) => l.groups.find((g) => g.path === path)!.rect; - expect(rect(folded, "server/tests")).toEqual(rect(open, "server/tests")); - expect(rect(folded, "client/src")).toEqual(rect(open, "client/src")); - expect(folded.chunks.some((t) => t.chunk.path.startsWith("server/tests/"))).toBe(false); - expect(folded.groups.find((g) => g.path === "server/tests")!.chunkIds.length).toBeGreaterThan(3); + expect(rect(folded, "src/worker.ts")).toEqual(rect(open, "src/worker.ts")); + expect(rect(folded, "config")).toEqual(rect(open, "config")); + expect(folded.chunks.some((t) => t.chunk.path === "src/worker.ts")).toBe(false); + expect(folded.groups.find((g) => g.path === "src/worker.ts")!.chunkIds.length).toBe(4); - const zoomed = layoutEdits(chunks, size, "server/app/routers"); - expect(new Set(zoomed.chunks.map((t) => t.chunk.path))).toEqual(new Set(["server/app/routers/scans.py"])); + const zoomed = layoutEdits(chunks, size, "src/util"); + expect(new Set(zoomed.chunks.map((t) => t.chunk.path))).toEqual(new Set(["src/util/text.ts"])); }); it("places a band by its lines and keeps a one-line band visible", () => { @@ -149,15 +150,20 @@ describe("tile state under a lens", () => { }); }); -describe("the sample payload", () => { - it("covers every status, kind and match, and drops reverted work in net mode", () => { - const touched = samplePayload({ path: "/repo", window: "branch", mode: "touched" }); - const all = (key: K) => [...new Set(touched.chunks.map((c) => c[key]))].sort(); - expect(all("status")).toEqual(["added", "deleted", "modified", "moved", "reverted"]); - expect(all("kind")).toEqual(["class", "file", "function", "heading", "range"]); - expect(all("match")).toEqual(["exact", "moved", "none", "renamed-file", "uncertain"]); - const net = samplePayload({ path: "/repo", window: "branch", mode: "net" }); - expect(net.chunks.some((c) => c.status === "reverted")).toBe(false); - expect(net.chunks.every((c) => c.touches.length === 0)).toBe(true); +describe("the server's payload for the acceptance repo", () => { + const t = touched as ChangeLensPayload; + const n = net as ChangeLensPayload; + + it("keeps reverted work in touched mode only", () => { + expect(t.chunks.filter((c) => c.status === "reverted").map((c) => c.id)).toEqual(["src/scheduler.ts::pickNext"]); + expect(n.chunks.some((c) => c.id === "src/scheduler.ts::pickNext")).toBe(false); + expect(n.chunks.every((c) => c.touches.length === 0)).toBe(true); + }); + + it("draws the pure rename as a move with no change, and the config hunk as not measured", () => { + const rename = t.chunks.find((c) => c.id === "src/util/text.ts")!; + expect(tileLook(rename, { metric: "complexity", color: "delta" })).toMatchObject({ state: "moved", value: 0 }); + const config = t.chunks.find((c) => c.path === "config/settings.yaml")!; + expect(tileLook(config, { metric: "complexity", color: "now" })).toMatchObject({ state: "not-measured", value: null }); }); }); diff --git a/client/src/changelens/fixture.json b/client/src/changelens/fixture.json index 54f15c95..33e97398 100644 --- a/client/src/changelens/fixture.json +++ b/client/src/changelens/fixture.json @@ -20,7 +20,8 @@ "timezone": "UTC", "includesWorktree": true, "notes": [], - "repoRoot": "/repo/change-lens-fixture" + "repoRoot": "/repo/change-lens-fixture", + "scope": "" }, "commits": [ { @@ -307,19 +308,23 @@ "firstTouched": "2026-01-06T19:00:00+00:00", "lastTouched": "2026-01-06T19:00:00+00:00", "metrics": { - "parameter_count": { + "cognitive_complexity": { "before": null, - "after": 2 + "after": 17 }, - "ts_type_interface_count": { + "comment_lines": { "before": null, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": null, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": null, + "after": 0 + }, + "comment_noise_docblock": { "before": null, "after": 0 }, @@ -327,33 +332,29 @@ "before": null, "after": 0 }, - "cognitive_complexity": { + "complexity": { "before": null, - "after": 17 + "after": 12 }, - "max_nesting_depth": { + "loc": { "before": null, - "after": 3 + "after": 22 }, - "complexity": { + "max_nesting_depth": { "before": null, - "after": 12 + "after": 3 }, - "comment_noise_commented_code": { + "parameter_count": { "before": null, - "after": 0 + "after": 2 }, "todo_count": { "before": null, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": null, "after": 0 - }, - "loc": { - "before": null, - "after": 22 } }, "measured": true, @@ -396,19 +397,23 @@ "firstTouched": "2026-01-06T19:00:00+00:00", "lastTouched": "2026-01-06T19:00:00+00:00", "metrics": { - "parameter_count": { - "before": 2, - "after": 2 + "cognitive_complexity": { + "before": 13, + "after": 16 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -416,39 +421,34 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 13, - "after": 16 + "complexity": { + "before": 11, + "after": 13 + }, + "loc": { + "before": 12, + "after": 13 }, "max_nesting_depth": { "before": 2, "after": 2 }, - "complexity": { - "before": 11, - "after": 13 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 2, + "after": 2 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 12, - "after": 13 } }, "measured": true, "buckets": [ - "complex-and-changed", - "new-hotspot" + "complex-and-changed" ], "fileClass": "code", "hunks": [ @@ -491,19 +491,23 @@ "firstTouched": "2026-01-06T12:00:00+00:00", "lastTouched": "2026-01-06T16:00:00+00:00", "metrics": { - "parameter_count": { - "before": 1, - "after": 1 + "cognitive_complexity": { + "before": 3, + "after": 3 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -511,33 +515,29 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { + "complexity": { "before": 3, "after": 3 }, + "loc": { + "before": 6, + "after": 6 + }, "max_nesting_depth": { "before": 2, "after": 2 }, - "complexity": { - "before": 3, - "after": 3 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 1, + "after": 1 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 6, - "after": 6 } }, "measured": true, @@ -600,17 +600,17 @@ "firstTouched": "2026-01-06T13:00:00+00:00", "lastTouched": "2026-01-06T13:00:00+00:00", "metrics": { - "loc": { - "before": 10, - "after": 10 + "cognitive_complexity": { + "before": 1, + "after": 1 }, "complexity": { "before": 2, "after": 2 }, - "cognitive_complexity": { - "before": 1, - "after": 1 + "loc": { + "before": 10, + "after": 10 } }, "measured": true, @@ -643,19 +643,23 @@ "firstTouched": "2026-01-06T17:00:00+00:00", "lastTouched": "2026-01-06T17:00:00+00:00", "metrics": { - "parameter_count": { - "before": 1, - "after": 1 + "cognitive_complexity": { + "before": 4, + "after": 5 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -663,33 +667,29 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { + "complexity": { "before": 4, "after": 5 }, + "loc": { + "before": 8, + "after": 9 + }, "max_nesting_depth": { "before": 2, "after": 2 }, - "complexity": { - "before": 4, - "after": 5 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 1, + "after": 1 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 8, - "after": 9 } }, "measured": true, @@ -747,19 +747,23 @@ "firstTouched": "2026-01-06T10:00:00+00:00", "lastTouched": "2026-01-06T18:00:00+00:00", "metrics": { - "parameter_count": { - "before": 2, - "after": 2 + "cognitive_complexity": { + "before": 9, + "after": 24 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -767,33 +771,29 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 9, - "after": 24 + "complexity": { + "before": 5, + "after": 11 + }, + "loc": { + "before": 13, + "after": 18 }, "max_nesting_depth": { "before": 4, "after": 4 }, - "complexity": { - "before": 5, - "after": 11 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 2, + "after": 2 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 13, - "after": 18 } }, "measured": true, @@ -850,19 +850,23 @@ "firstTouched": "2026-01-06T14:00:00+00:00", "lastTouched": "2026-01-06T14:00:00+00:00", "metrics": { - "parameter_count": { - "before": 1, + "cognitive_complexity": { + "before": 3, "after": null }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": null }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": null }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": null + }, + "comment_noise_docblock": { "before": 0, "after": null }, @@ -870,33 +874,29 @@ "before": 0, "after": null }, - "cognitive_complexity": { + "complexity": { "before": 3, "after": null }, - "max_nesting_depth": { - "before": 2, + "loc": { + "before": 6, "after": null }, - "complexity": { - "before": 3, + "max_nesting_depth": { + "before": 2, "after": null }, - "comment_noise_commented_code": { - "before": 0, + "parameter_count": { + "before": 1, "after": null }, "todo_count": { "before": 0, "after": null }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": null - }, - "loc": { - "before": 6, - "after": null } }, "measured": true, @@ -937,31 +937,27 @@ "firstTouched": null, "lastTouched": null, "metrics": { - "parameter_count": { - "before": 2, + "cognitive_complexity": { + "before": 1, "after": 2 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { "before": 0, "after": 0 }, - "comment_noise_ratio": { + "comment_noise_docblock": { "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 1, - "after": 2 - }, - "max_nesting_depth": { + "comment_noise_ratio": { "before": 0, "after": 0 }, @@ -969,21 +965,25 @@ "before": 2, "after": 3 }, - "comment_noise_commented_code": { + "loc": { + "before": 3, + "after": 4 + }, + "max_nesting_depth": { "before": 0, "after": 0 }, + "parameter_count": { + "before": 2, + "after": 2 + }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 3, - "after": 4 } }, "measured": true, diff --git a/client/src/changelens/fixture.net.json b/client/src/changelens/fixture.net.json index e5790b13..bba40107 100644 --- a/client/src/changelens/fixture.net.json +++ b/client/src/changelens/fixture.net.json @@ -20,7 +20,8 @@ "timezone": "UTC", "includesWorktree": true, "notes": [], - "repoRoot": "/repo/change-lens-fixture" + "repoRoot": "/repo/change-lens-fixture", + "scope": "" }, "commits": [ { @@ -278,19 +279,23 @@ "firstTouched": "2026-01-06T19:00:00+00:00", "lastTouched": "2026-01-06T19:00:00+00:00", "metrics": { - "parameter_count": { + "cognitive_complexity": { "before": null, - "after": 2 + "after": 17 }, - "ts_type_interface_count": { + "comment_lines": { "before": null, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": null, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": null, + "after": 0 + }, + "comment_noise_docblock": { "before": null, "after": 0 }, @@ -298,33 +303,29 @@ "before": null, "after": 0 }, - "cognitive_complexity": { + "complexity": { "before": null, - "after": 17 + "after": 12 }, - "max_nesting_depth": { + "loc": { "before": null, - "after": 3 + "after": 22 }, - "complexity": { + "max_nesting_depth": { "before": null, - "after": 12 + "after": 3 }, - "comment_noise_commented_code": { + "parameter_count": { "before": null, - "after": 0 + "after": 2 }, "todo_count": { "before": null, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": null, "after": 0 - }, - "loc": { - "before": null, - "after": 22 } }, "measured": true, @@ -361,19 +362,23 @@ "firstTouched": "2026-01-06T19:00:00+00:00", "lastTouched": "2026-01-06T19:00:00+00:00", "metrics": { - "parameter_count": { - "before": 2, - "after": 2 + "cognitive_complexity": { + "before": 13, + "after": 16 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -381,39 +386,34 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 13, - "after": 16 + "complexity": { + "before": 11, + "after": 13 + }, + "loc": { + "before": 12, + "after": 13 }, "max_nesting_depth": { "before": 2, "after": 2 }, - "complexity": { - "before": 11, - "after": 13 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 2, + "after": 2 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 12, - "after": 13 } }, "measured": true, "buckets": [ - "complex-and-changed", - "new-hotspot" + "complex-and-changed" ], "fileClass": "code", "hunks": [ @@ -446,17 +446,17 @@ "firstTouched": "2026-01-06T13:00:00+00:00", "lastTouched": "2026-01-06T13:00:00+00:00", "metrics": { - "loc": { - "before": 10, - "after": 10 + "cognitive_complexity": { + "before": 1, + "after": 1 }, "complexity": { "before": 2, "after": 2 }, - "cognitive_complexity": { - "before": 1, - "after": 1 + "loc": { + "before": 10, + "after": 10 } }, "measured": true, @@ -483,19 +483,23 @@ "firstTouched": "2026-01-06T17:00:00+00:00", "lastTouched": "2026-01-06T17:00:00+00:00", "metrics": { - "parameter_count": { - "before": 1, - "after": 1 + "cognitive_complexity": { + "before": 4, + "after": 5 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -503,33 +507,29 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { + "complexity": { "before": 4, "after": 5 }, + "loc": { + "before": 8, + "after": 9 + }, "max_nesting_depth": { "before": 2, "after": 2 }, - "complexity": { - "before": 4, - "after": 5 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 1, + "after": 1 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 8, - "after": 9 } }, "measured": true, @@ -571,19 +571,23 @@ "firstTouched": "2026-01-06T10:00:00+00:00", "lastTouched": "2026-01-06T18:00:00+00:00", "metrics": { - "parameter_count": { - "before": 2, - "after": 2 + "cognitive_complexity": { + "before": 9, + "after": 24 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": 0 + }, + "comment_noise_docblock": { "before": 0, "after": 0 }, @@ -591,33 +595,29 @@ "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 9, - "after": 24 + "complexity": { + "before": 5, + "after": 11 + }, + "loc": { + "before": 13, + "after": 18 }, "max_nesting_depth": { "before": 4, "after": 4 }, - "complexity": { - "before": 5, - "after": 11 - }, - "comment_noise_commented_code": { - "before": 0, - "after": 0 + "parameter_count": { + "before": 2, + "after": 2 }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 13, - "after": 18 } }, "measured": true, @@ -661,19 +661,23 @@ "firstTouched": "2026-01-06T14:00:00+00:00", "lastTouched": "2026-01-06T14:00:00+00:00", "metrics": { - "parameter_count": { - "before": 1, + "cognitive_complexity": { + "before": 3, "after": null }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": null }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": null }, - "comment_noise": { + "comment_noise_commented_code": { + "before": 0, + "after": null + }, + "comment_noise_docblock": { "before": 0, "after": null }, @@ -681,33 +685,29 @@ "before": 0, "after": null }, - "cognitive_complexity": { + "complexity": { "before": 3, "after": null }, - "max_nesting_depth": { - "before": 2, + "loc": { + "before": 6, "after": null }, - "complexity": { - "before": 3, + "max_nesting_depth": { + "before": 2, "after": null }, - "comment_noise_commented_code": { - "before": 0, + "parameter_count": { + "before": 1, "after": null }, "todo_count": { "before": 0, "after": null }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": null - }, - "loc": { - "before": 6, - "after": null } }, "measured": true, @@ -742,31 +742,27 @@ "firstTouched": null, "lastTouched": null, "metrics": { - "parameter_count": { - "before": 2, + "cognitive_complexity": { + "before": 1, "after": 2 }, - "ts_type_interface_count": { + "comment_lines": { "before": 0, "after": 0 }, - "comment_noise_docblock": { + "comment_noise": { "before": 0, "after": 0 }, - "comment_noise": { + "comment_noise_commented_code": { "before": 0, "after": 0 }, - "comment_noise_ratio": { + "comment_noise_docblock": { "before": 0, "after": 0 }, - "cognitive_complexity": { - "before": 1, - "after": 2 - }, - "max_nesting_depth": { + "comment_noise_ratio": { "before": 0, "after": 0 }, @@ -774,21 +770,25 @@ "before": 2, "after": 3 }, - "comment_noise_commented_code": { + "loc": { + "before": 3, + "after": 4 + }, + "max_nesting_depth": { "before": 0, "after": 0 }, + "parameter_count": { + "before": 2, + "after": 2 + }, "todo_count": { "before": 0, "after": 0 }, - "comment_lines": { + "ts_type_interface_count": { "before": 0, "after": 0 - }, - "loc": { - "before": 3, - "after": 4 } }, "measured": true, diff --git a/client/src/changelens/layout.ts b/client/src/changelens/layout.ts index 8f221783..57cdc81c 100644 --- a/client/src/changelens/layout.ts +++ b/client/src/changelens/layout.ts @@ -17,7 +17,8 @@ export interface Size { } export interface GroupTile { - kind: "folder" | "file"; + /** `pool`: a file's smaller chunks drawn as one tile. */ + kind: "folder" | "file" | "pool"; /** Repo-relative path of the folder or file. */ path: string; /** Label: a collapsed chain reads `server/app/services`. */ @@ -72,7 +73,7 @@ export function flooredWeights(values: number[], area: number, minArea: number): interface TreeNode { name: string; path: string; - kind: "folder" | "file" | "leaf"; + kind: "folder" | "file" | "pool" | "leaf"; children?: TreeNode[]; leaf?: T; weight?: number; @@ -151,7 +152,7 @@ function settleSides(tree: TreeNode, size: Size) { let grew = false; for (const node of squarify(tree, size, 2).leaves()) { const side = Math.min(node.x1 - node.x0, node.y1 - node.y0); - if (node.data.kind !== "leaf" || side >= MIN_TILE_SIDE) continue; + if ((node.data.kind !== "leaf" && node.data.kind !== "pool") || side >= MIN_TILE_SIDE) continue; node.data.weight = (node.data.weight ?? 0) * Math.min(4, (MIN_TILE_SIDE + 1) / Math.max(side, 1)); grew = true; } @@ -165,28 +166,60 @@ const rectOf = (n: { x0: number; y0: number; x1: number; y1: number }): Rect => * Only edits. `scope` is the folder or file the map is zoomed to ("" for the * repo); `collapsed` holds the paths of the groups drawn as one tile. */ -export function layoutEdits(chunks: LensChunk[], size: Size, scope = "", collapsed: ReadonlySet = new Set(), minArea = MIN_TILE_AREA): EditsLayout { +export function layoutEdits( + chunks: LensChunk[], + size: Size, + scope = "", + collapsed: ReadonlySet = new Set(), + pooled: ReadonlySet = new Set(), + minArea = MIN_TILE_AREA +): EditsLayout { const shown = chunks.filter((c) => inScope(c.path, scope)); if (!shown.length || size.width <= 0 || size.height <= 0) return { groups: [], chunks: [] }; + // The floor applies to what is drawn: each open chunk, and each pool as one tile with its chunks' lines. // Group strips and padding take a share of the map, so aim the floor a little high. - const weights = flooredWeights(shown.map((c) => c.added + c.deleted), size.width * size.height * 0.8, minArea); + const lines = (c: LensChunk) => c.added + c.deleted; + const poolLines = new Map(); + const poolCount = new Map(); + for (const c of shown) + if (pooled.has(c.id)) { + poolLines.set(c.path, (poolLines.get(c.path) ?? 0) + lines(c)); + poolCount.set(c.path, (poolCount.get(c.path) ?? 0) + 1); + } + const open = shown.filter((c) => !pooled.has(c.id)); + const floored = flooredWeights([...open.map(lines), ...poolLines.values()], size.width * size.height * 0.8, minArea); + const openWeight = new Map(open.map((c, i) => [c.id, floored[i]])); + const poolWeight = new Map([...poolLines.keys()].map((path, i) => [path, floored[open.length + i]])); + const weights = shown.map((c) => openWeight.get(c.id) ?? (poolWeight.get(c.path)! * (lines(c) + 1)) / (poolLines.get(c.path)! + poolCount.get(c.path)!)); const byFile = new Map>(); + const pools = new Map>(); shown.forEach((chunk, i) => { let file = byFile.get(chunk.path); if (!file) byFile.set(chunk.path, (file = { name: chunk.path.split("/").pop() ?? chunk.path, path: chunk.path, kind: "file", children: [] })); - file.children!.push({ name: chunk.name, path: chunk.id, kind: "leaf", leaf: chunk, weight: weights[i] }); + const leaf: TreeNode = { name: chunk.name, path: chunk.id, kind: "leaf", leaf: chunk, weight: weights[i] }; + if (!pooled.has(chunk.id)) return void file.children!.push(leaf); + let pool = pools.get(chunk.path); + if (!pool) { + pools.set(chunk.path, (pool = { name: "more", path: poolPath(chunk.path), kind: "pool", children: [] })); + file.children!.push(pool); + } + pool.children!.push(leaf); }); const tree = folderTree(scope, [...byFile].map(([path, node]) => ({ path, node }))); const ids = new Map(); // A collapsed group becomes one leaf with the weight of everything under it. - const fold = (node: TreeNode): TreeNode => { - if (node.kind === "leaf") return node; - ids.set(node.path, leavesOf(node).map((c) => c.id)); - if (collapsed.has(node.path) && node.path !== scope) return { ...node, children: undefined, weight: weightOf(node) }; - return { ...node, children: node.children!.map(fold) }; + // A pool, or a group the user collapsed, becomes one leaf with the weight of everything under it. + // Pools fold before the sides settle, so a pool is widened as one tile; collapsed groups fold after, + // so collapsing keeps the area the open tiles had. + const fold = (node: TreeNode, which: (n: TreeNode) => boolean): TreeNode => { + if (node.kind === "leaf" || !node.children) return node; + if (!ids.has(node.path)) ids.set(node.path, leavesOf(node).map((c) => c.id)); + if (which(node) && node.path !== scope) return { ...node, children: undefined, weight: weightOf(node) }; + return { ...node, children: node.children.map((c) => fold(c, which)) }; }; - settleSides(tree, size); - const laid = squarify(fold(tree), size, 2); + const withPools = fold(tree, (n) => n.kind === "pool"); + settleSides(withPools, size); + const laid = squarify(fold(withPools, (n) => collapsed.has(n.path)), size, 2); const groups: GroupTile[] = []; const tiles: ChunkTile[] = []; @@ -200,6 +233,28 @@ export function layoutEdits(chunks: LensChunk[], size: Size, scope = "", collaps return { groups, chunks: tiles }; } +/** Open chunk tiles the map aims for, per px² of map: room for a name and a value in each. */ +export const TILE_BUDGET_AREA = MIN_TILE_AREA * 7; + +/** Path of the tile that pools a file's smaller chunks. */ +export const poolPath = (file: string) => `${file}#more`; + +/** + * The chunks to pool into one "N more" tile per file, so a window with + * hundreds of chunks stays readable. The chunks with the most churn stay + * open, up to the map's budget; a file keeps a pool only for two or more. + * Files in `expanded` pool nothing, and chunks in `keep` (ones the user selected) stay open. + */ +export function pooledChunks(chunks: LensChunk[], size: Size, scope = "", expanded: ReadonlySet = new Set(), keep: ReadonlySet = new Set()): Set { + const shown = chunks.filter((c) => inScope(c.path, scope)); + const budget = Math.max(12, Math.floor((size.width * size.height) / TILE_BUDGET_AREA)); + if (shown.length <= budget) return new Set(); + const ranked = [...shown].sort((a, b) => b.added + b.deleted - (a.added + a.deleted) || a.id.localeCompare(b.id)); + const byFile = new Map(); + for (const c of ranked.slice(budget)) if (!expanded.has(c.path) && !keep.has(c.id)) byFile.set(c.path, [...(byFile.get(c.path) ?? []), c.id]); + return new Set([...byFile.values()].filter((ids) => ids.length > 1).flat()); +} + // --- Show in repo ----------------------------------------------------------------- /** A file or folder of the repo map, with repo-relative paths. */ diff --git a/client/src/changelens/panel/ChunkInspector.tsx b/client/src/changelens/panel/ChunkInspector.tsx index ba6ca800..af5d40b7 100644 --- a/client/src/changelens/panel/ChunkInspector.tsx +++ b/client/src/changelens/panel/ChunkInspector.tsx @@ -31,6 +31,9 @@ function Section(props: { title: string; detail?: JSX.Element; children: JSX.Ele ); } +/** No change worth a row: equal sides, or a new or gone value of 0. */ +const quiet = (v: BeforeAfter) => v.before === v.after || (v.before ?? 0) === (v.after ?? 0); + function verdict(id: string, v: BeforeAfter): Verdict { if (v.before === null || v.after === null || v.before === v.after) return "same"; const dir = metricDef(id)?.direction; @@ -209,9 +212,21 @@ export function ChunkInspector(props: { when={metricRows().length} fallback={

No metrics for this kind of chunk.

} > - + id === "complexity" || !quiet(v))}> {([id, v]) => } + id !== "complexity" && quiet(v))}> + {(rest) => ( + +

+ Same on both sides:{" "} + {rest() + .map(([id, v]) => `${metricLabel(id)} ${formatMetricValue(id, (v.after ?? v.before)!)}`) + .join(" · ")} +

+
+ )} +

{c().naReason}

diff --git a/client/src/changelens/panel/ReviewBuckets.tsx b/client/src/changelens/panel/ReviewBuckets.tsx index 9e42b600..608f107d 100644 --- a/client/src/changelens/panel/ReviewBuckets.tsx +++ b/client/src/changelens/panel/ReviewBuckets.tsx @@ -131,7 +131,7 @@ export function ReviewBuckets(props: { payload: ChangeLensPayload; selected: str
{list(hotspots(), "No new hotspot.")}
diff --git a/client/src/changelens/panel/sample.ts b/client/src/changelens/panel/sample.ts index 9cad9324..5bb79516 100644 --- a/client/src/changelens/panel/sample.ts +++ b/client/src/changelens/panel/sample.ts @@ -391,7 +391,6 @@ export const samplePayload: ChangeLensPayload = { window: "branch", mode: "touched", ref: "HEAD", - repoRoot: "/repo/jobs-service", base: { ref: "merge-base(main, HEAD)", sha: sha("3f9a"), label: "main @ 3f9a3f9", date: "2026-11-17T14:02:00Z" }, head: { ref: WORKTREE, sha: null, label: "Working tree", date: null }, since: null, @@ -399,6 +398,8 @@ export const samplePayload: ChangeLensPayload = { timezone: "America/Chicago", includesWorktree: true, notes: [], + repoRoot: "/Users/you/projects/jobs", + scope: "", }, commits, chunks, diff --git a/client/src/changelens/sample.ts b/client/src/changelens/sample.ts deleted file mode 100644 index 1d860e12..00000000 --- a/client/src/changelens/sample.ts +++ /dev/null @@ -1,391 +0,0 @@ -// A hand-made Change Lens result for `?clmock=1`: one afternoon and morning of -// work on scan retries in srcly itself. It covers every chunk status, kind and -// match, a not-measured chunk, a reverted change, a merge and the working tree. -// The paths are real srcly files, so Show in repo lines up with the scan tree. - -import type { LensQuery } from "./api"; -import { - WORKTREE, - type BeforeAfter, - type ChangeLensPayload, - type ChunkKind, - type ChunkMatch, - type ChunkStatus, - type LensChunk, - type LensCommit, - type LensFile, - type LensHunkDiff, - type ReviewBucket, -} from "./types"; - -const TZ = "America/Chicago"; - -const COMMITS: Omit[] = [ - { sha: "a41c9e27d0b35f1c8e6a2b9d4f70c1e5a3b8d6f2", short: "a41c9e2", subject: "feat(scan): retry a file that timed out once", author: "Byron Wall", date: "2026-11-19T14:02:11-06:00" }, - { sha: "7be03d14c9a2e6f5b8d1037a6c4e9f2b5d8a1c3e", short: "7be03d1", subject: "test(scan): cover the retry path", author: "Byron Wall", date: "2026-11-19T14:31:40-06:00" }, - { sha: "c55f8a0e3b7d2c9f6a1e4b8d5c2f9a6e3b0d7c4a", short: "c55f8a0", subject: "refactor(scan): move the backoff helper to scan_workers", author: "Byron Wall", date: "2026-11-19T15:10:05-06:00" }, - { sha: "19d4e77a2c5f8b1e4d7a0c3f6b9e2d5a8c1f4b7e", short: "19d4e77", subject: "feat(scan): try a thread pool for retries", author: "Byron Wall", date: "2026-11-19T16:20:48-06:00" }, - { sha: "e02b6f4d8a1c5e9b3f7d2a6c0e4b8f1d5a9c3e7b", short: "e02b6f4", subject: 'Revert "feat(scan): try a thread pool for retries"', author: "Byron Wall", date: "2026-11-19T17:05:22-06:00" }, - { sha: "58aa3c1f7e2b9d4a6c0f3e8b1d5a7c9e2f4b6d8a", short: "58aa3c1", subject: "Merge branch 'progress-panel': show retried files", author: "Byron Wall", date: "2026-11-20T09:40:17-06:00" }, - { sha: "d9017bb3e6a2c8f4d0b5e1a7c3f9d6b2e8a4c0f5", short: "d9017bb", subject: "fix(scan): cap retries per job, add POST /scans/{id}/retry", author: "Byron Wall", date: "2026-11-20T10:15:33-06:00" }, - { sha: "3f6e2ad9c5b1e7a3d8f4c0b6e2a9d5f1c7b3e8a4", short: "3f6e2ad", subject: "docs: retry rules; rename budget.py to size_budget.py", author: "Byron Wall", date: "2026-11-20T11:02:09-06:00" }, - { sha: WORKTREE, short: "now", subject: "Uncommitted changes", author: "", date: null }, -]; -const [C1, C2, C3, C4, C5, C6, C7, C8] = COMMITS.map((c) => c.sha); - -/** path → [LOC at head (null: deleted), file class, status, old path]. */ -const FILES: Record = { - "server/app/services/scan_jobs.py": [480, "code"], - "server/app/services/scan_workers.py": [342, "code"], - "server/app/services/scan_progress.py": [39, "code"], - "server/app/services/size_budget.py": [90, "code", "renamed", "server/app/services/budget.py"], - "server/app/routers/scans.py": [133, "code"], - "server/tests/test_scan_jobs.py": [207, "test"], - "server/tests/test_scan_workers.py": [245, "test"], - "server/tests/test_scan_error_handling.py": [123, "test"], - "server/pyproject.toml": [60, "config"], - "server/uv.lock": [2140, "generated"], - "client/src/state/scanStore.ts": [251, "code"], - "client/src/services/scanJobs.ts": [205, "code"], - "client/src/utils/scanProgress.ts": [183, "code"], - "client/src/components/feedback/ScanProgress.tsx": [214, "code"], - "client/src/components/feedback/RetryBadge.tsx": [38, "code", "added"], - "scripts/dev-server.sh": [34, "config"], - "docs/adding-a-metric.md": [73, "docs"], - "README.md": [236, "docs"], -}; - -type Touch = [sha: string, added: number, deleted: number]; -type Pair = [before: number | null, after: number | null]; - -interface Spec { - path: string; - name: string; - /** Qualified name for the id, when it differs from the display name. */ - q?: string; - kind: ChunkKind; - lines: [number, number]; - base?: [number, number]; - status?: ChunkStatus; - match?: ChunkMatch; - oldPath?: string; - touches: Touch[]; - /** Lines that still differ at head; defaults to the touch total. */ - net?: [number, number]; - /** [complexity, cognitive, loc, nesting] pairs; omit a metric with `undefined`. */ - m?: [Pair?, Pair?, Pair?, Pair?]; - na?: string; - buckets?: ReviewBucket[]; -} - -const SCAN_JOBS = "server/app/services/scan_jobs.py"; -const SCAN_WORKERS = "server/app/services/scan_workers.py"; -const SCANS = "server/app/routers/scans.py"; -const TEST_JOBS = "server/tests/test_scan_jobs.py"; -const TEST_WORKERS = "server/tests/test_scan_workers.py"; -const STORE = "client/src/state/scanStore.ts"; -const JOBS_TS = "client/src/services/scanJobs.ts"; -const PROGRESS_TS = "client/src/utils/scanProgress.ts"; -const PANEL = "client/src/components/feedback/ScanProgress.tsx"; - -const SPECS: Spec[] = [ - // The handler the session kept coming back to: four commits, one of them reverted. - { path: SCAN_JOBS, name: "run", q: "ScanJob.run", kind: "function", lines: [372, 405], base: [372, 390], touches: [[C1, 14, 2], [C4, 9, 3], [C5, 3, 9], [C7, 6, 1]], net: [18, 3], m: [[6, 11], [8, 17], [19, 34], [2, 4]], buckets: ["new-hotspot"] }, - { path: SCAN_JOBS, name: "file_done", q: "ScanJob.file_done", kind: "function", lines: [334, 352], base: [334, 344], touches: [[C1, 9, 2], [C7, 3, 1]], net: [10, 2], m: [[12, 14], [15, 19], [11, 19], [3, 3]], buckets: ["complex-and-changed"] }, - { path: SCAN_JOBS, name: "start", q: "ScanJobManager.start", kind: "function", lines: [436, 466], touches: [[C7, 4, 1]], m: [[9, 9], [11, 11], [28, 31], [3, 3]] }, - { path: SCAN_JOBS, name: "cancel", q: "ScanJob.cancel", kind: "function", lines: [225, 227], status: "reverted", touches: [[C4, 5, 1], [C5, 1, 5]], net: [0, 0], m: [[2, 2], [1, 1], [3, 3], [1, 1]] }, - { path: SCAN_JOBS, name: "snapshot", q: "ScanJob.snapshot", kind: "function", lines: [193, 222], touches: [[C1, 3, 0], [C7, 2, 1]], net: [4, 0], m: [[5, 5], [4, 4], [27, 31], [2, 2]] }, - { path: SCAN_JOBS, name: "ScanJob", kind: "class", lines: [143, 182], touches: [[C1, 4, 0]], m: [undefined, undefined, [36, 40], undefined] }, - { path: SCAN_JOBS, name: "_legacy_retry", kind: "function", lines: [131, 142], status: "deleted", match: "none", touches: [[C3, 0, 12]], m: [[4, null], [5, null], [12, null], [2, null]] }, - - { path: SCAN_WORKERS, name: "_retry_backoff", kind: "function", lines: [118, 131], base: [47, 60], status: "moved", match: "moved", oldPath: SCAN_JOBS, touches: [[C1, 14, 0], [C3, 14, 14]], net: [0, 0], m: [[3, 3], [3, 3], [12, 12], [1, 1]] }, - { path: SCAN_WORKERS, name: "run_file_analyses", kind: "function", lines: [173, 322], base: [160, 296], touches: [[C1, 22, 6], [C4, 31, 4], [C5, 4, 31], [C7, 5, 2]], net: [24, 7], m: [[24, 27], [38, 44], [118, 131], [5, 5]], buckets: ["complex-and-changed"] }, - { path: SCAN_WORKERS, name: "_retry_pool", kind: "function", lines: [133, 133], status: "reverted", match: "none", touches: [[C4, 26, 0], [C5, 0, 26]], net: [0, 0], m: [[null, null], [null, null], [null, null], [null, null]] }, - { path: SCAN_WORKERS, name: "_worker_main", kind: "function", lines: [78, 113], touches: [[C1, 3, 1]], m: [[7, 7], [9, 9], [33, 35], [3, 3]] }, - - { path: "server/app/services/scan_progress.py", name: "ScanObserver", kind: "class", lines: [12, 39], base: [12, 33], touches: [[C1, 4, 0], [C6, 2, 0]], m: [undefined, undefined, [20, 26], undefined] }, - { path: "server/app/services/size_budget.py", name: "check", kind: "function", lines: [65, 90], status: "moved", match: "renamed-file", oldPath: "server/app/services/budget.py", touches: [[C8, 0, 0]], net: [0, 0], m: [[5, 5], [6, 6], [22, 22], [2, 2]] }, - - { path: SCANS, name: "retry_scan", kind: "function", lines: [84, 118], status: "added", match: "none", touches: [[C7, 35, 0]], m: [[null, 12], [null, 16], [null, 31], [null, 4]], buckets: ["new-hotspot"] }, - { path: SCANS, name: "get_scan", kind: "function", lines: [74, 79], touches: [[C7, 2, 1]], m: [[4, 5], [3, 4], [4, 5], [1, 2]] }, - { path: SCANS, name: "stream_scan", kind: "function", lines: [137, 168], touches: [[C6, 6, 2]], m: [[8, 9], [12, 13], [28, 32], [3, 3]] }, - - { path: TEST_JOBS, name: "test_retry_after_timeout", kind: "function", lines: [96, 121], status: "added", match: "none", touches: [[C2, 26, 0]], m: [[null, 2], [null, 1], [null, 22], [null, 1]] }, - { path: TEST_JOBS, name: "test_retry_cap", kind: "function", lines: [123, 139], status: "added", match: "none", touches: [[C7, 17, 0]], m: [[null, 1], [null, 0], [null, 14], [null, 0]] }, - { path: TEST_JOBS, name: "test_cancel_marks_job_cancelled", kind: "function", lines: [84, 94], touches: [[C2, 3, 1], [C4, 4, 0], [C5, 0, 4]], net: [3, 1], m: [[1, 1], [0, 0], [9, 11], [0, 0]] }, - { path: TEST_JOBS, name: "fake_scan", kind: "function", lines: [22, 49], touches: [[C2, 8, 2]], m: [[3, 4], [3, 5], [22, 28], [2, 2]] }, - { path: TEST_WORKERS, name: "test_pool_kills_hung_worker_and_keeps_going", kind: "function", lines: [52, 68], touches: [[C2, 5, 2]], m: [[2, 2], [1, 1], [11, 14], [1, 1]] }, - { path: TEST_WORKERS, name: "test_backoff_grows", kind: "function", lines: [246, 262], status: "added", match: "none", touches: [[C3, 17, 0]], m: [[null, 2], [null, 1], [null, 13], [null, 1]] }, - { path: "server/tests/test_scan_error_handling.py", name: "test_timeout_is_reported_once", kind: "function", lines: [88, 104], touches: [[C2, 6, 3]], m: [[1, 1], [0, 0], [12, 15], [0, 0]] }, - - { path: "server/pyproject.toml", name: "pyproject.toml", kind: "file", lines: [18, 24], touches: [[C7, 2, 1]], na: "Config file: no analyzer measures it" }, - { path: "server/uv.lock", name: "uv.lock", kind: "file", lines: [1204, 1262], touches: [[C7, 42, 17]], na: "Generated lock file: out of scope" }, - - { path: STORE, name: "createScanStore", kind: "function", lines: [53, 251], base: [53, 236], touches: [[C6, 19, 4], [WORKTREE, 6, 2]], net: [23, 5], m: [[18, 21], [26, 31], [171, 186], [4, 4]], buckets: ["complex-and-changed"] }, - { path: JOBS_TS, name: "watchScan", kind: "function", lines: [127, 205], touches: [[C6, 11, 3]], m: [[7, 8], [9, 11], [68, 76], [3, 3]] }, - { path: JOBS_TS, name: "ScanSnapshot", kind: "class", lines: [18, 42], touches: [[C6, 3, 0]], m: [undefined, undefined, [21, 24], undefined] }, - { path: JOBS_TS, name: "retryScan", kind: "function", lines: [102, 108], status: "added", match: "none", touches: [[C6, 7, 0]], m: [[null, 2], [null, 1], [null, 6], [null, 1]] }, - { path: PROGRESS_TS, name: "describeScan", kind: "function", lines: [93, 141], base: [93, 128], touches: [[C6, 15, 2], [WORKTREE, 4, 1]], net: [18, 3], m: [[5, 9], [6, 13], [33, 46], [2, 3]] }, - { path: PROGRESS_TS, name: "formatElapsed", kind: "function", lines: [55, 63], match: "uncertain", touches: [[C6, 6, 5]], m: [[3, 4], [2, 3], [7, 8], [1, 2]] }, - { path: PROGRESS_TS, name: "retryLabel", kind: "function", lines: [143, 151], status: "added", match: "none", touches: [[WORKTREE, 9, 0]], m: [[null, 2], [null, 1], [null, 8], [null, 1]] }, - { path: PANEL, name: "ScanProgress", kind: "function", lines: [41, 162], base: [41, 139], touches: [[C6, 27, 6], [WORKTREE, 5, 3]], net: [30, 7], m: [[8, 12], [11, 18], [92, 113], [3, 4]], buckets: ["new-hotspot"] }, - { path: PANEL, name: "FailedFileRow", kind: "function", lines: [164, 190], status: "deleted", match: "none", touches: [[C6, 0, 27]], m: [[4, null], [3, null], [24, null], [2, null]] }, - { path: "client/src/components/feedback/RetryBadge.tsx", name: "RetryBadge", kind: "function", lines: [9, 38], status: "added", match: "none", touches: [[C6, 30, 0]], m: [[null, 3], [null, 2], [null, 27], [null, 1]] }, - - { path: "scripts/dev-server.sh", name: "lines 17–24", q: "L17-24", kind: "range", lines: [17, 24], touches: [[C7, 3, 1]], na: "No analyzer reads shell scripts" }, - { path: "docs/adding-a-metric.md", name: "## Timeouts and retries", kind: "heading", lines: [56, 73], status: "added", match: "none", touches: [[C8, 18, 0]], m: [undefined, undefined, [null, 14], undefined] }, - { path: "README.md", name: "## How the analysis engine works", kind: "heading", lines: [120, 164], touches: [[C8, 7, 3]], m: [undefined, undefined, [38, 42], undefined] }, -]; - -const METRIC_IDS = ["complexity", "cognitive_complexity", "loc", "max_nesting_depth"]; - -const idOf = (s: Spec) => (s.kind === "file" ? s.path : `${s.path}::${s.q ?? s.name}`); -const dateOf = (sha: string) => COMMITS.find((c) => c.sha === sha)?.date ?? null; - -function build(spec: Spec, shas: Set, net: boolean): LensChunk | null { - const touches = spec.touches.filter(([sha]) => shas.has(sha)); - if (!touches.length) return null; - const status = spec.status ?? "modified"; - if (net && status === "reverted") return null; - const added = touches.reduce((n, t) => n + t[1], 0); - const deleted = touches.reduce((n, t) => n + t[2], 0); - const [netAdded, netDeleted] = touches.length === spec.touches.length && spec.net ? spec.net : status === "reverted" ? [0, 0] : [added, deleted]; - const metrics: Record = {}; - (spec.m ?? []).forEach((pair, i) => { - if (pair) metrics[METRIC_IDS[i]] = { before: pair[0], after: pair[1] }; - }); - const dates = touches.map(([sha]) => dateOf(sha)).filter((d): d is string => d !== null); - const fileClass = FILES[spec.path][1]; - return { - id: idOf(spec), - path: spec.path, - ...(spec.oldPath ? { oldPath: spec.oldPath } : {}), - kind: spec.kind, - name: spec.name, - startLine: spec.lines[0], - endLine: spec.lines[1], - ...(status !== "added" ? { baseStartLine: (spec.base ?? spec.lines)[0], baseEndLine: (spec.base ?? spec.lines)[1] } : {}), - status, - match: spec.match ?? "exact", - added: net ? netAdded : added, - deleted: net ? netDeleted : deleted, - netAdded, - netDeleted, - touches: net ? [] : touches.map(([sha, a, d]) => ({ sha, added: a, deleted: d })), - firstTouched: dates[0] ?? null, - lastTouched: dates[dates.length - 1] ?? null, - metrics, - measured: !spec.na, - ...(spec.na ? { naReason: spec.na } : {}), - buckets: fileClass === "code" ? (spec.buckets ?? []) : [], - fileClass, - hunks: (net ? [[null, netAdded, netDeleted] as const] : touches).map(([sha, a, d], i) => ({ - sha, - oldStart: (spec.base ?? spec.lines)[0] + i * 3, - oldLines: d + 6, - newStart: spec.lines[0] + i * 3, - newLines: a + 6, - })), - }; -} - -const short = (ref: string) => (ref.length > 12 ? ref.slice(0, 7) : ref); - -export function samplePayload(q: LensQuery): ChangeLensPayload { - const net = q.mode === "net"; - // The last day holds the merge, the fix, the docs commit and the working tree. - const window = q.window === "24h" ? COMMITS.slice(5) : COMMITS; - const shas = new Set(window.map((c) => c.sha)); - const chunks = SPECS.map((s) => build(s, shas, net)).filter((c): c is LensChunk => c !== null); - - const touchesBySha = new Map; added: number; deleted: number }>(); - for (const spec of SPECS) - for (const [sha, a, d] of spec.touches) { - const entry = touchesBySha.get(sha) ?? { ids: [], files: new Set(), added: 0, deleted: 0 }; - entry.ids.push(idOf(spec)); - entry.files.add(spec.path); - entry.added += a; - entry.deleted += d; - touchesBySha.set(sha, entry); - } - const live = new Set(chunks.map((c) => c.id)); - const commits: LensCommit[] = window.map((c) => { - const t = touchesBySha.get(c.sha)!; - return { ...c, files: t.files.size, added: t.added, deleted: t.deleted, chunkIds: t.ids.filter((id) => live.has(id)) }; - }); - - const byFile = new Map(); - for (const c of chunks) byFile.set(c.path, [...(byFile.get(c.path) ?? []), c]); - const files: LensFile[] = [...byFile].map(([path, list]) => { - const [loc, fileClass, status, oldPath] = FILES[path]; - return { - path, - ...(oldPath ? { oldPath } : {}), - status: status ?? "modified", - added: list.reduce((n, c) => n + c.added, 0), - deleted: list.reduce((n, c) => n + c.deleted, 0), - loc, - fileClass, - chunkIds: list.map((c) => c.id), - outOfScope: fileClass === "generated" || fileClass === "vendor", - }; - }); - - const first = window[0]; - const base = - q.window === "custom" && q.base - ? { ref: q.base, sha: "e17633fb2a9c4d5e6f708192a3b4c5d6e7f80910", label: `${short(q.base)} @ e17633f`, date: "2026-11-18T16:44:02-06:00" } - : q.window === "24h" - ? { ref: "e02b6f4^1", sha: C5, label: "e02b6f4", date: dateOf(C5) } - : q.window === "7d" - ? { ref: "a41c9e2^1", sha: "e17633fb2a9c4d5e6f708192a3b4c5d6e7f80910", label: "e17633f", date: "2026-11-18T16:44:02-06:00" } - : { ref: "merge-base(main, HEAD)", sha: "e17633fb2a9c4d5e6f708192a3b4c5d6e7f80910", label: "main @ e17633f", date: "2026-11-18T16:44:02-06:00" }; - const day = 24 * 3600 * 1000; - const until = "2026-11-21T08:30:00-06:00"; - const since = q.window === "custom" ? q.since || null : q.window === "branch" ? null : new Date(Date.parse(until) - (q.window === "24h" ? day : 7 * day)).toISOString(); - - return { - selection: { - window: q.window, - mode: q.mode, - ref: "scan-retries", - repoRoot: "/repo/srcly", - base, - head: q.window === "custom" && q.head ? { ref: q.head, sha: C8, label: `${short(q.head)} @ 3f6e2ad`, date: dateOf(C8) } : { ref: WORKTREE, sha: null, label: "Working tree", date: null }, - since, - until: q.window === "custom" ? q.until || null : q.window === "branch" ? null : until, - timezone: TZ, - includesWorktree: !(q.window === "custom" && q.head), - notes: [ - `History is read first-parent on scan-retries: merge 58aa3c1 counts once, as its diff against ${first.short === "58aa3c1" ? "e02b6f4" : "its first parent"}.`, - ...(net ? [] : ["2 chunks changed and were put back inside the window. They show as reverted."]).filter(() => q.window !== "24h"), - ], - }, - commits, - chunks, - files, - summary: { - filesEdited: files.length, - filesTotal: 1184, - chunks: chunks.length, - churnLines: chunks.reduce((n, c) => n + c.touches.reduce((m, t) => m + t.added + t.deleted, 0), 0) || chunks.reduce((n, c) => n + c.added + c.deleted, 0), - netLines: chunks.reduce((n, c) => n + c.netAdded + c.netDeleted, 0), - reverted: chunks.filter((c) => c.status === "reverted").length, - }, - metricIds: METRIC_IDS, - }; -} - -export function emptyPayload(q: LensQuery): ChangeLensPayload { - const full = samplePayload({ ...q, window: "branch" }); - const tip = { ref: "main", sha: "e17633fb2a9c4d5e6f708192a3b4c5d6e7f80910", label: "main @ e17633f", date: "2026-11-18T16:44:02-06:00" }; - return { - selection: { ...full.selection, window: q.window, mode: q.mode, ref: "main", base: { ...tip, ref: "origin/main", label: "origin/main @ e17633f" }, head: tip, includesWorktree: false, notes: ["main is level with origin/main, and the working tree is clean. There is nothing to show in this window."] }, - commits: [], - chunks: [], - files: [], - summary: { filesEdited: 0, filesTotal: 1184, chunks: 0, churnLines: 0, netLines: 0, reverted: 0 }, - metricIds: [], - }; -} - -const RUN_DIFF = `@@ -372,19 +372,34 @@ class ScanJob(ScanObserver): - def run(self) -> None: - """Analyze the tree in this thread; the manager owns the thread.""" - try: -- tree = scan_codebase(self.root_path, observer=self, cancel=self._cancel) -+ tree, timed_out = scan_codebase(self.root_path, observer=self, cancel=self._cancel) - except ScanCancelled: - self._finish(ScanPhase.CANCELLED) - return - except Exception as exc: # noqa: BLE001 - reported to the client - self._finish(ScanPhase.FAILED, error=str(exc)) - return -+ # One more pass over the files that hit the timeout: a cold cache or a -+ # busy machine explains most of them. -+ retried = 0 -+ for path in timed_out: -+ if self._cancel.cancelled or retried >= MAX_RETRIES_PER_JOB: -+ break -+ retried += 1 -+ self._update(retrying=path) -+ try: -+ node = analyze_with_timeout(path, timeout=self.timeout * _retry_backoff(retried)) -+ except AnalysisTimeout: -+ self._failures.append(_Failure(path, "timeout", "timed out twice")) -+ continue -+ if node is not None: -+ tree.replace_file(path, node) -+ self._update(retrying=None, retried=retried) - self._tree = tree - self._save_to_cache() - self._finish(ScanPhase.COMPLETE) -`; - -const RETRY_SCAN_DIFF = `@@ -81,0 +84,35 @@ def cancel_scan(job_id: str) -> dict: -+@router.post("/scans/{job_id}/retry") -+def retry_scan(job_id: str, req: RetryRequest) -> dict: -+ """Run the failed files of a finished scan again.""" -+ job = _job_or_404(job_id) -+ if not job.finished: -+ raise HTTPException(status_code=409, detail="The scan is still running") -+ if job.retried >= MAX_RETRIES_PER_JOB: -+ raise HTTPException(status_code=429, detail="This scan used all its retries") -+ paths = req.paths or [f.path for f in job.failures if f.reason == "timeout"] -+ if not paths: -+ return {"retried": 0, "snapshot": job.snapshot()} -+ for path in paths: -+ if not Path(path).is_file(): -+ raise HTTPException(status_code=404, detail=f"No such file: {path}") -+ done = 0 -+ for path in paths: -+ if job.retry_file(path): -+ done += 1 -+ elif req.stop_on_failure: -+ break -+ return {"retried": done, "snapshot": job.snapshot()} -`; - -const DOC_DIFF = `@@ -55,0 +56,18 @@ -+## Timeouts and retries -+ -+A file that passes the per-file timeout is analyzed once more, after every -+other file is done. The second try gets twice the time. -+ -+- A scan retries at most 25 files. The rest keep their fallback LOC. -+- A file that times out twice is reported as \`timeout\`, once. -+- A retry never changes a metric's meaning: \`N/A\` stays \`None\`, never 0. -`; - -const DIFFS: Record = { - [`${SCAN_JOBS}::ScanJob.run`]: RUN_DIFF, - [`${SCANS}::retry_scan`]: RETRY_SCAN_DIFF, - "docs/adding-a-metric.md::## Timeouts and retries": DOC_DIFF, -}; - -/** A stand-in diff for the chunks without a written one: the right shape and counts. */ -function fillerDiff(c: LensChunk, added: number, deleted: number): string { - const lines = [`@@ -${c.baseStartLine ?? c.startLine},${deleted + 2} +${c.startLine},${added + 2} @@ ${c.name}`, ` # ${c.name}: context`]; - for (let i = 0; i < deleted; i++) lines.push(`- old line ${i + 1} of ${c.name}`); - for (let i = 0; i < added; i++) lines.push(`+ new line ${i + 1} of ${c.name}`); - lines.push(" # context"); - return `${lines.join("\n")}\n`; -} - -export function sampleHunk(q: LensQuery, chunkId: string, commit?: string): LensHunkDiff { - const payload = samplePayload(q); - const chunk = payload.chunks.find((c) => c.id === chunkId); - if (!chunk) throw new Error(`No chunk ${chunkId} in this window`); - const step = commit ? payload.commits.find((c) => c.sha === commit) : undefined; - const touch = commit ? chunk.touches.find((t) => t.sha === commit) : undefined; - const reverted = !commit && chunk.status === "reverted"; - return { - chunkId, - path: chunk.path, - ...(chunk.oldPath ? { oldPath: chunk.oldPath } : {}), - from: step ? `${step.short}^` : payload.selection.base.label, - to: step ? (step.sha === WORKTREE ? "Working tree" : step.short) : payload.selection.head.label, - diff: reverted ? "" : !commit && DIFFS[chunkId] ? DIFFS[chunkId] : fillerDiff(chunk, touch?.added ?? chunk.netAdded, touch?.deleted ?? chunk.netDeleted), - truncated: false, - }; -} diff --git a/client/src/changelens/slots.tsx b/client/src/changelens/slots.tsx deleted file mode 100644 index f246046e..00000000 --- a/client/src/changelens/slots.tsx +++ /dev/null @@ -1,207 +0,0 @@ -// The four panel components of the Changes view, with the prop signatures of -// docs/intent/change-lens/contract.md. These are plain stand-ins: the real -// ones are in ./panel, and this file then only re-exports them. - -import { For, Show } from "solid-js"; -import { X } from "lucide-solid"; -import { Button } from "../components/ui/Button"; -import { IconButton } from "../components/ui/IconButton"; -import { metricLabel } from "../utils/metricsStore"; -import { beforeAfter, matchNote, plural, STATUS_LABEL } from "./labels"; -import { WORKTREE, type ChangeLensPayload, type LensChunk, type LensCommit, type LensHunkDiff, type ReviewBucket } from "./types"; - -const BUCKETS: { id: ReviewBucket; title: string; rule: string }[] = [ - { id: "complex-and-changed", title: "Already complex and changed", rule: "Complexity 10 or more at base, and the body changed" }, - { id: "new-hotspot", title: "New hotspot", rule: "Added or grew, and complexity is 10 or more now" }, -]; - -const Stat = (props: { added: number; deleted: number }) => ( - - +{props.added} −{props.deleted} - -); - -export function ReviewBuckets(props: { payload: ChangeLensPayload; selected: string | null; onSelect: (chunkId: string) => void }) { - const inBucket = (id: ReviewBucket) => props.payload.chunks.filter((c) => c.buckets.includes(id)); - return ( -
- - {(bucket) => ( -
-

- {bucket.title} - {inBucket(bucket.id).length} -

- None in this window
}> - {(chunk) => ( - - )} -
- - )} - -
- ); -} - -export function ChunkInspector(props: { - payload: ChangeLensPayload; - chunk: LensChunk | null; - onOpenHunk: (chunkId: string, commit?: string) => void; - onOpenCode: (chunk: LensChunk) => void; -}) { - const commit = (sha: string) => props.payload.commits.find((c) => c.sha === sha); - return ( - Select a chunk on the map to see what changed in it.
}> - {(chunk) => ( -
-
-
{chunk().name}
-
- {chunk().path}:{chunk().startLine}–{chunk().endLine} -
-
-
- {STATUS_LABEL[chunk().status]} - - - net +{chunk().netAdded} −{chunk().netDeleted} - -
- {(note) =>
{note()}
}
-
- - -
- Not measured: {chunk().naReason ?? "no analyzer reads this chunk"}
}> -
- - {(id) => ( - <> - {metricLabel(id)} - {beforeAfter(id, chunk().metrics[id]) ?? "not measured"} - - )} - -
- - -
-
Changed by {plural(chunk().touches.length, "commit")}
- - {(touch) => ( - - )} - -
-
-
- )} - - ); -} - -const LINE_CLASS: Record = { - "+": "bg-[var(--plc-success-subtle)]", - "-": "bg-[var(--plc-error-subtle)]", - "@": "text-[var(--plc-on-subtle)]", -}; - -export function HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; onClose: () => void }) { - return ( -
-
- {props.loading ? "Reading the diff…" : "Diff"}}> - {(d) => ( - <> - {d().path} - - {d().from} → {d().to} - - - )} - - - - -
-
- -
{props.error}
-
- - {(d) => ( - The two sides are equal: there is no diff.
}> -
- {(line) =>
{line || " "}
}
-
- -
The diff was clipped.
-
- - )} - -
-
- ); -} - -export function CommitRail(props: { commits: LensCommit[]; selected: string | null; onSelect: (sha: string | null) => void; highlightChunk?: string | null }) { - return ( -
- - {(commit) => { - const selected = () => props.selected === commit.sha; - const touches = () => Boolean(props.highlightChunk && commit.chunkIds.includes(props.highlightChunk)); - return ( - - ); - }} - -
- ); -} diff --git a/client/src/changelens/types.ts b/client/src/changelens/types.ts index 70dc20fc..90d7219e 100644 --- a/client/src/changelens/types.ts +++ b/client/src/changelens/types.ts @@ -1,5 +1,6 @@ // Change Lens payload contract. The server builds it in -// server/app/services/changelens/; docs/intent/change-lens/contract.md explains each field. +// server/app/services/changelens/ and mirrors these types in models.py. +// The window, chunk and bucket rules are in site/src/docs/pages/changes.md. // Field names are camelCase on the wire. export type LensWindow = "branch" | "24h" | "7d" | "custom"; @@ -38,6 +39,8 @@ export interface LensSelection { notes: string[]; /** Absolute path of the git repo. Every `path` in the payload is relative to it. */ repoRoot: string; + /** The analyzed folder inside the repo (`server/app`); "" when it is the repo root. Only files under it are read. */ + scope: string; } export interface LensCommit { diff --git a/docs/CODE_MAP.md b/docs/CODE_MAP.md index dd1ba7fe..494c7a67 100644 --- a/docs/CODE_MAP.md +++ b/docs/CODE_MAP.md @@ -43,7 +43,7 @@ Browser | --- | --- | | CLI entry point, arg parsing, port pick, browser open | `server/app/run.py` (`main`) | | Startup banner and `--version`: version, paths, client build, cache, data-flow engine, `SRCLY_*` overrides | `server/app/startup_info.py` | -| Headless commands (`scan`, `report`, `hotspots`, `explain`; `report --quadrant `) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` | +| Headless commands (`scan`, `report`, `hotspots`, `explain`, `changes`; `report --quadrant `) | `server/app/run.py` (`_run_headless`) → `server/app/services/reporting.py` | | `explain --at` scopes (folder rollups, file symbols, `file::symbol`, `file::name@line` for same-named symbols, a pasted `path:line name` start-at value), file classes (code/test/docs/style/fixture/…) that the findings queue and folder scores use; the `Analysis:` provenance line (reused or fresh scan, HEAD, uncommitted files, checker coverage) that `explain` and `report` print | `server/app/services/scopes.py` (`find`, `_at_line`, `provenance`, `provenance_line`); per-symbol branch shape (statements vs `&&`/`||`/`?:`, deepest lines, from the analyzer markers) and tests that import or name a file or symbol in `server/app/services/scope_evidence.py`; `server/app/services/file_classes.py`; CLI reuses the analysis cache in `reporting.py` (`scan_tree` sets the root's private `_analysis`); `report`'s printed summary in `run.py` (`_format_quiet_report_summary`) | | FastAPI app, CORS, static SPA mount | `server/app/main.py` | | Ctrl+C / SIGTERM: cancel running scans, then uvicorn shutdown | `server/app/main.py` (`lifespan`, `_install_scan_cancelling_signal_handlers`); CLI exit code in `server/app/run.py` (`main`) | @@ -117,6 +117,8 @@ Browser | `POST /api/dataflow/anchor-graph` | `routers/dataflow.py:anchor_graph` | A value's neighbourhood from any expression (`span` + `text`, or `name` + `line`), `direction` backward / forward / both; 404 for a name not on its line | | `GET /api/files/content` | `routers/files.py:get_file_content` | Raw file text; `ref=` reads it from a git commit (`git show`) | | `GET /api/files/markers` | `routers/files.py:get_file_markers` → `services/markers.py` | Lines behind each metric (`{metric: [{line, end_line, note}]}`) for the code viewer overlay; `ref=` as above | +| `GET /api/change-lens?path=&window=&mode=&ref=&base=&head=&since=&until=&worktree=` | `routers/changelens.py:get_change_lens` → `services/changelens/service.py:build_payload` | The window's commits, edited chunks and files (`ChangeLensPayload`); paths are relative to `selection.repoRoot`; 409 with a reason outside a Git repo | +| `GET /api/change-lens/hunk?path=&chunk=&commit=` (+ the same selection params) | `routers/changelens.py:get_change_lens_hunk` → `service.py:hunk_diff` | One chunk's unified diff, base → head or one commit's step (`commit` = sha or `WORKTREE`); 404 for an unknown chunk | | `GET /api/compare/refs` | `routers/compare.py:list_refs` | Branches + recent commits for the compare ref picker | | `GET /api/compare/sources?kind=prs\|worktrees\|branches` | `routers/compare.py:list_sources` → `services/compare/sources.py` | One picker section each (PRs with worktree/needs-fetch context, live worktrees newest first, branches with ahead/behind); a source that can't load returns `available: false` + reason | | `GET /api/compare/commits?base=&head=` | `routers/compare.py:get_commits` → `git_refs.list_commits` | First-parent commits in a range, oldest first, each with its first parent (commit stepper; capped at 100) | @@ -200,6 +202,25 @@ Ref picker rules: - A commit's result is cached by SHA. The stepper pre-warms the next commit, so stepping through a PR does not repeat cold scans. - Phase timings show where a slow first run spends its time. +### Change Lens (`?view=changes`, `srcly changes`) + +Which code chunks a branch or a time window edited. User guide: `site/src/docs/pages/changes.md` (window, touched/net, chunk and bucket rules). The payload contract is `client/src/changelens/types.ts`; the server's Pydantic models mirror it. + +| Feature | Where | +| --- | --- | +| `srcly changes [path]` (Markdown, `--json`) | `server/app/run.py` → `server/app/services/changelens/service.py` (`build_payload`, `render_markdown`) | +| Window resolution: first-parent history of `ref`, branch base (merge base, or the upstream tip on the default branch), 24h/7d/custom, 200-commit cap, shallow clones, working tree entry, the scan root's `scope` inside the repo | `server/app/services/changelens/window.py` (`resolve`) | +| Hunks per commit and base → head (`git diff -U0`), renames | `server/app/services/changelens/hunks.py` | +| Blob parsing with the scan's analyzers (one parse per side, by blob sha), Markdown headings, generated/vendored files | `server/app/services/changelens/blobs.py` | +| Chunks: hunk → innermost named scope, file/heading/range chunks, base ↔ head pairing (exact, renamed-file, moved, uncertain), touches, reverted, metrics before → after, review buckets (`COMPLEX_AT`) | `server/app/services/changelens/chunks.py` | +| Chunk-limited unified diff for one chunk | `server/app/services/changelens/textdiff.py`, `service.py` (`hunk_diff`) | +| Acceptance repo (every case of the issue) and the client's fixture payloads | `server/tests/fixtures/change_lens_repo.py` (`--write-payloads` writes `client/src/changelens/fixture*.json`), `server/tests/test_change_lens.py` | +| The view: fetches, URL state (`cw`, `cm`, `cl`, `cc`, `cs`, `clens`, custom refs), selection kept across results, repo ↔ scan paths | `client/src/changelens/ChangeLensView.tsx`, `api.ts`, `urlState.ts` | +| Toolbar: window presets and Custom form, Touched/Net, Only edits/In repo, color metric with Now/Δ | `client/src/changelens/WindowBar.tsx` | +| Maps: Only edits packing (floored area, pooled small chunks, collapse), In repo bands, tile states and the delta scale, legend | `client/src/changelens/LensMap.tsx`, `layout.ts`, `colors.ts`, `labels.ts`, `Legend.tsx` | +| Review panel (props only): `ReviewBuckets`, `ChunkInspector`, `HunkDiff`, `CommitRail`; dev harness `client/panel-harness.html` | `client/src/changelens/panel/` | +| Browser smoke on the acceptance repo | `client/e2e/changes.spec.ts` | + ### Client: app shell and first run | Feature | Where | diff --git a/docs/intent/change-lens/contract.md b/docs/intent/change-lens/contract.md deleted file mode 100644 index bb981047..00000000 --- a/docs/intent/change-lens/contract.md +++ /dev/null @@ -1,99 +0,0 @@ -# Change Lens: contract - -Source: [#397](https://github.com/byronwall/srcly/issues/397). This file is temporary. The last PR of the stack moves its lasting facts into `docs/CODE_MAP.md` and the site docs, and removes this folder. - -Change Lens answers three questions after a coding session: where the work happened, what changed in the shape of the code, and what to review first. A window changes which code is visible. - -The payload types are in `client/src/changelens/types.ts`. That file is the contract. The server's Pydantic models mirror it with camelCase aliases. - -## Endpoints - -### `GET /api/change-lens` - -| Param | Values | Default | -| --- | --- | --- | -| `path` | Absolute path of the analyzed folder (the scan root) | required | -| `window` | `branch`, `24h`, `7d`, `custom` | `branch` | -| `mode` | `touched`, `net` | `touched` | -| `ref` | Branch or revision whose history is read | `HEAD` | -| `base`, `head` | Revisions, for `custom` | none | -| `since`, `until` | ISO 8601 times, for `custom` | none | -| `worktree` | `1` or `0`: include staged and unstaged edits | `1` when `ref` is `HEAD` | - -Returns `ChangeLensPayload`. A folder that is not a git repo returns 409 with a reason. An empty window returns 200 with empty lists and a note. - -Every `path` in the payload is relative to `selection.repoRoot`. When `path` is a folder inside the repo, only files below it are read, and a note says so. - -### `GET /api/change-lens/hunk` - -`path`, the same selection params, `chunk` (a chunk id), and an optional `commit` (a sha or `WORKTREE`). Returns `LensHunkDiff`. Without `commit`, the diff runs from the selection's base to its head. With `commit`, it runs from that commit's first parent to the commit. - -The diff holds only the chunk's own lines. A symbol's diff compares its body on the two sides, so a moved symbol shows only what changed in it. It leaves out the changed lines of the named scopes nested in it: those are in the nested chunks' diffs. A `file` chunk's diff leaves out the lines inside named scopes. An unknown chunk id returns 404. So does a `commit` that is not in the selection; a sha of fewer than 7 characters returns 400. - -### `srcly changes [path]` - -Prints the same result as Markdown: the resolved selection, the review buckets, then the chunks grouped by folder, with `before → after` complexity. Flags: `--window`, `--mode`, `--ref`, `--base`, `--head`, `--since`, `--until`, `--no-worktree`, `--json`. - -## Time rules - -1. **One history.** Read `git log --first-parent `. A merge commit counts once, as its diff against its first parent. Activity from other branches never mixes in. Say this in `selection.notes` when the window holds a merge. A merge of the default branch into a feature branch is listed, but its diff is not read: those are upstream changes. A note names it. A merge that is itself on the default branch (a merged PR) is never an upstream merge. When the base is older than such a merge (a time window), "before" is the base with the merge's own diff applied, so neither mode counts what the merge brought in. If that diff overlaps the branch's own edits and cannot be applied, the base stays as it is and a note says so. -2. **Branch window.** Base is the merge-base of `ref` and the default branch, found the way `compare/git_refs.py` (`resolve_auto_base`) finds it. Head is `ref`. On the default branch itself, the base is the upstream tip (`origin/`); when that equals head, the window is empty and a note says so. -3. **Time windows.** Commits whose committer date is inside `[since, until]`. Base is the first parent of the oldest commit in the window. Head is the newest. `24h` and `7d` count back from now. A `since` later than `until` returns 400. A time window reads the newest 5,000 commits of the ref; a note says so when that limit cuts the window. -4. **Working tree.** Staged and unstaged edits are one entry, `WORKTREE`, after the last commit. It has no time. Untracked files count as added, unless srcly's ignore rules skip them. The entry exists only when the tree holds edits; then `selection.head` is the working tree. -5. **Touched against net.** Touched is the union of chunks that any commit in the window changed. Net compares the base snapshot with the head snapshot (the working tree, when included). A chunk that was changed and then put back has status `reverted` in touched mode and is absent in net mode. -6. **Shallow or incomplete history.** State it in `selection.notes`. Never guess a base. A window never reads past the oldest commit a shallow clone holds. -7. **Long windows.** A window keeps its newest 200 commits. The base moves to the parent of the oldest one kept, and a note says so. -8. **Files left out.** Binary files and files that srcly's ignore rules skip (lockfiles, `.json`, images) are not in the payload. A note gives their count. - -## Chunk rules - -1. Parse each changed file once per side (base and head) with the analyzer the scan uses for it. Parse the blob (`git show :`), not a checkout. Do not scan whole snapshots. A line ends at a newline only, as git counts lines: a lone CR, a form feed or U+2028 is content. -2. A hunk belongs to the innermost named scope that holds its lines: on the new side for added and changed lines, on the old side for deleted lines. Executable scopes win over display scopes. A callback or an object literal with no name belongs to the named scope around it, and so does an object under a key of such a literal. A nested named scope has a qualified name (`Outer.inner`, `Class.method`). Comment and decorator lines right above a scope belong to it, also when a class around the scope holds those lines. -3. Hunks outside every scope form one `file` chunk for that file. In Markdown, a hunk belongs to its nearest heading section (`heading`). In a file no analyzer reads (YAML, CSS, shell), hunks within 10 lines of each other form one `range` chunk; when such a file is added or deleted, it is one `file` chunk. An empty file that is added or deleted is one `file` chunk too, in both modes. A generated or vendored file is one `file` chunk and is not analyzed. -4. Never invent a symbol. A chunk with no analyzer has `measured: false`, an empty `metrics`, and a `naReason`. So do `heading` chunks and `file` chunks: no code metric applies to them. A file whose base or head does not parse (a syntax error at that end) gets no symbols: its hunks form `range` chunks (one `file` chunk when the file is added or deleted) with the `naReason` "Syntax error at head" or "at base", and a note names the file. -5. Pair head and base chunks by path and qualified name (`exact`). When one file holds a qualified name more than once (overloads, a getter and its setter), the scopes pair by body: identical bodies first, then the closest. Position in the file never decides, and the chunk has the key of its scope at head (`load`, `load#2`). When git reports a rename, pair by qualified name across the two paths (`renamed-file`). A symbol that left one file and appeared in another with a near-identical body is `moved` (same name, 90% of body lines equal). A line-number overlap alone is never a match. A weaker guess is `uncertain`: the same name with 60% to 90% equal, or a new name on an unchanged body in the same file (a renamed function, or a Markdown heading reworded above the same text). Unpaired chunks are `added` or `deleted`. -6. A file is followed through its renames. A file that a commit of the window added has no base, and a file that one deleted has no head, even when another file holds its path at that end. `files` lists each path once: a deleted file whose path a renamed file took shares that file's entry. A pure rename with an unchanged body has equal `before` and `after`. It is not an improvement or a regression. A file renamed with no edit is one `file` chunk with status `moved`, no changed lines, and file-level metrics (`loc`, max `complexity`) that are equal on both sides. -7. Deleted chunks stay in touched mode, with their base lines. A symbol added and removed inside the window is `reverted`, with no metrics. -8. Touches come from mapping each commit's hunks to the chunk through the file's symbols at that commit. `touches.length` is the number of commits that changed the chunk. -9. Use one analysis version for both sides. - -## Review buckets - -Buckets are plain rules. There is no single score. - -- `complex-and-changed`: the chunk existed at base with cyclomatic complexity of 10 or more, and its body changed. -- `new-hotspot`: the chunk is `added`, or its complexity rose, and its complexity at head is 10 or more. - -Test, docs, generated and vendor files get no bucket. The thresholds are constants in one place. - -## Client view - -Change Lens is the fourth view: `?view=changes`, beside Treemap, Graph and 2x2. Its code is in `client/src/changelens/`. URL params: `cw` (window), `cm` (mode), `cl` (layout: `edits` or `repo`), `cc` (selected commit), `cs` (selected chunk id), `cbase`, `chead`, `csince`, `cuntil`. - -- **Window bar** (in the view toolbar slot): the four presets, the Touched/Net switch, the Only edits/Show in repo switch. Below it, one status line shows the resolved base and head, the time limits and time zone, and each note. -- **Only edits:** a packed treemap of chunks grouped by folder, then file. Area is changed lines (`added + deleted`), with a floor so each chunk can be clicked. Folder labels read like `5 edited / 43 files · mostly tests`. Breadcrumbs and collapsible groups stay. -- **Show in repo:** the file map with area by file LOC. Untouched files are muted. Edited chunks keep an outline. -- **Lenses:** the color picker gains "Complexity delta" (a diverging scale) beside the current metrics. Added, deleted, moved, reverted and not-measured each have their own state, never a zero. A color change never changes the layout or the selection. -- **Panel** (`client/src/changelens/panel/`): `ReviewBuckets`, `ChunkInspector` (before → after for each metric, the touch strip, churn against net), `HunkDiff`, `CommitRail`. - -Panel components take data through props only. They do not fetch, and they do not read the navigation store. The view owns state and passes it in: - -```ts -// client/src/changelens/panel/index.ts -ReviewBuckets(props: { payload: ChangeLensPayload; selected: string | null; onSelect: (chunkId: string) => void }) -ChunkInspector(props: { payload: ChangeLensPayload; chunk: LensChunk | null; onOpenHunk: (chunkId: string, commit?: string) => void; onOpenCode: (chunk: LensChunk) => void }) -HunkDiff(props: { diff: LensHunkDiff | null; loading: boolean; error?: string; onClose: () => void }) -CommitRail(props: { commits: LensCommit[]; selected: string | null; onSelect: (sha: string | null) => void; highlightChunk?: string | null }) -``` - -## Acceptance fixture - -`server/tests/fixtures/change_lens_repo.py` builds a small git repo in a temp folder, with fixed commit dates. Its branch holds: one edit to one function in a large file; three edits to the same function; a change that a later commit reverts; a pure file rename; a deleted function; a config hunk and a Markdown hunk; a new function with high complexity; and an uncommitted edit. - -The tests and the browser proof check that: - -- Only edits hides untouched chunks, keeps breadcrumbs, and opens the right diff. -- Reverted work shows in Touched and not in Net. The pure rename reports no complexity change. -- A color change keeps layout and selection. A switch to Show in repo keeps the selection. -- Before → after values come from the same analysis inputs. Unsupported metrics and unresolved matches say so. -- The UI never names an agent as the author of a read or an edit. diff --git a/server/app/services/changelens/__init__.py b/server/app/services/changelens/__init__.py index b5927ea0..095a33be 100644 --- a/server/app/services/changelens/__init__.py +++ b/server/app/services/changelens/__init__.py @@ -1 +1 @@ -"""Change Lens: the code chunks a window of git history edited (``docs/intent/change-lens/contract.md``).""" +"""Change Lens: the code chunks a window of git history edited (rules: ``site/src/docs/pages/changes.md``).""" diff --git a/server/app/services/changelens/chunks.py b/server/app/services/changelens/chunks.py index ef0dc343..846d9939 100644 --- a/server/app/services/changelens/chunks.py +++ b/server/app/services/changelens/chunks.py @@ -547,7 +547,7 @@ def _slice(store: BlobStore, ref: Optional[BlobRef], scope: Optional[Scope]) -> def _metrics(before: Optional[dict], after: Optional[dict]) -> dict[str, BeforeAfter]: out = {} - for name in dict.fromkeys([*(before or {}), *(after or {})]): + for name in sorted({*(before or {}), *(after or {})}): pair = BeforeAfter(before=(before or {}).get(name), after=(after or {}).get(name)) if pair.before is not None or pair.after is not None: out[name] = pair @@ -563,7 +563,8 @@ def _buckets(chunk: LensChunk) -> list[str]: changed = chunk.net_added + chunk.net_deleted > 0 if before is not None and after is not None and before >= COMPLEX_AT and changed: out.append("complex-and-changed") - if after is not None and after >= COMPLEX_AT and (chunk.status == "added" or (before is not None and after > before)): + # A new hotspot crossed the line in this window: absent or below it at base, at or above it at head. + if after is not None and after >= COMPLEX_AT and (before is None or before < COMPLEX_AT): out.append("new-hotspot") return out diff --git a/server/app/services/changelens/models.py b/server/app/services/changelens/models.py index a2110dee..4e732dc8 100644 --- a/server/app/services/changelens/models.py +++ b/server/app/services/changelens/models.py @@ -57,6 +57,7 @@ class LensSelection(LensModel): includes_worktree: bool notes: list[str] repo_root: str + scope: str class LensCommit(LensModel): diff --git a/server/app/services/changelens/service.py b/server/app/services/changelens/service.py index 4141fa1e..4d97d87f 100644 --- a/server/app/services/changelens/service.py +++ b/server/app/services/changelens/service.py @@ -123,6 +123,7 @@ def build_payload(path: Path, params: Params) -> dict: includes_worktree=built.has_worktree, notes=notes, repo_root=str(window.repo), + scope=window.scope, ) chunks = built.chunks payload = ChangeLensPayload( diff --git a/server/app/services/changelens/window.py b/server/app/services/changelens/window.py index 511f0aaa..bb70544c 100644 --- a/server/app/services/changelens/window.py +++ b/server/app/services/changelens/window.py @@ -178,6 +178,11 @@ def _shallow_boundary(repo: Path) -> set[str]: return set() +def _label(name: str, sha: str) -> str: + """`main @ e17633f`; a bare sha reads as its short form only.""" + return sha[:7] if sha.startswith(name) and len(name) >= 7 else f"{name} @ {sha[:7]}" + + def resolve(path: Path, params: Params) -> Window: try: repo = repo_root(path) @@ -193,7 +198,7 @@ def resolve(path: Path, params: Params) -> Window: tip_ref = params.head if params.window == "custom" and params.head else params.ref tip_sha = _sha(repo, tip_ref) tip_name = branch_of(repo, tip_ref) or tip_ref - tip = Endpoint(tip_ref, tip_sha, f"{tip_name} @ {tip_sha[:7]}", _commit_ts(repo, tip_sha)) + tip = Endpoint(tip_ref, tip_sha, _label(tip_name, tip_sha), _commit_ts(repo, tip_sha)) wants_worktree = params.worktree if params.worktree is not None else tip_sha == head_commit if wants_worktree and tip_sha != head_commit: @@ -220,7 +225,7 @@ def resolve(path: Path, params: Params) -> Window: elif params.window == "custom": if params.base: base_sha = _sha(repo, params.base) - window.base = Endpoint(params.base, base_sha, f"{branch_of(repo, params.base) or params.base} @ {base_sha[:7]}", _commit_ts(repo, base_sha)) + window.base = Endpoint(params.base, base_sha, _label(branch_of(repo, params.base) or params.base, base_sha), _commit_ts(repo, base_sha)) window.commits = _log(repo, f"{base_sha}..{tip_sha}")[::-1] if not _is_ancestor(repo, base_sha, tip_sha): notes.append( diff --git a/server/tests/fixtures/change_lens_repo.py b/server/tests/fixtures/change_lens_repo.py index 66c27d10..fcf39b88 100644 --- a/server/tests/fixtures/change_lens_repo.py +++ b/server/tests/fixtures/change_lens_repo.py @@ -1,4 +1,4 @@ -"""The Change Lens acceptance repo (docs/intent/change-lens/contract.md, "Acceptance fixture"). +"""The Change Lens acceptance repo (issue #397, "Small acceptance fixture"). ``build(folder)`` makes a git repo with a ``main`` commit and a ``feature`` branch whose commits hold each case the contract names. Dates, names and diff --git a/server/tests/test_change_lens.py b/server/tests/test_change_lens.py index 0601ad93..1d0f2d23 100644 --- a/server/tests/test_change_lens.py +++ b/server/tests/test_change_lens.py @@ -1,4 +1,4 @@ -"""Change Lens on the acceptance repo (docs/intent/change-lens/contract.md).""" +"""Change Lens on the acceptance repo (rules: site/src/docs/pages/changes.md).""" from __future__ import annotations @@ -119,7 +119,10 @@ def test_review_buckets(touched): plan = chunks["src/planner.ts::planRoute"] assert plan["status"] == "added" and plan["buckets"] == ["new-hotspot"] assert plan["metrics"]["complexity"] == {"before": None, "after": plan["metrics"]["complexity"]["after"]} - assert "complex-and-changed" in chunks["src/router.ts::dispatch"]["buckets"] + # dispatch was already at the line and rose: it is complex and changed, not a new hotspot. + dispatch = chunks["src/router.ts::dispatch"] + assert dispatch["metrics"]["complexity"]["before"] >= 10 + assert dispatch["buckets"] == ["complex-and-changed"] assert chunks["src/worker.ts::retryJob"]["buckets"] == ["new-hotspot"] assert chunks["src/worker.ts::parseArgs"]["buckets"] == [] diff --git a/site/public/screenshots/README.md b/site/public/screenshots/README.md index 165876c4..bd0ecc41 100644 --- a/site/public/screenshots/README.md +++ b/site/public/screenshots/README.md @@ -13,4 +13,5 @@ Each JPEG is 2160 × 1350 pixels: a 1440 × 900 viewport at 1.5x, quality 82. - `graph.jpg`: the import graph around `client/src/viz/treemap`. - `compare.jpg`: compare mode for commit `5a8a9c38` (symbols dead and hub overlays). - `symbols.jpg`: Symbols mode centered on `NotePage`. +- `changes.jpg`: the Changes view over a fixed range (`e17633f` to the capture revision), with `parseLocation` selected. It was first captured with `--ref` on the Change Lens branch, before the view reached `main`. - `data-flow.jpg`: the `/notes/[id]` trace from `NotePage`, with where it stops. diff --git a/site/public/screenshots/changes.jpg b/site/public/screenshots/changes.jpg new file mode 100644 index 00000000..c9752cfb Binary files /dev/null and b/site/public/screenshots/changes.jpg differ diff --git a/site/scripts/capture.mjs b/site/scripts/capture.mjs index 5b209936..8a3a1e3e 100644 --- a/site/scripts/capture.mjs +++ b/site/scripts/capture.mjs @@ -136,6 +136,11 @@ const views = [ name: "compare", url: app(clone, { view: "treemap", compare: "5a8a9c38~1..5a8a9c38" }), delay: 3000, timeout: 600_000, steps: async (page) => page.getByText("Risk metrics", { exact: true }).first().waitFor(), }, + { + // Change Lens over the commits that built it: a fixed range, so a rerun next month still has edits. + name: "changes", url: app(clone, { view: "changes", cw: "custom", cbase: "e17633f", cs: "client/src/navigation/location.ts::parseLocation" }), + ready: '[data-change-lens][data-lens-state="ready"]', delay: 1500, + }, { name: "symbols", url: app(fixture, { view: "graph", symbols: "src/routes/notes/[id].tsx#NotePage" }), delay: 4000 }, { name: "data-flow", url: app(fixture, { view: "graph", anchor: "src/routes/notes/[id].tsx@NotePage:6", dir: "forward" }), ready: "text=Where the trace stops", delay: 2000 }, ]; diff --git a/site/scripts/prerender.mjs b/site/scripts/prerender.mjs index 036765ca..55e00a0b 100644 --- a/site/scripts/prerender.mjs +++ b/site/scripts/prerender.mjs @@ -76,7 +76,7 @@ const absolute = (markdown) => markdown .replace(/\]\(\.\.\/([a-z0-9-]+)\/?(#[^)]+)?\)/gi, (_m, slug, hash = "") => `](${origin}${base}docs/${slug}/${hash})`) .replace(/\]\(\/srcly\//g, `](${origin}${base}`); const guides = []; -const order = ["overview", "tour", "design", "get-started", "explore", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; +const order = ["overview", "tour", "design", "get-started", "explore", "changes", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; const slugs = (await readdir("src/docs/pages")).filter((name) => name.endsWith(".md")).map((name) => name.slice(0, -3)); assert.deepEqual([...slugs].sort(), [...order].sort(), "Add new guides to the llms.txt order"); for (const slug of order) { diff --git a/site/src/App.tsx b/site/src/App.tsx index 5e7ca95d..e00d6b08 100644 --- a/site/src/App.tsx +++ b/site/src/App.tsx @@ -13,6 +13,7 @@ export const pages = [ { slug: 'design', title: 'Design decisions', description: 'Learn what Srcly measures, how it presents evidence, and where its limits are.' }, { slug: 'get-started', title: 'Get started', description: 'Install Srcly and analyze your first codebase.' }, { slug: 'explore', title: 'Explore a codebase', description: 'Navigate the treemap, hotspots, explorer, and code view.' }, + { slug: 'changes', title: 'Review changes', description: 'See the code a branch or a time window edited, and what to review first.' }, { slug: 'metrics', title: 'Metrics', description: 'Understand metric values, scope, and coverage.' }, { slug: 'findings', title: 'Findings', description: 'Read checker findings and understand what Srcly measured.' }, { slug: 'data-flow', title: 'Data flow', description: 'Trace TypeScript, JavaScript, and Python values through the codebase.' }, @@ -23,7 +24,7 @@ export const pages = [ const groups = [ { title: 'Discover', slugs: ['overview', 'tour', 'design'] }, - { title: 'Use Srcly', slugs: ['get-started', 'explore', 'metrics', 'findings', 'data-flow'] }, + { title: 'Use Srcly', slugs: ['get-started', 'explore', 'changes', 'metrics', 'findings', 'data-flow'] }, { title: 'Automate & configure', slugs: ['reports', 'cli', 'configuration'] }, ]; const base = import.meta.env.BASE_URL; diff --git a/site/src/docs/pages/changes.md b/site/src/docs/pages/changes.md new file mode 100644 index 00000000..20d7ab24 --- /dev/null +++ b/site/src/docs/pages/changes.md @@ -0,0 +1,93 @@ +# Review changes + +The **Changes** view shows the code a window of Git history edited. Use it after a coding session to answer three questions: where did the work happen, what changed in the shape of the code, and what should you review first. A window changes which code is visible. It does not recolor a map of the whole repository. + +
The Changes view of Srcly's own repository, with parseLocation selected
The commits that built Change Lens. The map shows only edited chunks, grouped by folder and file. parseLocation is selected: its complexity went from 47 to 52, so it is in Already complex and changed.
+ +## Open the view + +1. Analyze a folder inside a Git repository. +2. Select **Changes** beside Treemap, Graph and 2×2. +3. Pick a window: **This branch**, **24 hours**, **7 days**, or **Custom**. +4. Select a chunk on the map or in the review lists, then select **Open diff**. + +The status line under the toolbar shows the resolved base and head, the number of commits, the time limits with the time zone, and any notes. Read it first: it tells you exactly which history you are looking at. + +The view reads the checked-out branch. Staged and unstaged edits are included as one **Working tree** entry after the last commit. To read other revisions, use **Custom** and enter a base and a head (a branch, tag or sha), or a time range. + +## Windows + +- **This branch** compares the branch with the commit where it left the default branch (the merge base). On the default branch itself, the base is the upstream tip. When the two are equal, the window is empty and a note says so. +- **24 hours** and **7 days** read the commits whose committer date falls in that time, counted back from now. The base is the first parent of the oldest commit in the window. +- **Custom** takes two revisions, a time range, or both. + +Srcly reads one history: the first-parent log of the branch. A merge commit counts once, as its diff against its first parent, so merged work is never counted twice and other branches never mix in. A merge of the default branch into your branch is listed but not read, because those are upstream changes. A note names it. When the base is older than such a merge, "before" is the base with that merge's changes applied, so upstream work never reads as yours. If the merge overlaps your own earlier edits, the base stays as it is and a note says so. On the default branch itself, no merge is an upstream merge. + +A window keeps its newest 200 commits. A time window reads at most the newest 5,000 commits to find its start, and a note says when that cuts it short. In a shallow clone, Srcly never reads past the oldest commit the clone holds, and a note says so. Binary files and files that Srcly's ignore rules skip (lockfiles, `.json`, images) are left out, and a note gives their count. + +## Touched and Net + +**Touched** is the default. It shows every chunk that any commit in the window changed. **Net** compares the base snapshot with the head snapshot. + +The two differ when work was tried and put back. A function that a commit changed and a later commit restored is **reverted** in Touched: it is drawn with dots and a ↺ mark. In Net it is gone, because the base and the head are equal. Use Touched to see where the session went. Use Net to review what will land. + +## What a chunk is + +A chunk is the unit the map draws. Srcly parses each changed file on both sides with the same analyzer the scan uses, then groups hunks this way: + +- A hunk belongs to the innermost named function, method or class that holds its lines. A callback or object literal with no name belongs to the named scope around it. Nested names are qualified, such as `Class.method`. +- Comment and decorator lines right above a function or method belong to it, not to the class around it. +- Hunks outside every named scope form one file-level chunk for that file. +- In Markdown, a hunk belongs to its nearest heading section. +- In a file no analyzer reads (YAML, CSS, shell), nearby hunks form one line-range chunk. +- A generated or vendored file is one chunk and is not analyzed. So is an empty file that was added or deleted. +- A file that does not parse at the base or the head gets no symbols. Its chunks say **Syntax error**, and a note names the file. + +Srcly never invents a symbol. A chunk with no analyzer says **not measured**, never 0. So do heading and file-level chunks: no code metric applies to them. + +Head and base chunks pair by path and name. When Git reports a renamed file, they pair by name across the two paths. Two scopes with the same name in one file pair by body: identical first, then closest. A symbol that left one file and appeared in another with a near-identical body is **moved**. A weaker guess is labeled **uncertain**, and so is a Markdown heading that was reworded above the same text. A file added in the window has no base, even when a renamed file held that path before. A line-number overlap alone is never a match. A pure rename with an unchanged body has equal before and after values: it is not an improvement or a regression. + +## Read the map + +**Only edits** packs the edited chunks together, grouped by folder and then file. Tile area is changed lines, with a floor so a one-line edit can still be selected. A folder label reads like `5 edited / 43 files · mostly tests`. Select a folder or file name to zoom; use the breadcrumbs to go back up. The chevron folds a group into one tile without moving its neighbours. + +In a long window, each file keeps its largest chunks open and pools the smaller ones into one **N more** tile. Select a pool to open it. A chunk you select from a list leaves its pool. + +**In repo** returns to the familiar file map, sized by file LOC. Untouched files are muted, and each edited chunk is a band at its lines in its file. The selection stays when you switch. + +The **Color** menu picks a metric and **Now** (the value at head) or **Δ** (the change in the window). Delta uses a diverging scale: blue fell, orange rose. Added, deleted, moved, reverted and not-measured chunks each have their own fill and mark. A color change keeps the layout and the selection. + +## Review first + +The panel lists two review buckets. They are plain rules, not a score: + +- **Already complex and changed**: the chunk had cyclomatic complexity of 10 or more at base, and its body changed. +- **New hotspot**: the chunk crossed the line in the window. Its complexity is 10 or more at head, and at base it was below 10 or the chunk did not exist. A chunk that was already at 10 or more is only in the first bucket. + +Test, docs, generated and vendored files get no bucket. **All edits** lists every chunk, most lines churned first, with status and file-class filters. + +## Inspect a chunk + +The inspector shows the chunk's status, where it is, and each metric as base → head. Metrics that did not change fold into one line. **Touches** places one mark per commit that changed the chunk on the window's timeline, with churned lines against net lines. Six edits to one handler and one edit each to six handlers are different stories, and this is where you see which one you have. + +**Open diff** shows only the chunk's own lines. Changed lines of a nested named scope are in that scope's diff, not in its parent's. A symbol's diff compares its body on the two sides, so a moved symbol shows only what changed in it. Select a touch mark to see that one commit's diff. + +## Step through commits + +The commit rail under the map shows the window's commits on a compressed time axis, sized by lines changed. Commits that touched the selected chunk are highlighted. Select a commit to dim every chunk it did not change. With a commit selected, **Open diff** shows that commit's hunk. Select **All** or the commit again to clear it. The left and right arrow keys step through commits. + +## From the command line + +`srcly changes` prints the same result as Markdown: the resolved selection, the review buckets, then the chunks grouped by folder with before → after complexity. + +```bash +uvx srcly changes +uvx srcly changes . --window 7d --mode net +uvx srcly changes . --window custom --base main --head my-branch --json +``` + +See [Command line](../cli/) for every flag. + +## What it does not claim + +The view shows commits and local edits. It does not show who read a file or which tool made an edit, and it never credits an agent with a read or an edit. A complexity change is a structural signal to inspect, not a verdict on the change. diff --git a/site/src/docs/pages/cli.md b/site/src/docs/pages/cli.md index ca9a1b71..bec6eaa0 100644 --- a/site/src/docs/pages/cli.md +++ b/site/src/docs/pages/cli.md @@ -66,6 +66,20 @@ uvx srcly compare --dataflow Unavailable measurements stay null. If a file is measured on one side only, Srcly records a coverage change and does not count the missing value as a zero delta. A file absent from one dependency graph has unknown fan-in and fan-out. +## Review recent changes + +`changes` prints the code chunks a window of Git history edited, as Markdown: the resolved base and head, the review buckets, then the chunks grouped by folder with before → after complexity. It is the text form of the app's **Changes** view. + +```bash +uvx srcly changes +uvx srcly changes . --window 7d +uvx srcly changes . --window branch --mode net --json +uvx srcly changes . --window custom --base main --head my-branch +uvx srcly changes . --window custom --since 2026-11-01T00:00:00 --until 2026-11-08T00:00:00 +``` + +`--window` is `branch` (the default: this branch against its merge base), `24h`, `7d`, or `custom` with `--base`/`--head` or `--since`/`--until`. `--mode touched` (the default) lists every chunk a commit changed, with reverted work; `--mode net` compares the base and head snapshots only. `--ref` picks the branch whose first-parent history is read. Uncommitted edits are included when the head is the checked-out commit; `--no-worktree` leaves them out. `--json` prints the same payload the app reads. See [Review changes](../changes/) for the window, chunk and bucket rules. + ## Fix and check `fix` prints a diff of supported mechanical fixes. It applies changes only with `--write`: diff --git a/site/src/docs/pages/tour.md b/site/src/docs/pages/tour.md index 1a291d00..572a7a16 100644 --- a/site/src/docs/pages/tour.md +++ b/site/src/docs/pages/tour.md @@ -42,7 +42,15 @@ Use Data flow when you have a supported route or symbol and want to follow model
Partial route trace for /notes/[id] in Srcly's included symbol-graph example
The /notes/[id] route trace in the included symbol-graph example is anchored at NotePage. It is partial: one callback handoff has no call sites to pair its values. Inspect the unproven handoff before relying on the path.
-## 5. Repeat the investigation in a terminal +## 5. Review what a session changed + +After a coding session, select **Changes** and pick **This branch**, **24 hours** or **7 days**. The map shows only the functions, sections and line ranges that the window edited, grouped by folder and file. Tile area is changed lines, so one edited handler in a 2,000-line file gets the footprint of that handler. The panel lists what to review first by plain rules: chunks that were already complex and changed, and chunks that crossed the complexity line. Select a chunk to see its before → after values and the commits that touched it, then open its diff. + +
The Changes view of Srcly's own repository, with parseLocation selected
The Changes view over the commits that built it. parseLocation went from complexity 47 to 52 and leads the review list.
+ +Switch **Touched** to **Net** to drop work that was tried and put back. See [Review changes](../changes/) for the window and chunk rules. + +## 6. Repeat the investigation in a terminal If you need a saved review or want to pass evidence to an agent, run: diff --git a/site/tests/site.spec.ts b/site/tests/site.spec.ts index 1ee61312..f6125f69 100644 --- a/site/tests/site.spec.ts +++ b/site/tests/site.spec.ts @@ -1,6 +1,6 @@ import { expect, test } from "@playwright/test"; -const guides = ["overview", "tour", "design", "get-started", "explore", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; +const guides = ["overview", "tour", "design", "get-started", "explore", "changes", "metrics", "findings", "data-flow", "reports", "cli", "configuration"]; test("every guide has readable static HTML and valid local links", async ({ browser, request }) => { const context = await browser.newContext({ javaScriptEnabled: false }); diff --git a/skills/srcly-code-quality/SKILL.md b/skills/srcly-code-quality/SKILL.md index e689306b..9c138911 100644 --- a/skills/srcly-code-quality/SKILL.md +++ b/skills/srcly-code-quality/SKILL.md @@ -56,6 +56,7 @@ Use `uvx srcly scan . --out -` only when a caller explicitly wants raw tree JSON ## Command Selection - Broad review: `uvx srcly report . --out .srcly --format both` +- Review a branch or a coding session: `uvx srcly changes . --window branch` (or `24h`, `7d`; `--mode net` drops work that was put back; `--json` for the payload). It lists the edited functions and sections, before → after complexity, and two review buckets: already complex and changed, and new hotspots (complexity crossed 10). Paths are relative to the Git repo root. - Single metric list: `uvx srcly hotspots . --metric complexity --limit 20` (any non-neutral id from `metrics.schema.json`; `--cohort function` ranks functions) - Report ranked by another metric: `uvx srcly report . --out .srcly --metric comment_noise` - Named 2x2 (members per quadrant in `report.md` + `quadrants.json`): `uvx srcly report . --out .srcly --quadrant activity` ("Hot mess" = complex and changing often; also `blast_radius`, `component_weight`, `comment_noise`)