Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.
Python aicode-complexitycode-healthcode-intelligencecode-qualitydead-codedeveloper-toolsdocumentationgit-analyticsmcpopen-sourcepythonrefactoringstatic-analysistechnical-debt
feat(lens): inspect and zoom the map from the keyboard (#3025)
Raghav Chamadiya86805c2475d8
diff --git a/docs/agent/LENS.md b/docs/agent/LENS.mdindex 81b97bfef..8177bc2e4 100644--- a/docs/agent/LENS.md+++ b/docs/agent/LENS.md@@ -248,6 +248,30 @@ is drawn: `<N> files, all drawn`, `<N> of <M> files drawn at this size · rest tcap, `4,000 largest of <M> files drawn`, then `indexed <age>` and`<N> touched files not on the map` when some were outside it.+The keys under the map walk what the turn lit. They are letters, since digits+switch tabs, and only the ones that would do something are shown:++| Key | What it does |+|---|---|+| `j` | Select the next lit file: the edit, then the files Claude opened, then the edit's other importers, then files a Repowise reply named; it wraps around |+| `k` | Select the previous one |+| `z` | Zoom into the folder holding the selection: only that folder's files, at the full pane size, with their names |+| `u` | Zoom out one folder |+| `x` | Clear the selection |+| `h` | Health colours on or off |++The selected tile gets a bright ring, and one line under the strip says what it+is: its path, why it is lit (`Claude edited it, +1 line`, `Claude opened it`,+`imports query.py`, `named by get_context`), and what Lens already knows of it+(`hotspot`, `131 files use it`, `recent owner ...`, `9 tests reach it (inferred)`).+Lens asks for nothing new to fill that line. Zoomed in, a breadcrumb such as+`django / db / models` sits above the map and the scope line counts that+folder's files, and `j` and `k` walk only the lit files in it. Selection draws+one redraw, no animation. A new prompt or a `/clear` starts with nothing+selected and the whole repo in view, and a file the turn stops lighting loses+its selection. On a narrow pane the keys stay on one row: the least used ones+(`x`, then `u`, `k`, `z`) give way to a `…` first, and `h` stays.+The `Health colours` button under the map (hotkey `h`) colours the tiles byhealth band instead, `Excellent`, `Good`, `Fair`, `Needs work`, `At risk` and`Not scored`, with that legend; the `lens_map_health` setting starts the map@@ -394,6 +418,10 @@ own background.**The map says it could not load.** `Lens map could not load; it tries again on /lens`.Run `/lens` again once the server is up.+**A tab says Lens could not draw it.** `Lens could not draw this tab; details in the debug log`.+The tab bar stays, so the other tabs still work. Claude Code's debug log has a+line starting `lens:` that names the tab and the error.+**The change review timed out.** It has 20 seconds. The review is skipped forthat turn and runs again after the next turn that edits files.diff --git a/packages/claude-mod/mod-test/lens-map.test.ts b/packages/claude-mod/mod-test/lens-map.test.tsindex 680037aae..c41a3d1bd 100644--- a/packages/claude-mod/mod-test/lens-map.test.ts+++ b/packages/claude-mod/mod-test/lens-map.test.ts@@ -90,8 +90,8 @@ test('/lens map draws Django as quiet tiles, says what will light up, and offersconst map = await ui.find({ key: 'lens-map' })expect(map?.type).toBe('Raster')expect(map?.props.columns).toBe(180)- expect(map?.props.rows).toBe(47)- expect(String(map?.props.cells).length).toBe(180 * 47 * 16)+ expect(map?.props.rows).toBe(45)+ expect(String(map?.props.cells).length).toBe(180 * 45 * 16)expect(await ui.find({ type: 'Text', text: /^1,\d{3} of 2,970 files drawn at this size/ })).toBeDefined()expect(await ui.find({ type: 'Text', text: /^Nothing lit yet this turn/ })).toBeDefined()expect(await ui.find({ type: 'Text', text: ' Needs work' })).toBeUndefined()@@ -106,13 +106,22 @@ test('an edit ripples to the importers the server returned, by blit', async ($:const { seen, ui } = await openMap($, on)await $.tool.call({ tool: 'Edit', tool_use_id: 'toolu_e1', file_path: `${ROOT}\\django\\db\\models\\query.py`, old_string: 'a', new_string: 'a\nb' })expect(await waitFor(() => seen.blits.length >= 2)).toBe(true)- expect(seen.blits[0]).toMatchObject({ requestId: 'lens', key: 'lens-map', columns: 180, rows: 47 })+ expect(seen.blits[0]).toMatchObject({ requestId: 'lens', key: 'lens-map', columns: 180, rows: 45 })const fetched = BLAST_RADIUS.transitive_affected.lengthawait ui.unmount()const after = await $.ui.mount(PANE)expect(await after.find({ type: 'Text', text: '◉ query.py +1 line' })).toBeDefined()expect(await after.find({ type: 'Text', text: new RegExp(`^${fetched} importers: `) })).toBeDefined()+ // The inspector: j selects the edit and says what it is; z zooms into its folder.+ await after.press({ key: 'lens-map-next' })await after.unmount()+ const picked = await $.ui.mount(PANE)+ expect(await picked.find({ type: 'Text', text: /^django\/db\/models\/query\.py · Claude edited it, \+1 line/ })).toBeDefined()+ await picked.press({ key: 'lens-map-zoom' })+ await picked.unmount()+ const zoomed = await $.ui.mount(PANE)+ expect(await zoomed.find({ type: 'Text', text: /^django \/ db/ })).toBeDefined()+ await zoomed.unmount()})test('without the local server the pane says what to run', async ($: any, on: any) => {diff --git a/packages/claude-mod/scripts/bench-map.mjs b/packages/claude-mod/scripts/bench-map.mjsindex 09960dd7c..d81ff9b78 100644--- a/packages/claude-mod/scripts/bench-map.mjs+++ b/packages/claude-mod/scripts/bench-map.mjs@@ -1,8 +1,9 @@// Local benchmark for the map at 180x50: the layout (redone only on a resize// or a style change) and one lit frame with its encoding (a turn's searches,-// reads, the edit and its importers, mid-ripple). Three scales: a 100-file-// repo (synthetic), Django's 2,347 recorded files, and a 10,000-file repo-// (synthetic; the server sends its 4,000 largest). Budget 16 ms each; vitest+// reads, the edit and its importers, mid-ripple, and a selection). Three+// scales: a 100-file repo (synthetic), Django's 2,347 recorded files, and a+// 10,000-file repo (synthetic; the server sends its 4,000 largest), then the+// last two zoomed into one folder. Budget 16 ms each; vitest// guards a frame at 5x that (test/overlay.test.ts).//// npm run bench:map -w @repowise-dev/claude-mod@@ -54,16 +55,18 @@ function time(label, work) {function turnOver(files, importers) {const paths = files.map((f) => f.file_path);const edit = paths[Math.floor(paths.length / 3)];- return { hits: paths.slice(10, 40), reads: [paths[5], edit], named: [paths[5]], importers: importers ?? paths.slice(50, 62), edit, current: edit };+ return { hits: paths.slice(10, 40), reads: [paths[5], edit], named: [paths[5]], importers: importers ?? paths.slice(50, 62), edits: [edit], edit, current: edit };}-function bench(label, files, importers) {- const layout = map.layoutMap(files, { columns: 180, rows: 50, caseInsensitive: true });+function bench(label, files, importers, root = null) {+ const canvas = { columns: 180, rows: 50, caseInsensitive: true, root };+ const layout = map.layoutMap(files, canvas);const lit = turnOver(files, importers);- console.log(`${label}: ${files.length} files, ${layout.drawn.length} with a pixel, ${layout.dense ? "drawn as folders" : "a tile each"}`);- const layoutP95 = time("layout (on resize only)", () => map.layoutMap(files, { columns: 180, rows: 50, caseInsensitive: true }));+ const where = root === null ? "" : `, zoomed into ${root}`;+ console.log(`${label}${where}: ${layout.files.length} files, ${layout.drawn.length} with a pixel, ${layout.dense ? "drawn as folders" : "a tile each"}`);+ const layoutP95 = time("layout (on resize or zoom)", () => map.layoutMap(files, canvas));const frameP95 = time("lit frame mid-ripple + encode", (i) =>- map.frameCells(layout, map.resolveLit(layout, lit), { kind: "ripple", t: (i % 30) / 30 }),+ map.frameCells(layout, map.resolveLit(layout, lit, lit.edit), { kind: "ripple", t: (i % 30) / 30 }),);return Math.max(layoutP95, frameP95);}@@ -74,6 +77,8 @@ const worst = Math.max(bench("100 files (synthetic)", map.syntheticTree(100).files),bench("Django (recorded)", django, djangoImporters),bench("10,000 files (synthetic, the server's 4,000 largest)", map.syntheticTree(10_000).files.slice(0, SERVER_CAP)),+ bench("Django (recorded)", django, djangoImporters, "django/db/models"),+ bench("10,000 files (synthetic)", map.syntheticTree(10_000).files.slice(0, SERVER_CAP), undefined, "src"),);const ok = worst <= BUDGET_MS;console.log(ok ? `within the ${BUDGET_MS} ms budget` : `OVER the ${BUDGET_MS} ms budget`);diff --git a/packages/claude-mod/src/map-controller.ts b/packages/claude-mod/src/map-controller.tsindex ad43b9b1c..e5a052399 100644--- a/packages/claude-mod/src/map-controller.ts+++ b/packages/claude-mod/src/map-controller.ts@@ -16,14 +16,15 @@ import { Animator, type AnimIO, type Frame, type Step } from "./animator";import { withTimeout } from "./data/transport";import type { UiOpenResult } from "./mod-api";import { relativeTo } from "./model/events";+import { KNOWS_NOTHING, litPaths, step, whyLit, type Knows } from "./model/inspect";import { NO_STORY, withImporters, type Reach, type Story } from "./model/story";import { initialTrail, reduceTrail, type Callers, type TrailAction, type TrailState } from "./model/trail";-import { MAP_COPY, notPlacedLine, type ScopeFacts } from "./views/copy";+import { MAP_COPY, detailLine, notPlacedLine, type ScopeFacts } from "./views/copy";import type { Node } from "./views/elements";-import { layoutMap, type MapLayout, type MapStyle } from "./views/map";-import { mapPaneView, mapSize, noticeView, type PaneSize } from "./views/mapPane";+import { folderAt, layoutMap, type MapLayout, type MapStyle, type PlacedFile } from "./views/map";+import { HEALTH_KEY, MAP_KEYS, mapPaneView, mapSize, noticeView, type MapKeyState, type MapPaneParts, type PaneSize } from "./views/mapPane";import { desktopSize, svgPaneView } from "./views/mapSvg";-import { FLASH_MS, NO_LIT, RIPPLE_MS, frameCells, notOnMap, resolveLit, rippleRadius, type Anim, type Lit } from "./views/overlay";+import { FLASH_MS, NO_LIT, RIPPLE_MS, frameCells, litPixels, notOnMap, resolveLit, rippleRadius, type Anim, type Lit } from "./views/overlay";import { MAP_KEY } from "./views/mapPane";import type { ThemeName } from "./views/theme";@@ -60,26 +61,48 @@ export interface PaneInput extends PaneSize {theme: ThemeName;}-/** The current turn as it stands: what it lit (before its importers are joined) and its story. */-export type TurnSource = () => { lit: Lit; story: Story };+/** The current turn as it stands: what it lit (before its importers are joined), its story, and what Lens knows of a file. */+export type TurnSource = () => { lit: Lit; story: Story; knows?: (path: string) => Knows };++/** One read of the turn for one render or frame: what it lit with the importers joined, and the turn itself. */+type Lighting = { lit: Lit; reach: Reach | null; turn: ReturnType<TurnSource> };const NO_TURN: TurnSource = () => ({ lit: NO_LIT, story: NO_STORY });+/** The scope of the whole feed, or (zoomed in) of the folder's files alone. */function scopeFacts(layout: MapLayout, data: HealthMapFeed, repo: MapRepo, offMap: number): ScopeFacts {+ const whole = layout.root === null;return {drawn: layout.drawn.length,- shown: data.files.length,- repositoryTotal: data.repository_total,+ shown: whole ? data.files.length : layout.files.length,+ repositoryTotal: whole ? data.repository_total : layout.files.length,indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,- beyondCap: data.omitted.files,+ beyondCap: whole ? data.omitted.files : 0,dense: layout.dense,notOnMap: offMap,+ zoom: layout.root,};}-type LayoutKey = { data: HealthMapFeed; columns: number; rows: number; style: MapStyle };-const keyParts = (k: LayoutKey): unknown[] => [k.data, k.columns, k.rows, k.style.theme, k.style.health];-const sameKey = (a: LayoutKey, b: LayoutKey): boolean => keyParts(a).every((v, i) => v === keyParts(b)[i]);+type LayoutKey = { data: HealthMapFeed; columns: number; rows: number; style: MapStyle; root: string | null };+const cacheKey = (k: LayoutKey): string => `${k.root ?? ""}|${k.columns}|${k.rows}|${k.style.theme}|${k.style.health}`;+/** Layouts kept per feed: a few zoom levels and sizes. */+const LAYOUT_CACHE = 6;++/** The folder above `root`; null above the top. */+function parentOf(root: string | null): string | null {+ const at = root === null ? -1 : root.lastIndexOf("/");+ return at === -1 ? null : (root as string).slice(0, at);+}++/** The folder drawn where a file sits: the zoom target for it, or null when there is none deeper. */+function folderOf(layout: MapLayout, path: string): string | null {+ const at = layout.index.get(layout.caseInsensitive ? path.toLowerCase() : path);+ if (at === undefined) return null;+ const b = litPixels(layout, layout.files[at] as PlacedFile);+ const folder = folderAt(layout, Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2));+ return folder === layout.root ? null : folder;+}export class LensMap {trail: TrailState = initialTrail;@@ -100,7 +123,12 @@ export class LensMap {private readonly edited = new Set<string>();private readonly importers = new Map<string, Callers>();private drawn: { layout: MapLayout; root: string } | null = null;- private layoutCache: { key: LayoutKey; layout: MapLayout } | null = null;+ /** What the last render drew, for the keys: its layout and the lit files on it, in cursor order. */+ private view: { layout: MapLayout; paths: string[] } | null = null;+ private layoutCache: { data: HealthMapFeed; layouts: Map<string, MapLayout> } | null = null;+ /** The inspector's selection (a repo-relative path) and the folder zoomed into. */+ private selected: string | null = null;+ private zoom: string | null = null;private reducedMotion = false;/** Health colours on the tiles: off by default (`lens_map_health`), toggled from the pane. */private health: boolean;@@ -127,15 +155,74 @@ export class LensMap {return this.repo?.caseInsensitive === false ? rel : rel.toLowerCase();}- /** The pane's toggle: health colours on the tiles, or the quiet ghost map. */- toggleHealth(io: MapIO): void {- this.health = !this.health;+ /** A press of one of the map's keys (MAP_PRESSES): moves the cursor, zooms, or toggles health colours; one redraw. */+ press(io: MapIO, key: string): void {+ const act = this.actions()[key];+ if (act === undefined) return;+ act();io.redraw();}+ private actions(): Record<string, () => void> {+ return {+ [MAP_KEYS.next.key]: () => this.move(1),+ [MAP_KEYS.previous.key]: () => this.move(-1),+ [MAP_KEYS.clear.key]: () => (this.selected = null),+ [MAP_KEYS.zoom.key]: () => (this.zoom = this.zoomTarget() ?? this.zoom),+ [MAP_KEYS.up.key]: () => (this.zoom = parentOf(this.zoom)),+ [HEALTH_KEY]: () => (this.health = !this.health),+ };+ }++ /** The cursor walks the lit files the last render drew, so a zoomed view walks only its own folder's. */+ private move(by: 1 | -1): void {+ this.selected = step(this.view?.paths ?? [], this.selected, by);+ }++ /** Where the zoom key goes: the folder holding the selection, when one is drawn deeper than the current view. */+ private zoomTarget(): string | null {+ const layout = this.view?.layout ?? null;+ return layout === null || this.selected === null ? null : folderOf(layout, this.selected);+ }++ /** A new prompt starts with nothing selected and the whole repo in view. */+ turnStarted(): void {+ this.selected = null;+ this.zoom = null;+ }++ /**+ * The lit files on this layout in cursor order, and the selection among them.+ * A selection the turn stops lighting (or this view no longer draws) is dropped+ * for good, so it never comes back ringed when the file is lit again.+ */+ private see(layout: MapLayout, lit: Lit): string[] {+ const paths = litPaths(lit).filter((p) => layout.index.has(layout.caseInsensitive ? p.toLowerCase() : p));+ const s = this.selected;+ if (s !== null && !paths.some((p) => p.toLowerCase() === s.toLowerCase())) this.selected = null;+ this.view = { layout, paths };+ return paths;+ }++ /** The detail line, the keys that would act, and the rest of the pane's parts. */+ private parts(layout: MapLayout, lighting: Lighting, scope: ScopeFacts, paths: readonly string[]): MapPaneParts {+ const turn = lighting.turn;+ const selected = this.selected;+ const knows = selected === null ? KNOWS_NOTHING : (turn.knows?.(selected) ?? KNOWS_NOTHING);+ const detail = selected === null ? null : detailLine(selected, whyLit(selected, lighting.lit, turn.story, knows), knows);+ const keys: MapKeyState = {+ items: paths.length > 0,+ selected: selected !== null,+ zoomable: selected !== null && folderOf(layout, selected) !== null,+ zoomed: layout.root !== null,+ };+ return { story: turn.story, reach: lighting.reach, scope, detail, keys };+ }+/** What the turn lit, with the latest edit's importers joined as they stand now. */- private lighting(): { lit: Lit; reach: Reach | null } {- return withImporters(this.turn().lit, (p) => this.importersOf(p));+ private lighting(): Lighting {+ const turn = this.turn();+ return { ...withImporters(turn.lit, (p) => this.importersOf(p)), turn };}/** The band row the map wants shown, if any. */@@ -154,8 +241,8 @@ export class LensMap {}/**- * A `/clear`: the conversation's trail and edits go, so nothing of it stays- * lit. The feed, the repo and the importers already asked for (index data,+ * A `/clear`: the conversation's trail and edits go, with the selection and+ * the zoom, so nothing of it stays lit. The feed, the repo and the importers already asked for (index data,* by path) stay, and so does an open pane.*/clearConversation(io: MapIO): void {@@ -163,6 +250,7 @@ export class LensMap {this.edited.clear();this.editPath = null;this.band = null;+ this.turnStarted();io.redraw();}@@ -212,10 +300,17 @@ export class LensMap {const desktop = pane.surface === "desktop";const style: MapStyle = { theme: pane.theme, health: this.health };const size = mapSize(pane, this.health);- const layout = this.layoutFor({ data, ...(desktop ? desktopSize(size) : size), style }, repo.caseInsensitive);- const { lit, reach } = this.lighting();- const overlay = resolveLit(layout, lit);- const parts = { story: this.turn().story, reach, scope: scopeFacts(layout, data, repo, notOnMap(layout, lit)) };+ const at = desktop ? desktopSize(size) : size;+ let layout = this.layoutFor({ data, ...at, style, root: this.zoom }, repo.caseInsensitive);+ if (layout.root !== null && layout.files.length === 0) {+ // The zoomed folder left the feed (it refreshed): back to the whole repo.+ this.zoom = null;+ layout = this.layoutFor({ data, ...at, style, root: null }, repo.caseInsensitive);+ }+ const lighting = this.lighting();+ const paths = this.see(layout, lighting.lit);+ const overlay = resolveLit(layout, lighting.lit, this.selected);+ const parts = this.parts(layout, lighting, scopeFacts(layout, data, repo, notOnMap(layout, lighting.lit)), paths);if (desktop) return svgPaneView(layout, overlay, parts);this.drawn = { layout, root: repo.root };return mapPaneView(layout, frameCells(layout, overlay, mapStep(this.animator.progress(Date.now()))), parts);@@ -232,12 +327,15 @@ export class LensMap {return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;}- /** The layout for this feed, size and style; laid out again only when one of them changed. */+ /** The layout for this feed, size, style and zoom; kept per (zoom, size, style) for the feed, a few at a time. */private layoutFor(key: LayoutKey, caseInsensitive: boolean): MapLayout {- const c = this.layoutCache;- if (c !== null && sameKey(c.key, key)) return c.layout;- const layout = layoutMap(key.data.files, { columns: key.columns, rows: key.rows, caseInsensitive, style: key.style });- this.layoutCache = { key, layout };+ if (this.layoutCache?.data !== key.data) this.layoutCache = { data: key.data, layouts: new Map() };+ const layouts = this.layoutCache.layouts;+ const cached = layouts.get(cacheKey(key));+ if (cached !== undefined) return cached;+ const layout = layoutMap(key.data.files, { columns: key.columns, rows: key.rows, caseInsensitive, style: key.style, root: key.root });+ if (layouts.size >= LAYOUT_CACHE) layouts.delete(layouts.keys().next().value as string);+ layouts.set(cacheKey(key), layout);return layout;}@@ -344,7 +442,8 @@ export class LensMap {const on = this.drawn;const anim = mapStep(step);if (on === null || anim === undefined) return null;- const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit), anim);+ // The selection was checked against this layout when it was drawn.+ const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit, this.selected), anim);return { key: MAP_KEY, cells, columns: on.layout.columns, rows: on.layout.rows };}}diff --git a/packages/claude-mod/src/model/inspect.ts b/packages/claude-mod/src/model/inspect.tsnew file mode 100644index 000000000..6635bedd2--- /dev/null+++ b/packages/claude-mod/src/model/inspect.ts@@ -0,0 +1,86 @@+/**+ * The map's inspector: a cursor over the files the turn lit, in a fixed order+ * (the edits, then the files Claude opened, then the edit's other importers, then+ * files a Repowise reply named), and what one of them is: why it is lit and+ * what the index already told Lens about it. Nothing here asks for more. Pure.+ */++import type { Lit } from "../views/overlay";+import { pathKey, type FlowState } from "./flow";+import type { FileContext } from "./session";+import type { Story } from "./story";++/** What Lens already knows of a file, from lookups it made anyway. */+export interface Knows {+ /** The file's card (get_context), when the spinner fetched it. */+ context: FileContext | null;+ /** Tests that reach it (the edit's blast radius), when known. */+ tests: { total: number; basis: "measured" | "inferred" } | null;+ /** The Repowise tool whose reply named it, when one did. */+ namedBy: string | null;+}++export const KNOWS_NOTHING: Knows = { context: null, tests: null, namedBy: null };++const key = (p: string): string => p.toLowerCase();++/** The lit files in cursor order, each once. */+export function litPaths(lit: Lit): string[] {+ const edits = [...lit.edits].reverse();+ const order = [...edits, ...lit.reads, ...lit.importers, ...lit.named];+ const seen = new Set<string>();+ return order.filter((p) => {+ if (seen.has(key(p))) return false;+ seen.add(key(p));+ return true;+ });+}++/** The next (`by` 1) or previous (-1) lit file after `current`, wrapping; the first or last when `current` is not lit. */+export function step(paths: readonly string[], current: string | null, by: 1 | -1): string | null {+ if (paths.length === 0) return null;+ const at = current === null ? -1 : paths.findIndex((p) => key(p) === key(current));+ if (at === -1) return (by === 1 ? paths[0] : paths.at(-1)) ?? null;+ return paths[(at + by + paths.length) % paths.length] ?? null;+}++/** Why a file is lit, as facts the copy words: edited (with its size), opened, an importer of the edit, named. */+export interface Why {+ edited: { lines: Story["edited"][number]["lines"] } | null;+ opened: boolean;+ imports: string | null;+ namedBy: string | null;+}++const nameOf = (p: string): string => p.slice(p.lastIndexOf("/") + 1);+const has = (paths: readonly string[], p: string): boolean => paths.some((x) => key(x) === key(p));++export function whyLit(path: string, lit: Lit, story: Story, knows: Knows): Why {+ const edit = has(lit.edits, path) ? (story.edited.find((e) => e.name === nameOf(path)) ?? { lines: null }) : null;+ return {+ edited: edit === null ? null : { lines: edit.lines },+ opened: edit === null && has(lit.reads, path),+ imports: has(lit.importers, path) && lit.edit !== null ? nameOf(lit.edit) : null,+ namedBy: knows.namedBy,+ };+}++/** A file's card by repo-relative path, case aside. */+function contextOf(contexts: Readonly<Record<string, FileContext>>, path: string): FileContext | null {+ const exact = contexts[path];+ if (exact !== undefined) return exact;+ const lower = key(path);+ const found = Object.keys(contexts).find((k) => key(k) === lower);+ return found === undefined ? null : (contexts[found] ?? null);+}++/** What Lens already holds about a file: its card, the tests that reach an edited one, and which reply named it (Flow's record, when on). */+export function knowsOf(path: string, contexts: Readonly<Record<string, FileContext>>, flow: FlowState | null): Knows {+ const facts = flow === null ? undefined : flow.blast[pathKey(path)];+ const tests = facts?.tests ?? null;+ return {+ context: contextOf(contexts, path),+ tests: tests === null ? null : { total: tests.total, basis: tests.basis },+ namedBy: flow === null ? null : (flow.named[pathKey(path)]?.tool ?? null),+ };+}diff --git a/packages/claude-mod/src/register.ts b/packages/claude-mod/src/register.tsindex e9fb6cc50..808214a8b 100644--- a/packages/claude-mod/src/register.ts+++ b/packages/claude-mod/src/register.ts@@ -15,7 +15,8 @@ import { LensFlow, type FlowPane } from "./flow-controller";import { themeOf, type ThemeName } from "./views/theme";import { litFromFlow, litFromTrail, storyFromFlow, storyFromTrail, type Story } from "./model/story";import { NO_LIT, type Lit } from "./views/overlay";-import { HEALTH_KEY } from "./views/mapPane";+import { MAP_PRESSES } from "./views/mapPane";+import { knowsOf, type Knows } from "./model/inspect";import { LensMap, type MapIO, type MapRepo } from "./map-controller";import type {CheckNext,@@ -55,7 +56,7 @@ import {import { askReply, askRoute, lensCommand, whyDraft, type BarTab, type PaneTab } from "./model/ask";import { clearedConversation, hintFor, initialSession, reduce, type SavingsDelta, type SessionAction, type SessionState } from "./model/session";import { bandView } from "./views/band";-import { materialize, type ElementTable, type Node } from "./views/elements";+import { materialize, text, type ElementTable, type Node } from "./views/elements";import { marginView } from "./views/margin";import { isFileEdit, isRetryable, shouldReview, type ChangeRisk } from "./model/review";import { BRIEF_PRESS, briefText } from "./views/brief";@@ -425,6 +426,7 @@ async function onTurnStart($: ModApi, e: TurnStartEvent, next: (e: TurnStartEvenstarted = null;}dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });+ map.turnStarted();} catch (err) {bind($).debug(`turn.start failed: ${String(err)}`);}@@ -872,11 +874,12 @@ const TAB_BODIES: Record<PaneTab, TabBody> = {};/** The current turn for the map: from Flow's record, or from the map's own trail when Flow is off. */-function mapTurn(): { lit: Lit; story: Story } {- if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state) };+function mapTurn(): { lit: Lit; story: Story; knows: (path: string) => Knows } {+ const knows = (path: string) => knowsOf(path, state.contexts, flowOn ? flow.state : null);+ if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state), knows };const root = state.repoRoot;const lit = root === null ? NO_LIT : litFromTrail(map.trail, root, isWindowsPath(root));- return { lit, story: storyFromTrail(map.trail) };+ return { lit, story: storyFromTrail(map.trail), knows };}function mapBody(b: Bound, e: PaneRenderEvent): Node {@@ -886,22 +889,32 @@ function mapBody(b: Bound, e: PaneRenderEvent): Node {return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows: scroll.bodyRows - TAB_ROWS, theme });}-/** The map's "Health colours" button. */-function pressHealth($: ModApi): void {+/** One of the map's keys: the cursor, the zoom, or the health colours. */+function pressMap($: ModApi, key: string): void {try {- map.toggleHealth(bind($));+ map.press(bind($), key);} catch (err) {- bind($).debug(`health toggle failed: ${String(err)}`);+ bind($).debug(`map key failed: ${String(err)}`);}}+function mapPresses($: ModApi): Record<string, () => void> {+ return Object.fromEntries(MAP_PRESSES.map((key) => [key, () => pressMap($, key)]));+}+/** The shown tab's body; the map draws (and animates) only on its own tab, the owl ticks only on Flow's. */function tabBody(b: Bound, e: PaneRenderEvent): Node {const tab = state.pane.tab;if (tab !== "map") map.offScreen();if (tab !== "flow") flow.hide();const rows = (e.props.placement === "dock" ? e.props.scroll.bodyRows : PANE_ROWS) - TAB_ROWS;- return TAB_BODIES[tab](b, e, rows);+ try {+ return TAB_BODIES[tab](b, e, rows);+ } catch (err) {+ // A body that throws keeps the tab bar and says so, instead of blanking the pane.+ b.debug(`${tab} tab render failed: ${String(err)}`);+ return text(fit(PANE_COPY.bodyFailed, e.props.bodyColumns), { dimColor: true, wrap: "truncate-end" });+ }}async function onPane($: ModApi, e: PaneRenderEvent, next: (e: PaneRenderEvent) => Promise<unknown>): Promise<unknown> {@@ -909,7 +922,7 @@ async function onPane($: ModApi, e: PaneRenderEvent, next: (e: PaneRenderEvent)const b = bind($);try {const bar = tabBar(flowOn);- const presses = { ...tabPresses($, bar), ...flowRowPresses($), [HEALTH_KEY]: () => pressHealth($) };+ const presses = { ...tabPresses($, bar), ...flowRowPresses($), ...mapPresses($) };return materialize(paneView(state.pane.tab, tabBody(b, e), bar), $.ui.resolve(e), presses);} catch (err) {b.debug(`pane render failed: ${String(err)}`);diff --git a/packages/claude-mod/src/views/copy.ts b/packages/claude-mod/src/views/copy.tsindex 4487cdb3a..ad039bc87 100644--- a/packages/claude-mod/src/views/copy.ts+++ b/packages/claude-mod/src/views/copy.ts@@ -6,6 +6,7 @@import { formatNumber } from "@repowise-dev/ui/lib/format";import { countOf, fit } from "../format";import type { FileContext, HintKind, IndexFreshness, MarginNote, SavingsDelta } from "../model/session";+import type { Knows } from "../model/inspect";import type { Squeeze } from "../model/squeeze";import type { Behind, ReplyFact } from "../model/replies";@@ -228,8 +229,10 @@ export interface ScopeFacts {beyondCap: number;/** Too many files for a pixel each: drawn as folders. */dense: boolean;- /** Files the turn touched that are not on the map (outside the feed). */+ /** Files the turn touched that are not on the map (outside the feed, or outside the zoomed folder). */notOnMap: number;+ /** The folder zoomed into, or null. */+ zoom: string | null;}/** Scope parts a narrow line may leave out; the counts and the cap always stay. */@@ -257,7 +260,7 @@ function drawnPart(s: ScopeFacts): string[] {export function scopeParts(s: ScopeFacts): string[] {const parts = drawnPart(s);if (s.indexed !== null) parts.push(indexedPart(s.indexed));- if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} not on the map`);+ if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} ${s.zoom === null ? "not on the map" : "outside this folder"}`);return parts;}@@ -292,6 +295,47 @@ export function reachesPending(edit: string): string {export const REACHES_FAILED = "import graph unavailable";+/** The map's keys, as the hint row names them. */+export const MAP_KEYS_COPY = {+ next: "next",+ previous: "previous",+ zoom: "zoom in",+ up: "up",+ clear: "clear",+} as const;++/** Where the zoom is: `django / db / models`. */+export function crumbLine(root: string): string {+ return root.split("/").join(" / ");+}++/** Why a file is lit, in words: `Claude edited it, +1 line`, `Claude opened it`, `imports query.py`, `named by get_context`. */+export function whyParts(why: {+ edited: { lines: { delta: number } | { written: number } | null } | null;+ opened: boolean;+ imports: string | null;+ namedBy: string | null;+}): string[] {+ const parts: string[] = [];+ if (why.edited !== null) parts.push(`Claude edited it${why.edited.lines === null ? "" : `,${linesPart(why.edited.lines)}`}`);+ if (why.opened) parts.push("Claude opened it");+ if (why.imports !== null) parts.push(`imports ${why.imports}`);+ if (why.namedBy !== null) parts.push(`named by ${why.namedBy}`);+ return parts;+}++/** The inspector's line: `django/db/models/base.py · imports query.py · hotspot · 131 files use it`. */+export function detailLine(path: string, why: Parameters<typeof whyParts>[0], knows: Knows): string {+ const facts = knows.context === null ? [] : knowsParts(knows.context);+ const tests = knows.tests === null ? [] : [testsReach(knows.tests)];+ return [path, ...whyParts(why), ...facts, ...tests].join(" · ");+}++/** `12 tests reach it (inferred)`. */+export function testsReach(t: { total: number; basis: "measured" | "inferred" }): string {+ return `${countOf(t.total, "test reaches it", "tests reach it")} (${t.basis})`;+}+// The pane's tabs, Ask and Recap.export const PANE_COPY = {@@ -306,6 +350,7 @@ export const PANE_COPY = {noEvidence: "no evidence cited",fromIndex: "Built from the index",fromModel: "Written by this repo's configured model, from the index",+ bodyFailed: "Lens could not draw this tab; details in the debug log",} as const;/** Characters of a reply the Ask tab draws; the Markdown element takes at most 10,000. */diff --git a/packages/claude-mod/src/views/map.ts b/packages/claude-mod/src/views/map.tsindex 1ad5714f5..d30202c3e 100644--- a/packages/claude-mod/src/views/map.ts+++ b/packages/claude-mod/src/views/map.ts@@ -14,6 +14,7 @@import { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } from "d3-hierarchy";import { bandForScore, type HealthFileMetric } from "@repowise-dev/types/health";import { BRAND, DARK, DARK_CANVAS, DARK_CANVAS_BAND, LIGHT } from "@repowise-dev/ui/brand";+import { cellSafe } from "../format";import type { ThemeName } from "./theme";export type MapFile = Pick<HealthFileMetric, "file_path" | "score" | "nloc">;@@ -71,6 +72,8 @@ export interface MapPalette {named: number;importer: number;edit: number;+ /** The inspector's ring around the selected tile: the theme's brightest neutral, not a new hue. */+ ring: number;}export interface MapLayout {@@ -96,6 +99,8 @@ export interface MapLayout {dense: boolean;/** Every folder below the groups, parents first, as painted. */folders: FolderTile[];+ /** The folder zoomed into, or null for the whole repo. */+ root: string | null;}const UPPER_HALF = 0x2580;@@ -129,6 +134,7 @@ export const MAP_PALETTES: Record<ThemeName, MapPalette> = {named: mix(hex(DARK.accentSecondary), hex(DARK.bgRoot), 0.45),importer: hex(DARK.accentSecondary),edit: hex(BRAND.accent),+ ring: hex(BRAND.cream),},light: {tileA: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.08),@@ -139,6 +145,7 @@ export const MAP_PALETTES: Record<ThemeName, MapPalette> = {named: mix(hex(LIGHT.accentSecondary), hex(LIGHT.bgRoot), 0.55),importer: hex(LIGHT.accentSecondary),edit: hex(BRAND.accentTextLight),+ ring: hex(LIGHT.textPrimary),},};@@ -308,6 +315,8 @@ function paintBox(base: Uint32Array, width: number, box: { x0: number; y0: numbe/** A folder inside a group: its pixels (within the group's interior) and its tone, alternating among its siblings. */export interface FolderTile {+ /** The folder's repo-relative path. */+ path: string;x0: number;y0: number;x1: number;@@ -315,6 +324,13 @@ export interface FolderTile {tone: 0 | 1;}+/** A folder node's path: its group's key, then the folder names below it. */+function folderPath(group: HierarchyRectangularNode<Datum>, node: HierarchyRectangularNode<Datum>): string {+ // Ancestors from the root: the tree's root, then the group, then the folders below it.+ const below = node.ancestors().reverse().slice(2).map((n) => n.data.name);+ return [group.data.name, ...below].filter((part) => part !== "").join("/");+}+/** Every folder below the groups, parents before children, so the deepest folder big enough to show wins. */function folderTiles(group: HierarchyRectangularNode<Datum>, inner: ReturnType<typeof groupInterior>): FolderTile[] {const out: FolderTile[] = [];@@ -323,11 +339,23 @@ function folderTiles(group: HierarchyRectangularNode<Datum>, inner: ReturnType<tconst tone = ((node.parent?.children ?? []).indexOf(node) % 2) as 0 | 1;const [x0, x1] = pixelSpan(node.x0, node.x1);const [y0, y1] = pixelSpan(node.y0, node.y1);- out.push({ x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1), tone });+ const box = { x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1) };+ out.push({ path: folderPath(group, node), ...box, tone });}return out;}+const within = (f: { x0: number; y0: number; x1: number; y1: number }, x: number, y: number): boolean =>+ x >= f.x0 && x < f.x1 && y >= f.y0 && y < f.y1;++/** The folder drawn at a pixel: the deepest folder tile holding it, else its group (gutters included); null off the map. */+export function folderAt(layout: MapLayout, x: number, y: number): string | null {+ const tile = layout.folders.filter((f) => within(f, x, y)).at(-1);+ if (tile !== undefined) return tile.path;+ const group = layout.groups.find((g) => within({ x0: g.rect.x, y0: g.rect.y, x1: g.rect.x + g.rect.w, y1: g.rect.y + g.rect.h }, x, y));+ return group === undefined || group.key === "" ? null : group.key;+}+function paintFile(base: Uint32Array, width: number, f: PlacedFile, fill: number): void {const edge = mix(fill, BLACK, 0.3);const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;@@ -351,26 +379,50 @@ const LABEL_MIN_COLS = 12;const LABEL_MIN_ROWS = 3;const MAX_LABELS = 8;-function labelFor(g: MapGroup, columns: number, rows: number): MapLabel | null {+function labelFor(g: MapGroup, columns: number, rows: number, root: string | null): MapLabel | null {const col = Math.ceil(g.rect.x);const row = Math.ceil(g.rect.y / 2);const width = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;const height = Math.floor((g.rect.y + g.rect.h) / 2) - row;const small = height < LABEL_MIN_ROWS || width < LABEL_MIN_COLS;- if (g.key === "" || small || row >= rows) return null;- const text = labelText(g.key, width);+ // Zoomed in, a folder is named below the zoom root; files directly in it get no name.+ const key = root === null ? g.key : g.key.slice(root.length + 1);+ if (key === "" || small || row >= rows) return null;+ const text = labelText(key, width);return text === null ? null : { row, col, text };}/** Group labels, largest groups first, where the group is wide and tall enough. */-function labelsFor(groups: readonly MapGroup[], columns: number, rows: number): MapLabel[] {+function labelsFor(groups: readonly MapGroup[], columns: number, rows: number, root: string | null = null): MapLabel[] {return [...groups].sort((a, b) => b.nloc - a.nloc)- .map((g) => labelFor(g, columns, rows))+ .map((g) => labelFor(g, columns, rows, root)).filter((l): l is MapLabel => l !== null).slice(0, MAX_LABELS);}+/** A file's name inside its own tile, when the tile is a row tall and wide enough for it. */+function fileLabel(f: PlacedFile, rows: number): MapLabel | null {+ const text = cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1));+ const row = Math.ceil(f.py0 / 2);+ const roomy = f.px1 - f.px0 >= text.length + 2 && Math.floor(f.py1 / 2) > row;+ return roomy && row < rows ? { row, col: f.px0 + 1, text } : null;+}++/** Zoomed in: the names of files big enough to hold them, where no folder name already sits. */+function fileLabels(files: readonly PlacedFile[], rows: number, taken: readonly MapLabel[]): MapLabel[] {+ const used = new Set(taken.flatMap((l) => [...l.text].map((_, k) => `${l.row}:${l.col + k}`)));+ const out: MapLabel[] = [];+ for (const label of files.map((f) => fileLabel(f, rows))) {+ if (label === null) continue;+ const cells = [...label.text].map((_, k) => `${label.row}:${label.col + k}`);+ if (cells.some((c) => used.has(c))) continue;+ cells.forEach((c) => used.add(c));+ out.push(label);+ }+ return out;+}+/*** The base pixels: ghost folder tones under everything (no holes where files* are too small), then each file's tile, unless the map is dense, where the@@ -403,6 +455,14 @@ export interface MapCanvas {rows: number;caseInsensitive: boolean;style?: MapStyle;+ /** Zoomed in: only this folder's files, at the full size, with their names. */+ root?: string | null;+}++/** The files under `root` (all of them without one). */+function filesUnder(feed: readonly MapFile[], root: string | null): MapFile[] {+ const lines = feed.filter((f) => f.nloc > 0);+ return root === null ? lines : lines.filter((f) => f.file_path.startsWith(`${root}/`));}export function layoutMap(feed: readonly MapFile[], canvas: MapCanvas): MapLayout {@@ -410,11 +470,8 @@ export function layoutMap(feed: readonly MapFile[], canvas: MapCanvas): MapLayouconst style = canvas.style ?? DEFAULT_STYLE;const width = columns;const height = rows * 2;- const root = treemapOf(- feed.filter((f) => f.nloc > 0),- width,- height,- );+ const zoom = canvas.root ?? null;+ const root = treemapOf(filesUnder(feed, zoom), width, height);const groups: MapGroup[] = [];const files: PlacedFile[] = [];const folders: FolderTile[] = [];@@ -434,7 +491,9 @@ export function layoutMap(feed: readonly MapFile[], canvas: MapCanvas): MapLayou});const dense = drawn.length < files.length * DENSE_SHARE;const base = paintBase({ width, height, groups, folders, files, drawn }, style, dense);- return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base, style, dense, lower, folders };+ const folderNames = labelsFor(groups, columns, rows, zoom);+ const labels = zoom === null || dense ? folderNames : [...folderNames, ...fileLabels(files, rows, folderNames)];+ return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels, base, style, dense, lower, folders, root: zoom };}/**@@ -460,7 +519,8 @@ function labelCovered(label: MapLabel, marked: Uint8Array | undefined, width: nuconst cellGround = (pixel: number | undefined): number => (pixel === undefined || pixel === GROUND ? TERMINAL_DEFAULT : pixel);function writeText(words: Uint32Array, layout: MapLayout, label: MapLabel, colors: (col: number) => [number, number]): void {- for (let k = 0; k < label.text.length && label.col + k < layout.columns; k++) {+ if (label.row < 0 || label.row >= layout.rows) return;+ for (let k = Math.max(0, -label.col); k < label.text.length && label.col + k < layout.columns; k++) {const col = label.col + k;words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);}diff --git a/packages/claude-mod/src/views/mapPane.ts b/packages/claude-mod/src/views/mapPane.tsindex 689bdec01..78e95ef77 100644--- a/packages/claude-mod/src/views/mapPane.ts+++ b/packages/claude-mod/src/views/mapPane.ts@@ -12,6 +12,8 @@ import { fit } from "../format";import type { Reach, Story } from "../model/story";import {MAP_COPY,+ MAP_KEYS_COPY,+ crumbLine,REACHES_FAILED,SCOPE_REST,STORY_COPY,@@ -29,15 +31,28 @@ import { MAP_PALETTES, type MapLayout, type MapStyle } from "./map";export const MAP_KEY = "lens-map";export const HEALTH_KEY = "lens-map-health";+/** The map's key Buttons, by press key, with their hotkeys: letters only (digits are the tabs). */+export const MAP_KEYS = {+ next: { key: "lens-map-next", hotkey: "j" },+ previous: { key: "lens-map-previous", hotkey: "k" },+ zoom: { key: "lens-map-zoom", hotkey: "z" },+ up: { key: "lens-map-up", hotkey: "u" },+ clear: { key: "lens-map-clear", hotkey: "x" },+} as const;+export type MapKeyName = keyof typeof MAP_KEYS;+/** Every Button key the map's pane presses, for register.ts's press table. */+export const MAP_PRESSES: readonly string[] = [...Object.values(MAP_KEYS).map((k) => k.key), HEALTH_KEY];const MAX_COLUMNS = 512;const MAX_ROWS = 256;const MIN_ROWS = 4;const GAP = 2;const SEP = " · ";-/** The story strip's four rows, the scope's two, and the toggle's one. */+/** The breadcrumb, the story strip's four rows, the detail line, the scope's two, and the key row. */+const CRUMB_ROWS = 1;const STORY_ROWS = 4;+const DETAIL_ROWS = 1;const SCOPE_ROWS = 2;-const TOGGLE_ROWS = 1;+const KEY_ROWS = 1;const HEAD = 10;/** Importers named on the REACHES row before `+N`. */const REACH_NAMES = 3;@@ -81,7 +96,7 @@ export const swatchWidth = (s: Swatch): number => s.label.length + 2;/** Rows under the map at this width, reserved whatever they hold: the map's height must not move under a blit. */export function legendRows(columns: number, health = false): number {const bands = health ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;- return STORY_ROWS + bands + SCOPE_ROWS + TOGGLE_ROWS;+ return CRUMB_ROWS + STORY_ROWS + DETAIL_ROWS + bands + SCOPE_ROWS + KEY_ROWS;}export interface PaneSize {@@ -182,26 +197,80 @@ export function storyView(story: Story, reach: Reach | null, style: MapStyle, coreturn rows.filter(([, segs]) => segs.length > 0).map(([head, segs]) => storyRow(head, segs, columns));}+/** Which of the map's keys mean something now. */+export interface MapKeyState {+ items: boolean;+ selected: boolean;+ zoomable: boolean;+ zoomed: boolean;+}++export const NO_KEYS: MapKeyState = { items: false, selected: false, zoomable: false, zoomed: false };+export interface MapPaneParts {story: Story;reach: Reach | null;scope: ScopeFacts;+ /** The selected file's line: its path, why it is lit, what the index knows; null with nothing selected. */+ detail?: string | null;+ keys?: MapKeyState;+}++/** The keys a narrow row gives up first: clear, up, previous, zoom, next; the health toggle last. */+const KEY_PRIORITY: readonly (MapKeyName | "health")[] = ["health", "next", "zoom", "previous", "up", "clear"];+/** A plain Button draws as `h: label`. */+const keyCells = (label: string): number => label.length + 3;+const MORE = "…";++/**+ * The quiet key row: only the keys that would do something, then the health+ * toggle, on one row whatever the width: keys that do not fit are dropped,+ * lowest priority first, behind a `…`, so the rows under the map never grow+ * under a blit.+ */+export function keyRow(keys: MapKeyState, style: MapStyle, columns: number): Node {+ const on: [MapKeyName, boolean][] = [+ ["next", keys.items],+ ["previous", keys.items],+ ["zoom", keys.zoomable],+ ["up", keys.zoomed],+ ["clear", keys.selected],+ ];+ const all = [...on.filter(([, shown]) => shown).map(([name]) => ({ name, label: MAP_KEYS_COPY[name] as string })), { name: "health" as const, label: style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff }];+ const ranked = [...all].sort((a, b) => KEY_PRIORITY.indexOf(a.name) - KEY_PRIORITY.indexOf(b.name));+ // The top `n` keys by priority, with the gaps between them and the `…` when some are left out.+ const cells = (n: number) => ranked.slice(0, n).reduce((w, k) => w + keyCells(k.label) + GAP, 0) + (n < all.length ? MORE.length : -GAP);+ let kept = all.length;+ while (kept > 0 && cells(kept) > columns) kept--;+ const shown = new Set(ranked.slice(0, kept).map((k) => k.name));+ const nodes = all.filter((k) => shown.has(k.name)).map((k) => (k.name === "health" ? button(HEALTH_KEY, "h", k.label, true) : button(MAP_KEYS[k.name].key, MAP_KEYS[k.name].hotkey, k.label, true)));+ return box({ flexDirection: "row", columnGap: GAP }, kept < all.length ? [...nodes, text(MORE, { dimColor: true })] : nodes);}-/** Everything under the drawing: the story (or a quiet line), the health legend when on, the scope, and the toggle. */+const dimLine = (line: string, columns: number): Node => text(fit(line, columns), { dimColor: true, wrap: "truncate-end" });++/** Everything under the drawing: the story (or a quiet line), the selection's detail, the health legend when on, the scope, and the keys. */export function legendView(parts: MapPaneParts, style: MapStyle, columns: number): Node[] {const story = storyView(parts.story, parts.reach, style, columns);- const quiet = story.length === 0 ? [text(fit(MAP_COPY.quiet, columns), { dimColor: true, wrap: "truncate-end" })] : story;+ const quiet = story.length === 0 ? [dimLine(MAP_COPY.quiet, columns)] : story;+ const detail = parts.detail ?? null;return [...quiet,+ ...(detail === null ? [] : [text(fit(detail, columns), { wrap: "truncate-end" })]),...(style.health ? swatchRows(BAND_SWATCHES, columns) : []),- ...scopeRows(parts.scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),- button(HEALTH_KEY, "h", style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff, true),+ ...scopeRows(parts.scope, columns).map((f) => dimLine(f, columns)),+ keyRow(parts.keys ?? NO_KEYS, style, columns),];}+/** Zoomed in: where, above the drawing. */+function crumbs(layout: MapLayout): Node[] {+ return layout.root === null ? [] : [dimLine(crumbLine(layout.root), layout.columns)];+}+export function mapPaneView(layout: MapLayout, cells: string, parts: MapPaneParts): Node {return box({ key: "lens-map-pane", flexDirection: "column" }, [+ ...crumbs(layout),raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),...legendView(parts, layout.style, layout.columns),]);diff --git a/packages/claude-mod/src/views/overlay.ts b/packages/claude-mod/src/views/overlay.tsindex 480966743..e715b4f0c 100644--- a/packages/claude-mod/src/views/overlay.ts+++ b/packages/claude-mod/src/views/overlay.ts@@ -26,7 +26,7 @@ export interface Lit {export const NO_LIT: Lit = { hits: [], reads: [], named: [], importers: [], edits: [], edit: null, current: null };-/** The lit files as indices into `layout.files`, and the names written beside them. */+/** The lit files as indices into `layout.files`, the names beside them, and the selection. */export interface Overlay {hits: number[];reads: number[];@@ -35,6 +35,8 @@ export interface Overlay {edit: number | null;current: number | null;names: NameLabel[];+ /** The inspector's selection, ringed. */+ selected: number | null;}/** One step of an animation, `t` from 0 to 1; t = 1 is the resting frame. */@@ -103,7 +105,7 @@ function placeName(layout: MapLayout, taken: Set<number>, f: PlacedFile, color:}/** Names for the edit and the current step (amber) first, then the opened files, newest first. */-function namesFor(layout: MapLayout, o: Omit<Overlay, "names">): NameLabel[] {+function namesFor(layout: MapLayout, o: Pick<Overlay, "reads" | "edit" | "current">): NameLabel[] {const pal = MAP_PALETTES[layout.style.theme];const order = [...new Set([o.edit, o.current, ...[...o.reads].reverse()].filter((i): i is number => i !== null))];const taken = new Set<number>();@@ -113,8 +115,8 @@ function namesFor(layout: MapLayout, o: Omit<Overlay, "names">): NameLabel[] {.filter((n): n is NameLabel => n !== null);}-/** The lit files on this layout, with their names placed. */-export function resolveLit(layout: MapLayout, lit: Lit): Overlay {+/** The lit files on this layout, with their names placed; `selected` (a path) is ringed. */+export function resolveLit(layout: MapLayout, lit: Lit, selected: string | null = null): Overlay {const o = {hits: indices(layout, lit.hits),reads: indices(layout, lit.reads),@@ -124,7 +126,7 @@ export function resolveLit(layout: MapLayout, lit: Lit): Overlay {edit: one(layout, lit.edit),current: one(layout, lit.current),};- return { ...o, names: namesFor(layout, o) };+ return { ...o, names: namesFor(layout, o), selected: one(layout, selected) };}function center(layout: MapLayout, f: PlacedFile): [number, number] {@@ -191,6 +193,27 @@ function rippleReach(layout: MapLayout, overlay: Overlay, anim: Anim | undefinedreturn anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;}+const inRange = (v: number, n: number): boolean => v >= 0 && v < n;++function set(p: Paint, x: number, y: number, color: number): void {+ if (!inRange(x, p.layout.width) || !inRange(y, p.layout.height)) return;+ p.px[y * p.layout.width + x] = color;+ p.marked[y * p.layout.width + x] = 1;+}++/** The pixels around a box (one outside it on every side). */+function around(box: { x0: number; y0: number; x1: number; y1: number }): [number, number][] {+ const out: [number, number][] = [];+ for (let x = box.x0 - 1; x <= box.x1; x++) out.push([x, box.y0 - 1], [x, box.y1]);+ for (let y = box.y0; y < box.y1; y++) out.push([box.x0 - 1, y], [box.x1, y]);+ return out;+}++/** The inspector's ring: the pixels just around the selected tile, in the theme's brightest neutral. */+function paintSelection(p: Paint, f: PlacedFile, color: number): void {+ for (const [x, y] of around(litPixels(p.layout, f))) set(p, x, y, color);+}+/** Map pixels for one frame: the base with the turn's roles filled in, weakest first so the strongest shows. */export function framePixels(layout: MapLayout, overlay: Overlay, anim?: Anim): { pixels: Uint32Array; marked: Uint8Array } {const p: Paint = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };@@ -203,6 +226,8 @@ export function framePixels(layout: MapLayout, overlay: Overlay, anim?: Anim): {fillAll(p, [overlay.edit, overlay.current].filter((i): i is number => i !== null), pal.edit);const origin = overlay.edit === null ? undefined : layout.files[overlay.edit];if (origin !== undefined && reach < Infinity) paintRing(p, origin, reach, pal.importer);+ const selected = overlay.selected === null ? undefined : layout.files[overlay.selected];+ if (selected !== undefined) paintSelection(p, selected, pal.ring);return { pixels: p.px, marked: p.marked };}diff --git a/packages/claude-mod/test/fixtures/django-blast-radius-conf-depth1.json b/packages/claude-mod/test/fixtures/django-blast-radius-conf-depth1.jsonnew file mode 100644index 000000000..6841cbb3e--- /dev/null+++ b/packages/claude-mod/test/fixtures/django-blast-radius-conf-depth1.json@@ -0,0 +1,748 @@+{+ "transitive_affected": [+ {+ "path": "django/__init__.py"+ },+ {+ "path": "django/apps/config.py"+ },+ {+ "path": "django/apps/registry.py"+ },+ {+ "path": "django/conf/urls/i18n.py"+ },+ {+ "path": "django/conf/urls/static.py"+ },+ {+ "path": "django/contrib/admin/checks.py"+ },+ {+ "path": "django/contrib/admin/migrations/0001_initial.py"+ },+ {+ "path": "django/contrib/admin/models.py"+ },+ {+ "path": "django/contrib/admin/options.py"+ },+ {+ "path": "django/contrib/admin/sites.py"+ },+ {+ "path": "django/contrib/admin/views/main.py"+ },+ {+ "path": "django/contrib/admin/widgets.py"+ },+ {+ "path": "django/contrib/admindocs/middleware.py"+ },+ {+ "path": "django/contrib/auth/__init__.py"+ },+ {+ "path": "django/contrib/auth/admin.py"+ },+ {+ "path": "django/contrib/auth/base_user.py"+ },+ {+ "path": "django/contrib/auth/checks.py"+ },+ {+ "path": "django/contrib/auth/decorators.py"+ },+ {+ "path": "django/contrib/auth/hashers.py"+ },+ {+ "path": "django/contrib/auth/middleware.py"+ },+ {+ "path": "django/contrib/auth/mixins.py"+ },+ {+ "path": "django/contrib/auth/password_validation.py"+ },+ {+ "path": "django/contrib/auth/tokens.py"+ },+ {+ "path": "django/contrib/auth/views.py"+ },+ {+ "path": "django/contrib/flatpages/forms.py"+ },+ {+ "path": "django/contrib/flatpages/middleware.py"+ },+ {+ "path": "django/contrib/flatpages/templatetags/flatpages.py"+ },+ {+ "path": "django/contrib/flatpages/views.py"+ },+ {+ "path": "django/contrib/gis/db/backends/postgis/operations.py"+ },+ {+ "path": "django/contrib/gis/db/backends/spatialite/base.py"+ },+ {+ "path": "django/contrib/gis/gdal/libgdal.py"+ },+ {+ "path": "django/contrib/gis/geoip2.py"+ },+ {+ "path": "django/contrib/gis/geos/libgeos.py"+ },+ {+ "path": "django/contrib/gis/shortcuts.py"+ },+ {+ "path": "django/contrib/messages/middleware.py"+ },+ {+ "path": "django/contrib/messages/storage/__init__.py"+ },+ {+ "path": "django/contrib/messages/storage/base.py"+ },+ {+ "path": "django/contrib/messages/storage/cookie.py"+ },+ {+ "path": "django/contrib/messages/utils.py"+ },+ {+ "path": "django/contrib/redirects/middleware.py"+ },+ {+ "path": "django/contrib/sessions/backends/base.py"+ },+ {+ "path": "django/contrib/sessions/backends/cache.py"+ },+ {+ "path": "django/contrib/sessions/backends/cached_db.py"+ },+ {+ "path": "django/contrib/sessions/backends/file.py"+ },+ {+ "path": "django/contrib/sessions/management/commands/clearsessions.py"+ },+ {+ "path": "django/contrib/sessions/middleware.py"+ },+ {+ "path": "django/contrib/sitemaps/__init__.py"+ },+ {+ "path": "django/contrib/sites/checks.py"+ },+ {+ "path": "django/contrib/sites/management.py"+ },+ {+ "path": "django/contrib/sites/managers.py"+ },+ {+ "path": "django/contrib/sites/models.py"+ },+ {+ "path": "django/contrib/staticfiles/checks.py"+ },+ {+ "path": "django/contrib/staticfiles/finders.py"+ },+ {+ "path": "django/contrib/staticfiles/handlers.py"+ },+ {+ "path": "django/contrib/staticfiles/management/commands/runserver.py"+ },+ {+ "path": "django/contrib/staticfiles/storage.py"+ },+ {+ "path": "django/contrib/staticfiles/urls.py"+ },+ {+ "path": "django/contrib/staticfiles/utils.py"+ },+ {+ "path": "django/contrib/staticfiles/views.py"+ },+ {+ "path": "django/core/cache/backends/db.py"+ },+ {+ "path": "django/core/checks/caches.py"+ },+ {+ "path": "django/core/checks/compatibility/django_4_0.py"+ },+ {+ "path": "django/core/checks/files.py"+ },+ {+ "path": "django/core/checks/mail.py"+ },+ {+ "path": "django/core/checks/messages.py"+ },+ {+ "path": "django/core/checks/model_checks.py"+ },+ {+ "path": "django/core/checks/security/base.py"+ },+ {+ "path": "django/core/checks/security/csrf.py"+ },+ {+ "path": "django/core/checks/security/sessions.py"+ },+ {+ "path": "django/core/checks/translation.py"+ },+ {+ "path": "django/core/checks/urls.py"+ },+ {+ "path": "django/core/files/storage/__init__.py"+ },+ {+ "path": "django/core/files/storage/filesystem.py"+ },+ {+ "path": "django/core/files/storage/handler.py"+ },+ {+ "path": "django/core/files/storage/memory.py"+ },+ {+ "path": "django/core/files/uploadedfile.py"+ },+ {+ "path": "django/core/files/uploadhandler.py"+ },+ {+ "path": "django/core/handlers/asgi.py"+ },+ {+ "path": "django/core/handlers/base.py"+ },+ {+ "path": "django/core/handlers/exception.py"+ },+ {+ "path": "django/core/handlers/wsgi.py"+ },+ {+ "path": "django/core/mail/__init__.py"+ },+ {+ "path": "django/core/mail/backends/filebased.py"+ },+ {+ "path": "django/core/mail/backends/smtp.py"+ },+ {+ "path": "django/core/mail/deprecation.py"+ },+ {+ "path": "django/core/mail/handler.py"+ },+ {+ "path": "django/core/mail/message.py"+ },+ {+ "path": "django/core/management/__init__.py"+ },+ {+ "path": "django/core/management/commands/compilemessages.py"+ },+ {+ "path": "django/core/management/commands/createcachetable.py"+ },+ {+ "path": "django/core/management/commands/diffsettings.py"+ },+ {+ "path": "django/core/management/commands/listurls.py"+ },+ {+ "path": "django/core/management/commands/loaddata.py"+ },+ {+ "path": "django/core/management/commands/makemessages.py"+ },+ {+ "path": "django/core/management/commands/makemigrations.py"+ },+ {+ "path": "django/core/management/commands/runserver.py"+ },+ {+ "path": "django/core/management/commands/squashmigrations.py"+ },+ {+ "path": "django/core/management/commands/test.py"+ },+ {+ "path": "django/core/management/templates.py"+ },+ {+ "path": "django/core/serializers/__init__.py"+ },+ {+ "path": "django/core/serializers/xml_serializer.py"+ },+ {+ "path": "django/core/servers/basehttp.py"+ },+ {+ "path": "django/core/signing.py"+ },+ {+ "path": "django/db/backends/base/base.py"+ },+ {+ "path": "django/db/backends/base/creation.py"+ },+ {+ "path": "django/db/backends/base/operations.py"+ },+ {+ "path": "django/db/backends/base/schema.py"+ },+ {+ "path": "django/db/backends/mysql/operations.py"+ },+ {+ "path": "django/db/backends/oracle/base.py"+ },+ {+ "path": "django/db/backends/oracle/creation.py"+ },+ {+ "path": "django/db/backends/oracle/operations.py"+ },+ {+ "path": "django/db/backends/postgresql/base.py"+ },+ {+ "path": "django/db/backends/postgresql/operations.py"+ },+ {+ "path": "django/db/backends/sqlite3/operations.py"+ },+ {+ "path": "django/db/migrations/autodetector.py"+ },+ {+ "path": "django/db/migrations/loader.py"+ },+ {+ "path": "django/db/migrations/serializer.py"+ },+ {+ "path": "django/db/migrations/state.py"+ },+ {+ "path": "django/db/migrations/writer.py"+ },+ {+ "path": "django/db/models/base.py"+ },+ {+ "path": "django/db/models/fields/__init__.py"+ },+ {+ "path": "django/db/models/fields/related.py"+ },+ {+ "path": "django/db/models/functions/datetime.py"+ },+ {+ "path": "django/db/models/options.py"+ },+ {+ "path": "django/db/models/query.py"+ },+ {+ "path": "django/db/models/utils.py"+ },+ {+ "path": "django/db/utils.py"+ },+ {+ "path": "django/dispatch/dispatcher.py"+ },+ {+ "path": "django/forms/renderers.py"+ },+ {+ "path": "django/forms/utils.py"+ },+ {+ "path": "django/http/multipartparser.py"+ },+ {+ "path": "django/http/request.py"+ },+ {+ "path": "django/http/response.py"+ },+ {+ "path": "django/middleware/cache.py"+ },+ {+ "path": "django/middleware/clickjacking.py"+ },+ {+ "path": "django/middleware/common.py"+ },+ {+ "path": "django/middleware/csp.py"+ },+ {+ "path": "django/middleware/csrf.py"+ },+ {+ "path": "django/middleware/locale.py"+ },+ {+ "path": "django/middleware/security.py"+ },+ {+ "path": "django/tasks/backends/base.py"+ },+ {+ "path": "django/template/backends/django.py"+ },+ {+ "path": "django/template/backends/jinja2.py"+ },+ {+ "path": "django/template/context_processors.py"+ },+ {+ "path": "django/template/defaulttags.py"+ },+ {+ "path": "django/template/utils.py"+ },+ {+ "path": "django/templatetags/i18n.py"+ },+ {+ "path": "django/templatetags/static.py"+ },+ {+ "path": "django/test/client.py"+ },+ {+ "path": "django/test/selenium.py"+ },+ {+ "path": "django/test/signals.py"+ },+ {+ "path": "django/test/testcases.py"+ },+ {+ "path": "django/test/utils.py"+ },+ {+ "path": "django/urls/resolvers.py"+ },+ {+ "path": "django/utils/cache.py"+ },+ {+ "path": "django/utils/connection.py"+ },+ {+ "path": "django/utils/crypto.py"+ },+ {+ "path": "django/utils/formats.py"+ },+ {+ "path": "django/utils/html.py"+ },+ {+ "path": "django/utils/log.py"+ },+ {+ "path": "django/utils/numberformat.py"+ },+ {+ "path": "django/utils/timezone.py"+ },+ {+ "path": "django/utils/translation/__init__.py"+ },+ {+ "path": "django/utils/translation/reloader.py"+ },+ {+ "path": "django/utils/translation/trans_null.py"+ },+ {+ "path": "django/utils/translation/trans_real.py"+ },+ {+ "path": "django/views/csrf.py"+ },+ {+ "path": "django/views/debug.py"+ },+ {+ "path": "django/views/generic/dates.py"+ },+ {+ "path": "django/views/i18n.py"+ },+ {+ "path": "scripts/manage_translations.py"+ },+ {+ "path": "tests/admin_docs/test_views.py"+ },+ {+ "path": "tests/admin_scripts/configured_dynamic_settings_manage.py"+ },+ {+ "path": "tests/admin_scripts/configured_settings_manage.py"+ },+ {+ "path": "tests/admin_scripts/tests.py"+ },+ {+ "path": "tests/admin_utils/tests.py"+ },+ {+ "path": "tests/admin_widgets/tests.py"+ },+ {+ "path": "tests/auth_tests/test_basic.py"+ },+ {+ "path": "tests/auth_tests/test_decorators.py"+ },+ {+ "path": "tests/auth_tests/test_management.py"+ },+ {+ "path": "tests/auth_tests/test_middleware.py"+ },+ {+ "path": "tests/auth_tests/test_remote_user.py"+ },+ {+ "path": "tests/auth_tests/test_tokens.py"+ },+ {+ "path": "tests/auth_tests/test_views.py"+ },+ {+ "path": "tests/cache/tests.py"+ },+ {+ "path": "tests/check_framework/test_security.py"+ },+ {+ "path": "tests/check_framework/test_urls.py"+ },+ {+ "path": "tests/contenttypes_tests/test_operations.py"+ },+ {+ "path": "tests/contenttypes_tests/test_views.py"+ },+ {+ "path": "tests/csrf_tests/tests.py"+ },+ {+ "path": "tests/db_functions/datetime/test_extract_trunc.py"+ },+ {+ "path": "tests/decorators/test_csrf.py"+ },+ {+ "path": "tests/deprecation/test_signed_cookie_legacy_salt_fallback.py"+ },+ {+ "path": "tests/deprecation/test_use_blank_choice_dash.py"+ },+ {+ "path": "tests/file_storage/tests.py"+ },+ {+ "path": "tests/file_uploads/tests.py"+ },+ {+ "path": "tests/flatpages_tests/test_forms.py"+ },+ {+ "path": "tests/flatpages_tests/test_middleware.py"+ },+ {+ "path": "tests/flatpages_tests/test_views.py"+ },+ {+ "path": "tests/forms_tests/tests/test_forms.py"+ },+ {+ "path": "tests/gis_tests/geoapp/test_feeds.py"+ },+ {+ "path": "tests/gis_tests/geoapp/test_sitemaps.py"+ },+ {+ "path": "tests/gis_tests/layermap/tests.py"+ },+ {+ "path": "tests/gis_tests/test_geoip2.py"+ },+ {+ "path": "tests/gis_tests/utils.py"+ },+ {+ "path": "tests/i18n/patterns/tests.py"+ },+ {+ "path": "tests/i18n/tests.py"+ },+ {+ "path": "tests/indexes/tests.py"+ },+ {+ "path": "tests/logging_tests/logconfig.py"+ },+ {+ "path": "tests/logging_tests/tests.py"+ },+ {+ "path": "tests/mail/__init__.py"+ },+ {+ "path": "tests/mail/test_deprecated.py"+ },+ {+ "path": "tests/mail/tests.py"+ },+ {+ "path": "tests/messages_tests/test_cookie.py"+ },+ {+ "path": "tests/messages_tests/tests.py"+ },+ {+ "path": "tests/middleware/tests.py"+ },+ {+ "path": "tests/middleware_exceptions/tests.py"+ },+ {+ "path": "tests/migrations/test_autodetector.py"+ },+ {+ "path": "tests/migrations/test_loader.py"+ },+ {+ "path": "tests/migrations/test_migrations_custom_user/0001_initial.py"+ },+ {+ "path": "tests/migrations/test_writer.py"+ },+ {+ "path": "tests/model_indexes/tests.py"+ },+ {+ "path": "tests/model_options/test_tablespaces.py"+ },+ {+ "path": "tests/project_template/test_settings.py"+ },+ {+ "path": "tests/redirects_tests/tests.py"+ },+ {+ "path": "tests/responses/tests.py"+ },+ {+ "path": "tests/runtests.py"+ },+ {+ "path": "tests/servers/tests.py"+ },+ {+ "path": "tests/sessions_tests/tests.py"+ },+ {+ "path": "tests/settings_tests/tests.py"+ },+ {+ "path": "tests/shell/tests.py"+ },+ {+ "path": "tests/sites_tests/tests.py"+ },+ {+ "path": "tests/staticfiles_tests/cases.py"+ },+ {+ "path": "tests/staticfiles_tests/storage.py"+ },+ {+ "path": "tests/staticfiles_tests/test_checks.py"+ },+ {+ "path": "tests/staticfiles_tests/test_finders.py"+ },+ {+ "path": "tests/staticfiles_tests/test_forms.py"+ },+ {+ "path": "tests/staticfiles_tests/test_management.py"+ },+ {+ "path": "tests/staticfiles_tests/test_storage.py"+ },+ {+ "path": "tests/staticfiles_tests/test_templatetags.py"+ },+ {+ "path": "tests/staticfiles_tests/test_views.py"+ },+ {+ "path": "tests/template_tests/syntax_tests/i18n/base.py"+ },+ {+ "path": "tests/template_tests/syntax_tests/test_static.py"+ },+ {+ "path": "tests/test_client_regress/views.py"+ },+ {+ "path": "tests/test_runner/tests.py"+ },+ {+ "path": "tests/test_utils/tests.py"+ },+ {+ "path": "tests/urlpatterns_reverse/tests.py"+ },+ {+ "path": "tests/view_tests/tests/test_i18n.py"+ }+ ]+}diff --git a/packages/claude-mod/test/fixtures/lit-frames-map-commit.json b/packages/claude-mod/test/fixtures/lit-frames-map-commit.jsonnew file mode 100644index 000000000..80ff48366--- /dev/null+++ b/packages/claude-mod/test/fixtures/lit-frames-map-commit.json@@ -0,0 +1,266 @@+{+ "query 110x24 dark rest": "636b0d5b776135b6",+ "query 110x24 dark ripple@0": "5c95b0aa60e7555b",+ "query 110x24 dark [email protected]": "45283d09b151241d",+ "query 110x24 dark [email protected]": "53ea30a728602ece",+ "query 110x24 dark [email protected]": "fb3a76adecad2e74",+ "query 110x24 dark [email protected]": "16fc32ed01ee21ba",+ "query 110x24 dark [email protected]": "0efdc020d91b8e96",+ "query 110x24 dark ripple@1": "636b0d5b776135b6",+ "query 110x24 dark flash@0": "58b75c956db3c29e",+ "query 110x24 dark [email protected]": "a87812265c6ec2d8",+ "query 110x24 dark flash@1": "636b0d5b776135b6",+ "query 110x24 light rest": "f8e9419cb677f053",+ "query 110x24 light ripple@0": "404b46ed09f55f35",+ "query 110x24 light [email protected]": "393fda8de8151737",+ "query 110x24 light [email protected]": "04ad1f48d85ce752",+ "query 110x24 light [email protected]": "339e4bf509b1998f",+ "query 110x24 light [email protected]": "ddce3f07b8c28b8e",+ "query 110x24 light [email protected]": "c78f7bf7015a8c5c",+ "query 110x24 light ripple@1": "f8e9419cb677f053",+ "query 110x24 light flash@0": "5b6b7d1147e1cebd",+ "query 110x24 light [email protected]": "eac82bf063478cd6",+ "query 110x24 light flash@1": "f8e9419cb677f053",+ "query 110x24 dark+health rest": "144872f70be4c108",+ "query 110x24 dark+health ripple@0": "9e5dc57bd1a24aea",+ "query 110x24 dark+health [email protected]": "73b5a4a57e03e831",+ "query 110x24 dark+health [email protected]": "8ebd15cc6ae3d0e2",+ "query 110x24 dark+health [email protected]": "e8911d0df42bf5ee",+ "query 110x24 dark+health [email protected]": "ee5b907002c568c7",+ "query 110x24 dark+health [email protected]": "0c1d40a770f91b35",+ "query 110x24 dark+health ripple@1": "144872f70be4c108",+ "query 110x24 dark+health flash@0": "f2a002bfc4fd8a5a",+ "query 110x24 dark+health [email protected]": "50c6836d5f729850",+ "query 110x24 dark+health flash@1": "144872f70be4c108",+ "query 110x40 dark rest": "73bbbe65024b92c6",+ "query 110x40 dark ripple@0": "e3c48a3d9c2b05b4",+ "query 110x40 dark [email protected]": "91a092fb50e458e0",+ "query 110x40 dark [email protected]": "c8256951d23fd315",+ "query 110x40 dark [email protected]": "26e4e21549650bd8",+ "query 110x40 dark [email protected]": "b68e114d09ffa803",+ "query 110x40 dark [email protected]": "aa6240006791cecf",+ "query 110x40 dark ripple@1": "73bbbe65024b92c6",+ "query 110x40 dark flash@0": "ac33792d7fff02ab",+ "query 110x40 dark [email protected]": "f90d187a741f6b9d",+ "query 110x40 dark flash@1": "73bbbe65024b92c6",+ "query 110x40 light rest": "dc788d84d59ede9a",+ "query 110x40 light ripple@0": "9ba00ac571ce379e",+ "query 110x40 light [email protected]": "c35f1099c382fd33",+ "query 110x40 light [email protected]": "266c668d0a68180b",+ "query 110x40 light [email protected]": "9c953b9071e11f62",+ "query 110x40 light [email protected]": "79cc684aa8be5a9f",+ "query 110x40 light [email protected]": "bd800ebf688569f2",+ "query 110x40 light ripple@1": "dc788d84d59ede9a",+ "query 110x40 light flash@0": "e5d8e584fd48576a",+ "query 110x40 light [email protected]": "20f4e99180aa1d07",+ "query 110x40 light flash@1": "dc788d84d59ede9a",+ "query 110x40 dark+health rest": "ecdfe84bc9b60cd9",+ "query 110x40 dark+health ripple@0": "5978339622f2f9ea",+ "query 110x40 dark+health [email protected]": "c1800c5ce2c7afb8",+ "query 110x40 dark+health [email protected]": "630a1ea543a32738",+ "query 110x40 dark+health [email protected]": "dd2d7442c75a8286",+ "query 110x40 dark+health [email protected]": "73406b890c4a4d84",+ "query 110x40 dark+health [email protected]": "8e4d0a80df4ce816",+ "query 110x40 dark+health ripple@1": "ecdfe84bc9b60cd9",+ "query 110x40 dark+health flash@0": "43b702e7ec813c43",+ "query 110x40 dark+health [email protected]": "918262c605800f7c",+ "query 110x40 dark+health flash@1": "ecdfe84bc9b60cd9",+ "query 180x48 dark rest": "63734e763458c38b",+ "query 180x48 dark ripple@0": "44b30ee84ba70adc",+ "query 180x48 dark [email protected]": "0c4aac65df59bbec",+ "query 180x48 dark [email protected]": "68916104fe3ecd97",+ "query 180x48 dark [email protected]": "8c0560bd74416c11",+ "query 180x48 dark [email protected]": "007e58414be8e458",+ "query 180x48 dark [email protected]": "a5e38d84bbbc2678",+ "query 180x48 dark ripple@1": "63734e763458c38b",+ "query 180x48 dark flash@0": "dc92db331023f459",+ "query 180x48 dark [email protected]": "3c4bd535b175435f",+ "query 180x48 dark flash@1": "63734e763458c38b",+ "query 180x48 light rest": "4c9c82863a205fe9",+ "query 180x48 light ripple@0": "63ae1348d5bfa7dd",+ "query 180x48 light [email protected]": "2441dbae172e54c4",+ "query 180x48 light [email protected]": "d942eb0eebb0a6b0",+ "query 180x48 light [email protected]": "cfccabcf3d544fff",+ "query 180x48 light [email protected]": "a2f6e1cae832b049",+ "query 180x48 light [email protected]": "69562bf47d305ac2",+ "query 180x48 light ripple@1": "4c9c82863a205fe9",+ "query 180x48 light flash@0": "8987ea8239457298",+ "query 180x48 light [email protected]": "5e2b35be4800baa0",+ "query 180x48 light flash@1": "4c9c82863a205fe9",+ "query 180x48 dark+health rest": "75abd20f181ce16b",+ "query 180x48 dark+health ripple@0": "ece1783270ba2495",+ "query 180x48 dark+health [email protected]": "33ec837dfe5317f8",+ "query 180x48 dark+health [email protected]": "a06beabfa3790d8f",+ "query 180x48 dark+health [email protected]": "a1ee2426f1213cf8",+ "query 180x48 dark+health [email protected]": "12e36e45e1b64e3c",+ "query 180x48 dark+health [email protected]": "212cbcd6e1f82710",+ "query 180x48 dark+health ripple@1": "75abd20f181ce16b",+ "query 180x48 dark+health flash@0": "526d594997d81d24",+ "query 180x48 dark+health [email protected]": "511da32d68d01135",+ "query 180x48 dark+health flash@1": "75abd20f181ce16b",+ "query 180x60 dark rest": "d8458367ff806303",+ "query 180x60 dark ripple@0": "a020f42f306327c9",+ "query 180x60 dark [email protected]": "ea89fbb2b94208f4",+ "query 180x60 dark [email protected]": "ef4b303360bf960d",+ "query 180x60 dark [email protected]": "0e3037961ec8cf7e",+ "query 180x60 dark [email protected]": "3502a21eee8ed9ee",+ "query 180x60 dark [email protected]": "e40004a59b307e36",+ "query 180x60 dark ripple@1": "d8458367ff806303",+ "query 180x60 dark flash@0": "609014f6c79a3171",+ "query 180x60 dark [email protected]": "a2cb96d2513c8aff",+ "query 180x60 dark flash@1": "d8458367ff806303",+ "query 180x60 light rest": "c69a8e60e7b02c33",+ "query 180x60 light ripple@0": "2313a9f5ba252b44",+ "query 180x60 light [email protected]": "1899d8243aec02a1",+ "query 180x60 light [email protected]": "1cf0ca6460e4d337",+ "query 180x60 light [email protected]": "a8d72da891ffa57c",+ "query 180x60 light [email protected]": "95b529d2774246b6",+ "query 180x60 light [email protected]": "5388a027c1c277a0",+ "query 180x60 light ripple@1": "c69a8e60e7b02c33",+ "query 180x60 light flash@0": "8a4faebcc57c1ad2",+ "query 180x60 light [email protected]": "615f03b53cbb00d7",+ "query 180x60 light flash@1": "c69a8e60e7b02c33",+ "query 180x60 dark+health rest": "43d2017696ef2310",+ "query 180x60 dark+health ripple@0": "8dc1a28faf4f36e4",+ "query 180x60 dark+health [email protected]": "f4d6a95ede0cea12",+ "query 180x60 dark+health [email protected]": "2afd9adce650b046",+ "query 180x60 dark+health [email protected]": "92c4027fb670e50c",+ "query 180x60 dark+health [email protected]": "bdb03d0b7eeb9cb8",+ "query 180x60 dark+health [email protected]": "ee3eb31d861a2b3f",+ "query 180x60 dark+health ripple@1": "43d2017696ef2310",+ "query 180x60 dark+health flash@0": "3ecf273f17587822",+ "query 180x60 dark+health [email protected]": "a8bc37e60c870e84",+ "query 180x60 dark+health flash@1": "43d2017696ef2310",+ "conf 110x24 dark rest": "e387fb4f7c2cf3d6",+ "conf 110x24 dark ripple@0": "a1c159d406a539b6",+ "conf 110x24 dark [email protected]": "71f9262c843bc7c2",+ "conf 110x24 dark [email protected]": "ada59f791b19cec5",+ "conf 110x24 dark [email protected]": "458fac91e3420c83",+ "conf 110x24 dark [email protected]": "4ddd69e5ab58735c",+ "conf 110x24 dark [email protected]": "4cb9706b5876fae1",+ "conf 110x24 dark ripple@1": "e387fb4f7c2cf3d6",+ "conf 110x24 dark flash@0": "d1d1cc6c0694e6db",+ "conf 110x24 dark [email protected]": "d0c731d12f3f9c0c",+ "conf 110x24 dark flash@1": "e387fb4f7c2cf3d6",+ "conf 110x24 light rest": "4ba4ce2edff6ae85",+ "conf 110x24 light ripple@0": "52c4634b91f0285e",+ "conf 110x24 light [email protected]": "52f609f4cedf1912",+ "conf 110x24 light [email protected]": "031cf6c41199f06a",+ "conf 110x24 light [email protected]": "051ab6654c8eb121",+ "conf 110x24 light [email protected]": "9064593df566e511",+ "conf 110x24 light [email protected]": "3f2603ab72755629",+ "conf 110x24 light ripple@1": "4ba4ce2edff6ae85",+ "conf 110x24 light flash@0": "97af733335a8aaf6",+ "conf 110x24 light [email protected]": "75fae3ba27702370",+ "conf 110x24 light flash@1": "4ba4ce2edff6ae85",+ "conf 110x24 dark+health rest": "8f6e523d9c5b2122",+ "conf 110x24 dark+health ripple@0": "ef0623b90608a80b",+ "conf 110x24 dark+health [email protected]": "3497d9bea02bf245",+ "conf 110x24 dark+health [email protected]": "56562dc6c38ef32b",+ "conf 110x24 dark+health [email protected]": "80da5d69effdb1ce",+ "conf 110x24 dark+health [email protected]": "c758b6cafebf1bfd",+ "conf 110x24 dark+health [email protected]": "f774a0b8548ad34b",+ "conf 110x24 dark+health ripple@1": "8f6e523d9c5b2122",+ "conf 110x24 dark+health flash@0": "d77c08e24c1054dd",+ "conf 110x24 dark+health [email protected]": "8a4f42b9c295b902",+ "conf 110x24 dark+health flash@1": "8f6e523d9c5b2122",+ "conf 110x40 dark rest": "1a0f7038e543da1c",+ "conf 110x40 dark ripple@0": "29051c0abfad4863",+ "conf 110x40 dark [email protected]": "faa56b6e58918ed9",+ "conf 110x40 dark [email protected]": "d7bc2b72014ea31e",+ "conf 110x40 dark [email protected]": "a041dcb51f153ca8",+ "conf 110x40 dark [email protected]": "89b384f5c3af58b3",+ "conf 110x40 dark [email protected]": "0faad093e4bf4667",+ "conf 110x40 dark ripple@1": "1a0f7038e543da1c",+ "conf 110x40 dark flash@0": "bd13a55db63c672e",+ "conf 110x40 dark [email protected]": "689460b77b3dfca4",+ "conf 110x40 dark flash@1": "1a0f7038e543da1c",+ "conf 110x40 light rest": "496d1764cedde0aa",+ "conf 110x40 light ripple@0": "f3d20d3085253d8d",+ "conf 110x40 light [email protected]": "54d5f63165953b36",+ "conf 110x40 light [email protected]": "b28a372ee2eaacd2",+ "conf 110x40 light [email protected]": "1271a311bb251b86",+ "conf 110x40 light [email protected]": "24cd5a05e2ee3beb",+ "conf 110x40 light [email protected]": "d99cf5352b48b042",+ "conf 110x40 light ripple@1": "496d1764cedde0aa",+ "conf 110x40 light flash@0": "795fc4a8930adc1b",+ "conf 110x40 light [email protected]": "ffeb51095428baea",+ "conf 110x40 light flash@1": "496d1764cedde0aa",+ "conf 110x40 dark+health rest": "4ed02774999916cb",+ "conf 110x40 dark+health ripple@0": "f00778d4090f4d0e",+ "conf 110x40 dark+health [email protected]": "06799b2c07d17472",+ "conf 110x40 dark+health [email protected]": "42f103c3381e9ac3",+ "conf 110x40 dark+health [email protected]": "0c51714f3c339cf7",+ "conf 110x40 dark+health [email protected]": "e39f0fddb40ec3b5",+ "conf 110x40 dark+health [email protected]": "7db149d31cbcfa44",+ "conf 110x40 dark+health ripple@1": "4ed02774999916cb",+ "conf 110x40 dark+health flash@0": "9bb857a72c6ed2bc",+ "conf 110x40 dark+health [email protected]": "de9eebf5c4e5c315",+ "conf 110x40 dark+health flash@1": "4ed02774999916cb",+ "conf 180x48 dark rest": "e1c7a6591c023270",+ "conf 180x48 dark ripple@0": "67c7cf640ea54bf6",+ "conf 180x48 dark [email protected]": "54b95d2c305f6e85",+ "conf 180x48 dark [email protected]": "3bc7730b01dea4c0",+ "conf 180x48 dark [email protected]": "899c36b86e28bbbe",+ "conf 180x48 dark [email protected]": "8744548dd202fd66",+ "conf 180x48 dark [email protected]": "f46c757f68b12a84",+ "conf 180x48 dark ripple@1": "e1c7a6591c023270",+ "conf 180x48 dark flash@0": "16fb7d8820bf3daa",+ "conf 180x48 dark [email protected]": "862d9ac56d54e6ce",+ "conf 180x48 dark flash@1": "e1c7a6591c023270",+ "conf 180x48 light rest": "9ccf4c50c236d56d",+ "conf 180x48 light ripple@0": "a92a6ba7b87de698",+ "conf 180x48 light [email protected]": "2e156d7b0d5af3d9",+ "conf 180x48 light [email protected]": "8e27376341c9296a",+ "conf 180x48 light [email protected]": "3634c171413b0af2",+ "conf 180x48 light [email protected]": "1e1ee9ed3ba56dfe",+ "conf 180x48 light [email protected]": "a33f6cec22f89bfa",+ "conf 180x48 light ripple@1": "9ccf4c50c236d56d",+ "conf 180x48 light flash@0": "97a33786ae22468a",+ "conf 180x48 light [email protected]": "18f283e9733caace",+ "conf 180x48 light flash@1": "9ccf4c50c236d56d",+ "conf 180x48 dark+health rest": "25455f8d5fce311b",+ "conf 180x48 dark+health ripple@0": "22b411a4a3b5e045",+ "conf 180x48 dark+health [email protected]": "030879f8ae8aa53b",+ "conf 180x48 dark+health [email protected]": "1a4c70a2d2277ae1",+ "conf 180x48 dark+health [email protected]": "b8e2456d2b961706",+ "conf 180x48 dark+health [email protected]": "41e5363225626203",+ "conf 180x48 dark+health [email protected]": "8df5eb9352828a1d",+ "conf 180x48 dark+health ripple@1": "25455f8d5fce311b",+ "conf 180x48 dark+health flash@0": "5d0f27b9f2f8fde8",+ "conf 180x48 dark+health [email protected]": "8acec2fe6bb22b6c",+ "conf 180x48 dark+health flash@1": "25455f8d5fce311b",+ "conf 180x60 dark rest": "97a42796407546f2",+ "conf 180x60 dark ripple@0": "ab408a2ee7d99582",+ "conf 180x60 dark [email protected]": "4a2f8fae5288facc",+ "conf 180x60 dark [email protected]": "dd7c03931dea3db1",+ "conf 180x60 dark [email protected]": "44d09681b018f70c",+ "conf 180x60 dark [email protected]": "ed14fc9c69f824bc",+ "conf 180x60 dark [email protected]": "64880013ae6c05c2",+ "conf 180x60 dark ripple@1": "97a42796407546f2",+ "conf 180x60 dark flash@0": "f3de07e1589dd577",+ "conf 180x60 dark [email protected]": "aa039915234749d5",+ "conf 180x60 dark flash@1": "97a42796407546f2",+ "conf 180x60 light rest": "ba1c0c3a2608ff66",+ "conf 180x60 light ripple@0": "20e52c48bd5fa049",+ "conf 180x60 light [email protected]": "47935d14d8907039",+ "conf 180x60 light [email protected]": "ebf74c6ac936a692",+ "conf 180x60 light [email protected]": "29b17241ec65b0ae",+ "conf 180x60 light [email protected]": "e502cde7a0e6976d",+ "conf 180x60 light [email protected]": "99f971f03b5cd3a9",+ "conf 180x60 light ripple@1": "ba1c0c3a2608ff66",+ "conf 180x60 light flash@0": "632d39b4be528d05",+ "conf 180x60 light [email protected]": "0929cae4a68773d9",+ "conf 180x60 light flash@1": "ba1c0c3a2608ff66",+ "conf 180x60 dark+health rest": "4a1d6b9988e23bdc",+ "conf 180x60 dark+health ripple@0": "b884b2afdc4511b0",+ "conf 180x60 dark+health [email protected]": "3c0852869161a811",+ "conf 180x60 dark+health [email protected]": "89dbdb3fb5d81422",+ "conf 180x60 dark+health [email protected]": "2c30a3d343df8f67",+ "conf 180x60 dark+health [email protected]": "7c87149ac33f1a3c",+ "conf 180x60 dark+health [email protected]": "fa1684461d2c624b",+ "conf 180x60 dark+health ripple@1": "4a1d6b9988e23bdc",+ "conf 180x60 dark+health flash@0": "3be8054928cef07a",+ "conf 180x60 dark+health [email protected]": "7ddc6cc41cb92be3",+ "conf 180x60 dark+health flash@1": "4a1d6b9988e23bdc"+}diff --git a/packages/claude-mod/test/inspector.test.ts b/packages/claude-mod/test/inspector.test.tsnew file mode 100644index 000000000..5541caca9--- /dev/null+++ b/packages/claude-mod/test/inspector.test.ts@@ -0,0 +1,131 @@+// The inspector's cursor and detail line, and zoom,+// over the recorded Django feed and blast radius (test/django.ts).+import { describe, expect, it } from "vitest";+import { initialFlow, type FlowState } from "../src/model/flow";+import { KNOWS_NOTHING, knowsOf, litPaths, step, whyLit } from "../src/model/inspect";+import { NO_STORY } from "../src/model/story";+import { crumbLine, detailLine } from "../src/views/copy";+import type { Node } from "../src/views/elements";+import { MAP_PALETTES, folderAt, layoutMap } from "../src/views/map";+import { mapPaneView } from "../src/views/mapPane";+import { NO_LIT, framePixels, frameCells, litPixels, resolveLit, type Lit } from "../src/views/overlay";+import { decode, feed, importers } from "./django";+import { syntheticTree } from "./synthetic";++const QUERY = "django/db/models/query.py";+const MANAGER = "django/db/models/manager.py";+const BASE = "django/db/models/base.py";+const pal = MAP_PALETTES.dark;+const lit: Lit = { hits: ["tests/queries/tests.py"], reads: [MANAGER, QUERY], named: [QUERY], importers, edits: [QUERY], edit: QUERY, current: QUERY };+const story = { ...NO_STORY, edited: [{ name: "query.py", lines: { delta: 1 } as const }] };++describe("folder mode", () => {+ const dense = layoutMap(feed.files, { columns: 110, rows: 24, caseInsensitive: true });+ const o = resolveLit(dense, lit);++ it("importers keep their solid plum fill, with nothing written on it", () => {+ expect(dense.dense).toBe(true);+ const onMap = importers.filter((p) => dense.index.has(p.toLowerCase())).length;+ expect(o.importers).toHaveLength(onMap);+ const { pixels } = framePixels(dense, o);+ const opened = new Set(lit.reads.map((p) => p.toLowerCase()));+ const plum = o.importers.filter((i) => !opened.has(dense.files[i]!.path.toLowerCase()));+ expect(plum.length).toBeGreaterThan(0);+ for (const i of plum) {+ const b = litPixels(dense, dense.files[i]!);+ expect(pixels[b.y0 * dense.width + b.x0]).toBe(pal.importer);+ }+ const words = decode(frameCells(dense, o));+ const i = plum[0]!;+ const b = litPixels(dense, dense.files[i]!);+ expect(String.fromCharCode(words[((b.y0 >> 1) * dense.columns + b.x0) * 3]!)).toMatch(/[▀▄ ]/);+ });++ it("folderAt names the deepest folder drawn at a pixel (a gutter belongs to its group)", () => {+ const f = dense.files[dense.index.get(BASE)!]!;+ const b = litPixels(dense, f);+ expect(folderAt(dense, b.x0, b.y0)).toMatch(/^django\/db\/models/);+ expect(folderAt(dense, dense.width + 5, 0)).toBeNull();+ });+});++describe("the inspector", () => {+ it("visits the edit, then the opened files, then the other importers in the graph's order, then named files, each once", () => {+ const order = litPaths(lit);+ expect(order[0]).toBe(QUERY);+ expect(order[1]).toBe(MANAGER);+ expect(order.slice(2)).toEqual(importers.filter((p) => p !== MANAGER));+ expect(new Set(order.map((p) => p.toLowerCase())).size).toBe(order.length);+ });++ it("steps forward and back and wraps around; from nothing it starts at either end", () => {+ const order = litPaths(lit);+ expect(step(order, null, 1)).toBe(order[0]);+ expect(step(order, null, -1)).toBe(order.at(-1));+ expect(step(order, order.at(-1)!, 1)).toBe(order[0]);+ expect(step(order, order[0]!, -1)).toBe(order.at(-1));+ expect(step(order, "not/lit.py", 1)).toBe(order[0]);+ expect(step([], null, 1)).toBeNull();+ });++ it("the detail line: the path, why it is lit, and what the index already said", () => {+ const knows = { context: { callerFiles: 131, contributors: 172, hotspot: true, recentOwner: null }, tests: { total: 9, basis: "inferred" as const }, namedBy: "get_context" };+ expect(detailLine(QUERY, whyLit(QUERY, lit, story, knows), knows)).toBe(+ "django/db/models/query.py · Claude edited it, +1 line · named by get_context · hotspot · 131 files use it · 9 tests reach it (inferred)",+ );+ expect(detailLine(MANAGER, whyLit(MANAGER, lit, story, KNOWS_NOTHING), KNOWS_NOTHING)).toBe("django/db/models/manager.py · Claude opened it · imports query.py");+ expect(detailLine(BASE, whyLit(BASE, lit, story, KNOWS_NOTHING), KNOWS_NOTHING)).toBe("django/db/models/base.py · imports query.py");+ });++ it("what Lens knows comes from what it already holds: the file card, the edit's tests, the naming reply", () => {+ const card = { callerFiles: 3, contributors: 2, hotspot: false, recentOwner: null };+ const flow: FlowState = {+ ...initialFlow,+ blast: { [QUERY]: { importers: [], cochange: [], tests: { total: 4, files: [], basis: "measured" } } },+ named: { [QUERY]: { id: "toolu_rw", tool: "get_context", at: 1, turn: 1 } },+ };+ expect(knowsOf("Django/DB/models/query.py", { [QUERY]: card }, flow)).toEqual({ context: card, tests: { total: 4, basis: "measured" }, namedBy: "get_context" });+ expect(knowsOf(QUERY, {}, null)).toEqual(KNOWS_NOTHING);+ });++ it("the selected tile is ringed in the theme's brightest neutral, just outside it", () => {+ const layout = layoutMap(feed.files, { columns: 180, rows: 60, caseInsensitive: true });+ const o = resolveLit(layout, lit, BASE);+ const b = litPixels(layout, layout.files[o.selected!]!);+ const { pixels } = framePixels(layout, o);+ expect(pixels[(b.y0 - 1) * layout.width + b.x0]).toBe(pal.ring);+ expect(pixels[b.y0 * layout.width + b.x0]).toBe(pal.importer);+ });+});++describe("zoom", () => {+ const texts = (n: Node): string[] => (n.type === "Text" ? [n.children.join("")] : n.type === "Box" ? n.children.flatMap(texts) : []);++ it("lays out only the folder's files at the full size, named relative to it, with file names on big tiles", () => {+ const zoom = layoutMap(feed.files, { columns: 110, rows: 24, caseInsensitive: true, root: "django/db/models" });+ expect(zoom.root).toBe("django/db/models");+ expect(zoom.files.every((f) => f.path.startsWith("django/db/models/"))).toBe(true);+ expect(zoom.dense).toBe(false);+ expect(zoom.labels.some((l) => l.text === "query.py" || l.text === "__init__.py")).toBe(true);+ expect(zoom.labels.every((l) => !l.text.startsWith("django/"))).toBe(true);+ });++ it("keeps the turn's lighting, and shows where it is above the drawing", () => {+ const zoom = layoutMap(feed.files, { columns: 110, rows: 24, caseInsensitive: true, root: "django/db/models" });+ const o = resolveLit(zoom, lit, BASE);+ expect(o.edit).not.toBeNull();+ expect(o.importers.length).toBeGreaterThan(0);+ const view = mapPaneView(zoom, frameCells(zoom, o), { story: NO_STORY, reach: null, scope: { drawn: 1, shown: 1, repositoryTotal: 1, indexed: null, beyondCap: 0, dense: false, notOnMap: 3, zoom: zoom.root } });+ expect(texts(view)[0]).toBe("django / db / models");+ expect(texts(view)).toContain("1 file, all drawn · 3 touched files outside this folder");+ expect(crumbLine("a/b")).toBe("a / b");+ });++ it("works at both ends of scale: a 10,000-file tree (synthetic) zooms into one top folder", () => {+ const tree = syntheticTree(10_000).files.slice(0, 4_000);+ const zoom = layoutMap(tree, { columns: 120, rows: 24, caseInsensitive: true, root: "src" });+ expect(zoom.files.length).toBeGreaterThan(100);+ expect(zoom.files.every((f) => f.path.startsWith("src/"))).toBe(true);+ expect(resolveLit(zoom, NO_LIT).names).toEqual([]);+ });+});diff --git a/packages/claude-mod/test/lit-frames.test.ts b/packages/claude-mod/test/lit-frames.test.tsnew file mode 100644index 000000000..1d4222127--- /dev/null+++ b/packages/claude-mod/test/lit-frames.test.ts@@ -0,0 +1,40 @@+// The keys (the inspector's ring, zoom) must not change how the turn lights+// the map. test/fixtures/lit-frames-map-commit.json holds a hash of every frame+// the map commit painted for the inputs in ./lit-frames; with nothing selected,+// today's paint path must give the same frames.+import { createHash } from "node:crypto";+import { describe, expect, it } from "vitest";+import { layoutMap } from "../src/views/map";+import { frameCells, resolveLit, type Lit } from "../src/views/overlay";+import { feed } from "./django";+import { fixture } from "./fake-host";+import { SIZES, STEPS, STYLES, TURNS, caseName } from "./lit-frames";++const golden = JSON.parse(fixture("lit-frames-map-commit.json")) as Record<string, string>;+const hash = (cells: string): string => createHash("sha256").update(cells).digest("hex").slice(0, 16);++describe("lit colours and ripple frames, against the map commit", () => {+ it("covers files and folders: both kinds of map are in the golden", () => {+ const dense = SIZES.map(([columns, rows]) => layoutMap(feed.files, { columns, rows, caseInsensitive: true }).dense);+ expect(dense).toContain(true);+ expect(dense).toContain(false);+ });++ /** Every (size, style) layout, each once. */+ const layouts = SIZES.flatMap((size) => STYLES.map((style) => ({ size, style, layout: layoutMap(feed.files, { columns: size[0], rows: size[1], caseInsensitive: true, style }) })));++ /** The frames of one turn on one layout whose hash differs from the map commit's, by name. */+ function differing(turn: string, lit: Lit, at: (typeof layouts)[number]): string[] {+ const overlay = resolveLit(at.layout, lit);+ return STEPS.filter((step) => hash(frameCells(at.layout, overlay, step)) !== golden[caseName(turn, at.size, at.style, step)]).map((step) =>+ caseName(turn, at.size, at.style, step),+ );+ }++ for (const [turn, lit] of Object.entries(TURNS)) {+ it(`the ${turn} turn paints every frame as the map commit did`, () => {+ expect(layouts.flatMap((at) => differing(turn, lit, at))).toEqual([]);+ });+ }++});diff --git a/packages/claude-mod/test/lit-frames.ts b/packages/claude-mod/test/lit-frames.tsnew file mode 100644index 000000000..b37e458d7--- /dev/null+++ b/packages/claude-mod/test/lit-frames.ts@@ -0,0 +1,52 @@+// The inputs the lit-frame golden covers: two turns over the recorded Django+// feed (an edit of query.py, and one of conf/__init__.py with its 248+// importers), at sizes that draw files and sizes that draw folders, both+// themes, health colours on and off, and every animation step the pane plays.+import type { Lit } from "../src/views/overlay";+import type { ThemeName } from "../src/views/theme";+import { fixture } from "./fake-host";+import { importers as queryImporters } from "./django";++const CONF = "django/conf/__init__.py";+const QUERY = "django/db/models/query.py";+const confImporters = (JSON.parse(fixture("django-blast-radius-conf-depth1.json")) as { transitive_affected: { path: string }[] }).transitive_affected.map((t) => t.path);++export const TURNS: Record<string, Lit> = {+ query: {+ hits: ["tests/queries/tests.py", "django/db/models/sql/query.py"],+ reads: ["django/db/models/manager.py", QUERY],+ named: [QUERY, "django/db/models/base.py"],+ importers: queryImporters,+ edits: [QUERY],+ edit: QUERY,+ current: QUERY,+ },+ conf: {+ hits: ["django/conf/global_settings.py"],+ reads: [CONF, "django/core/management/__init__.py"],+ named: [CONF],+ importers: confImporters,+ edits: [CONF],+ edit: CONF,+ current: CONF,+ },+};++export const SIZES: [number, number][] = [+ [110, 24],+ [110, 40],+ [180, 48],+ [180, 60],+];++export const STYLES: { theme: ThemeName; health: boolean }[] = [+ { theme: "dark", health: false },+ { theme: "light", health: false },+ { theme: "dark", health: true },+];++type Step = { kind: "flash" | "ripple"; t: number } | undefined;+export const STEPS: Step[] = [undefined, ...[0, 0.1, 0.25, 0.5, 0.75, 0.9, 1].map((t) => ({ kind: "ripple" as const, t })), ...[0, 0.5, 1].map((t) => ({ kind: "flash" as const, t }))];++export const caseName = (turn: string, size: [number, number], style: { theme: string; health: boolean }, step: Step): string =>+ `${turn} ${size[0]}x${size[1]} ${style.theme}${style.health ? "+health" : ""} ${step === undefined ? "rest" : `${step.kind}@${step.t}`}`;diff --git a/packages/claude-mod/test/map-blast.test.ts b/packages/claude-mod/test/map-blast.test.tsnew file mode 100644index 000000000..8da4c062c--- /dev/null+++ b/packages/claude-mod/test/map-blast.test.ts@@ -0,0 +1,200 @@+// A wide edit through register(): Claude reads and edits django/conf/__init__.py,+// whose depth-1 blast radius (recorded from a re-indexed Django copy, paths only)+// names 248 importers. Every pane drawn after it must be a Raster the engine+// accepts, at a docked 110 and 180 columns, and a pane must never go blank.+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { Hook, ModApi, On } from "../src/mod-api";+import { decode } from "./django";+import { fixture, flatten, textOf, type Tree } from "./fake-host";++type Hooks = Record<string, Hook<any>>;++async function load(): Promise<Hooks> {+ vi.resetModules();+ const { register } = await import("../src/register");+ const hooks: Hooks = {};+ const on = ((event: string, a: unknown, b?: unknown) => {+ const m = b === undefined ? null : (a as { component?: string; command?: string; element?: string });+ hooks[m === null ? event : `${event}:${m.component ?? m.command ?? m.element}`] = (b ?? a) as Hook<any>;+ }) as On;+ register(on);+ return hooks;+}++const ROOT = "C:\\work\\django";+const SHA = "e78991410b78391bc07a4b5010b273dfec814ff6";+const CONF = `${ROOT}\\django\\conf\\__init__.py`;+const json = (body: unknown) => ({ status: 200, ok: true, headers: {}, text: JSON.stringify(body) });+const FILES: Record<string, string> = {+ "C:/work/django/.repowise/state.json": JSON.stringify({ last_sync_commit: SHA }),+ "C:/work/django/.repowise/serve.lock.json": fixture("locks/valid.json"),+};++function fullDollar() {+ const calls = { http: [] as string[], logs: [] as string[] };+ const $: ModApi = {+ session: { cwd: async () => ROOT },+ fs: { exists: async (p) => p.replace(/\\/g, "/") in FILES, read: async (p) => FILES[p.replace(/\\/g, "/")] ?? Promise.reject(new Error("ENOENT")) },+ process: {+ run: async (argv) => {+ if (argv[0] === "tasklist") return { exitCode: 0, stdout: '"python.exe","4242","Console"\r\n', stderr: "" };+ return { exitCode: 0, stdout: argv.includes("HEAD") ? `${SHA}\n` : "true\n", stderr: "" };+ },+ },+ http: {+ fetch: async (url) => {+ calls.http.push(url);+ if (url.endsWith("/health")) return json({ status: "healthy" });+ if (url.endsWith("/api/repos")) return json([{ id: "dj", name: "django", local_path: "c:/work/django/", updated_at: null }]);+ if (url.includes("/health/map")) return { status: 200, ok: true, headers: {}, text: fixture("django-health-map.json") };+ if (url.endsWith("/blast-radius")) return { status: 200, ok: true, headers: {}, text: fixture("django-blast-radius-conf-depth1.json") };+ return { status: 404, ok: false, headers: {}, text: "{}" };+ },+ },+ mcp: { connect: async () => ({ isConnected: false }), call: async () => Promise.reject(new Error("no MCP")) },+ prompt: { submit: async () => ({}) },+ ui: {+ invalidate: () => undefined,+ log: (text) => {+ calls.logs.push(text);+ },+ resolve: () => Object.fromEntries(["Box", "Text", "Button", "Input", "Markdown", "Raster", "Svg"].map((el) => [el, (props: Record<string, unknown>) => ({ el, props })])),+ open: async () => ({ isPlaced: true }),+ close: async () => undefined,+ blit: async () => ({}),+ },+ command: { register: async () => ({}) },+ config: { list: async () => [{ key: "theme", value: "dark" }] },+ settings: { read: async () => ({ prefersReducedMotion: true }) },+ };+ return { $, calls };+}++const wait = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));+async function until(check: () => boolean): Promise<void> {+ for (let i = 0; i < 300 && !check(); i++) await wait(5);+ expect(check()).toBe(true);+}++/** One width-1 BMP code point: printable, not a surrogate, not East Asian wide. */+const ONE_CELL = /^[^\u0000-\u001f\u007f-\u009f\ud800-\udfff\u1100-\u115f\u2e80-\ua4cf\uac00-\ud7a3\uf900-\ufaff\ufe30-\ufe4f\uff00-\uff60\uffe0-\uffe6]$/;++/** What the engine checks of a Raster: its size, its cells' count, each glyph one cell, at most 1,024 color pairs. */+function engineProblems(raster: { props: Record<string, unknown> }): string[] {+ const { columns, rows, cells } = raster.props as { columns: number; rows: number; cells: string };+ const words = decode(cells);+ const problems: string[] = [];+ if (columns > 512 || rows > 256) problems.push(`size ${columns}x${rows}`);+ if (words.length !== columns * rows * 3) problems.push(`${words.length} words for ${columns}x${rows}`);+ const pairs = new Set<string>();+ for (let i = 0; i < words.length; i += 3) {+ const ch = String.fromCodePoint(words[i]!);+ if (words[i]! > 0xffff || !ONE_CELL.test(ch)) problems.push(`cell ${i / 3}: U+${words[i]!.toString(16)}`);+ pairs.add(`${words[i + 1]}:${words[i + 2]}`);+ }+ if (pairs.size > 1024) problems.push(`${pairs.size} color pairs`);+ return problems.slice(0, 5);+}++let hooks: Hooks;+beforeEach(async () => {+ hooks = await load();+});++describe("a wide edit: django/conf/__init__.py and its 248 importers", () => {+ for (const [columns, rows] of [+ [110, 24],+ [180, 48],+ ] as const) {+ it(`draws an engine-valid map at ${columns} columns, ${rows} rows, before and after the importers land`, async () => {+ const d = fullDollar();+ await hooks["session.start"]!(d.$, { cwd: ROOT }, async () => undefined);+ await until(() => d.calls.http.some((u) => u.endsWith("/api/repos")));+ await wait(10);+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));+ await until(() => d.calls.http.some((u) => u.includes("/health/map")));+ const PANE = { surface: "terminal", requestId: "lens", props: { bodyColumns: columns, placement: "dock", scroll: { bodyRows: rows } } };+ const render = async () => (await hooks["ui.render:Pane"]!(d.$, PANE, async () => ({ el: "theirs" }))) as Tree;+ const raster = async () => {+ let tree = await render();+ for (let i = 0; i < 100 && !flatten(tree).some((n) => n.el === "Raster"); i++) {+ await wait(5);+ tree = await render();+ }+ return { tree, raster: flatten(tree).find((n) => n.el === "Raster") };+ };+ await hooks["tool.call"]!(d.$, { tool: "Read", tool_use_id: "toolu_r", file_path: CONF }, async () => ({ result: {} }));+ expect(engineProblems((await raster()).raster!)).toEqual([]);+ await hooks["tool.call"]!(d.$, { tool: "Edit", tool_use_id: "toolu_e", file_path: CONF, old_string: "a", new_string: "# x\na" }, async () => ({ result: {} }));+ await until(() => d.calls.http.some((u) => u.endsWith("/blast-radius")));+ await wait(20);+ const after = await raster();+ expect(after.raster).toBeDefined();+ expect(engineProblems(after.raster!)).toEqual([]);+ expect(textOf(after.tree).some((t) => /^248 importers: /.test(t))).toBe(true);+ expect(d.calls.logs.filter((l) => /render failed|draw|map key/.test(l))).toEqual([]);+ });+ }+});++/** register() with one module swapped for a version whose `name` throws. */+async function loadThrowing(module: string, name: string): Promise<Hooks> {+ vi.resetModules();+ vi.doMock(module, async (real) => ({+ ...(await real<Record<string, unknown>>()),+ [name]: () => {+ throw new Error("boom");+ },+ }));+ const { register } = await import("../src/register");+ const own: Hooks = {};+ register(((event: string, a: unknown, b?: unknown) => {+ const m = b === undefined ? null : (a as { component?: string; command?: string; element?: string });+ own[m === null ? event : `${event}:${m.component ?? m.command ?? m.element}`] = (b ?? a) as Hook<any>;+ }) as On);+ vi.doUnmock(module);+ return own;+}++const DOCKED = { surface: "terminal", requestId: "lens", props: { bodyColumns: 110, placement: "dock", scroll: { bodyRows: 24 } } };+const FAILED = "Lens could not draw this tab; details in the debug log";++describe("a tab body that throws", () => {+ async function shown(own: Hooks, tab: string) {+ const d = fullDollar();+ await own["session.start"]!(d.$, { cwd: ROOT }, async () => undefined);+ await until(() => d.calls.http.some((u) => u.endsWith("/api/repos")));+ await wait(10);+ await own["command.run:lens"]!(d.$, { command: "lens", args: tab }, async () => ({}));+ await wait(20);+ const tree = (await own["ui.render:Pane"]!(d.$, DOCKED, async () => ({ el: "theirs" }))) as Tree;+ return { d, tree };+ }++ it("Recap: keeps the tab bar, says it could not draw, and logs why", async () => {+ const { d, tree } = await shown(await loadThrowing("../src/views/pane", "recapView"), "recap");+ expect(tree).not.toEqual({ el: "theirs" });+ expect(flatten(tree).some((n) => n.el === "Button")).toBe(true);+ expect(textOf(tree)).toContain(FAILED);+ expect(d.calls.logs.some((l) => /recap tab render failed: Error: boom/.test(l))).toBe(true);+ });++ it("Map: the same, for a map that throws while it draws", async () => {+ const { d, tree } = await shown(await loadThrowing("../src/views/mapPane", "mapPaneView"), "map");+ expect(flatten(tree).some((n) => n.el === "Button")).toBe(true);+ expect(textOf(tree)).toContain(FAILED);+ expect(d.calls.logs.some((l) => /map tab render failed: Error: boom/.test(l))).toBe(true);+ });++ it("a map key that throws is logged and the pane keeps drawing", async () => {+ const own = await loadThrowing("../src/model/inspect", "step");+ const { d, tree } = await shown(own, "map");+ await own["tool.call"]!(d.$, { tool: "Read", tool_use_id: "toolu_r", file_path: CONF }, async () => ({ result: {} }));+ const next = flatten((await own["ui.render:Pane"]!(d.$, DOCKED, async () => ({ el: "theirs" }))) as Tree).find((n) => n.props?.key === "lens-map-next");+ expect(flatten(tree).some((n) => n.el === "Raster")).toBe(true);+ (next!.props.onPress as () => void)();+ expect(d.calls.logs.some((l) => /map key failed: Error: boom/.test(l))).toBe(true);+ const after = (await own["ui.render:Pane"]!(d.$, DOCKED, async () => ({ el: "theirs" }))) as Tree;+ expect(flatten(after).some((n) => n.el === "Raster")).toBe(true);+ });+});diff --git a/packages/claude-mod/test/map-controller.test.ts b/packages/claude-mod/test/map-controller.test.tsnew file mode 100644index 000000000..5d23e54db--- /dev/null+++ b/packages/claude-mod/test/map-controller.test.ts@@ -0,0 +1,104 @@+// The map's keys over a whole LensMap: the cursor walks only what the view+// draws, a new prompt or a /clear starts with nothing selected and no zoom, a+// selection the turn stopped lighting never comes back ringed, and a zoom into+// a folder the feed no longer has falls back to the whole repo.+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { HealthMapFeed } from "@repowise-dev/types/health";+import { LensMap, type MapIO, type PaneInput } from "../src/map-controller";+import { NO_STORY } from "../src/model/story";+import type { Node } from "../src/views/elements";+import { MAP_KEYS } from "../src/views/mapPane";+import { NO_LIT, type Lit } from "../src/views/overlay";+import { feed } from "./django";++const served = vi.hoisted(() => ({ feed: null as unknown }));+vi.mock("@repowise-dev/api-client/code-health", () => ({ getHealthMap: async () => served.feed }));++const io: MapIO = {+ redraw: () => undefined,+ debug: () => undefined,+ blit: async () => ({}),+ openPane: async () => ({ isPlaced: true }),+ closePane: async () => undefined,+};+const PANE: PaneInput = { surface: "terminal", notice: "", theme: "dark", bodyColumns: 180, placement: "dock", bodyRows: 60 };+const REPO = { id: "dj", root: "C:\\work\\django", updatedAt: null, caseInsensitive: true };++const MODELS = ["django/db/models/query.py", "django/db/models/manager.py", "django/db/models/base.py"];+const ELSEWHERE = ["django/conf/__init__.py", "django/http/request.py"];+const turnLit = (reads: string[]): Lit => ({ ...NO_LIT, reads, edits: [MODELS[0]!], edit: MODELS[0]!, current: MODELS[0]! });++const texts = (n: Node): string[] => (n.type === "Text" ? [n.children.join("")] : n.type === "Box" ? n.children.flatMap(texts) : []);+/** The path the detail line names, or null with nothing selected. */+const detailOf = (n: Node): string | null => texts(n).find((t) => /^django\/\S+ · /.test(t))?.split(" · ")[0] ?? null;+const crumbOf = (n: Node): string | null => texts(n).find((t) => / \/ /.test(t) && !t.includes(" · ")) ?? null;++let lit: Lit;+let map: LensMap;+const draw = () => map.paneTree(io, PANE);+const press = (k: keyof typeof MAP_KEYS) => map.press(io, MAP_KEYS[k].key);++beforeEach(async () => {+ served.feed = feed;+ lit = turnLit([...MODELS, ...ELSEWHERE]);+ map = new LensMap(false, undefined, false, () => ({ lit, story: NO_STORY }));+ map.setRepo(io, REPO);+ draw();+ await vi.waitFor(() => expect(texts(draw()).some((t) => t.includes("drawn"))).toBe(true));+});++describe("the map's cursor and zoom", () => {+ it("zoomed in, j walks only the lit files that folder draws", () => {+ press("next");+ expect(detailOf(draw())).toBe(MODELS[0]);+ press("zoom");+ const root = crumbOf(draw())!.split(" / ").join("/");+ expect(MODELS[0]!.startsWith(`${root}/`)).toBe(true);+ const seen = new Set<string>();+ for (let i = 0; i < 8; i++) {+ press("next");+ seen.add(detailOf(draw())!);+ }+ expect([...seen].every((p) => p.startsWith(`${root}/`))).toBe(true);+ expect(seen.size).toBeGreaterThan(1);+ });++ it("a new prompt starts with nothing selected and the whole repo in view", () => {+ press("next");+ press("zoom");+ expect(crumbOf(draw())).not.toBeNull();+ map.turnStarted();+ const tree = draw();+ expect([detailOf(tree), crumbOf(tree)]).toEqual([null, null]);+ });++ it("a /clear drops the selection and the zoom too", () => {+ press("next");+ press("zoom");+ map.clearConversation(io);+ const tree = draw();+ expect([detailOf(tree), crumbOf(tree)]).toEqual([null, null]);+ });++ it("a selection the turn stops lighting is dropped for good: lit again, it is not ringed again", () => {+ press("next");+ press("next");+ const chosen = detailOf(draw())!;+ lit = turnLit([...MODELS, ...ELSEWHERE].filter((p) => p !== chosen));+ expect(detailOf(draw())).toBeNull();+ lit = turnLit([...MODELS, ...ELSEWHERE]);+ expect(detailOf(draw())).toBeNull();+ });++ it("a zoom into a folder the feed no longer has falls back to the whole repo", async () => {+ press("next");+ press("zoom");+ const root = crumbOf(draw())!.split(" / ").join("/");+ // Stands in for a refreshed feed: the same map, without the zoomed folder.+ const without: HealthMapFeed = { ...feed, files: feed.files.filter((f) => !f.file_path.startsWith(`${root}/`)) };+ (map as unknown as { feed: { status: "ready"; data: HealthMapFeed } }).feed = { status: "ready", data: without };+ const tree = draw();+ expect(crumbOf(tree)).toBeNull();+ expect(texts(tree).some((t) => t.includes("drawn"))).toBe(true);+ });+});diff --git a/packages/claude-mod/test/map-register.test.ts b/packages/claude-mod/test/map-register.test.tsindex 85405f322..a45e178f7 100644--- a/packages/claude-mod/test/map-register.test.ts+++ b/packages/claude-mod/test/map-register.test.ts@@ -1,7 +1,7 @@// The map's wiring through register(): /lens, the Pane, the trail from tool// calls, importers and the ripple, auto-open. Answers come from the recorded// Django payloads (test/fixtures).-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { Hook, ModApi, On, PluginOptions } from "../src/mod-api";import { MAP_COPY, PANE_COPY } from "../src/views/copy";import { DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";@@ -70,6 +70,7 @@ function uiFake(calls: Calls): ModApi["ui"] {/** A `$` for a git work tree with no index and a connecting MCP server. */function fakeDollar() {const calls: Calls = { cwd: 0, invalidate: 0, logs: [], open: [], close: [], blit: [], commands: [], http: [] };+ made.push(calls);let release: () => void = () => {};const gate = { hold: false, wait: Promise.resolve() };const $: ModApi = {@@ -157,6 +158,19 @@ const pane = (requestId = "lens", surface = "terminal") => ({const THEIRS = { el: "theirs" };let hooks: Hooks;++/**+ * Every fake `$` this test made, so a draw that failed into the never-blank+ * guard cannot pass unnoticed: only a test about failing may log one.+ */+const made: { logs: string[] }[] = [];+afterEach(() => {+ const name = expect.getState().currentTestName ?? "";+ const failed = made.flatMap((c) => c.logs).filter((l) => /render failed|key failed/.test(l));+ made.length = 0;+ if (!/fail|throw/.test(name)) expect(failed).toEqual([]);+});+beforeEach(async () => {hooks = await load();});@@ -221,6 +235,42 @@ describe("the map pane", () => {expect(shown).toContain("Lens map needs a wider terminal: below 110 columns (90 now)");});+ it("the inspector: j and k walk the lit files with a detail line, z zooms into the selection's folder, u goes up, x clears", async () => {+ const d = await opened();+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));+ await until(() => asked(d, "/blast-radius") === 1);+ await settle();+ const key = async (k: string) => flatten(await render(d)).find((n) => n.props.key === `lens-map-${k}`);+ const hotkeys = async () => flatten(await render(d)).filter((n) => n.el === "Button" && String(n.props.key).startsWith("lens-map-")).map((n) => n.props.hotkey);+ expect(await hotkeys()).toEqual(["j", "k", "h"]);+ (await key("next"))!.props.onPress();+ let shown = textOf(await render(d));+ expect(shown.some((t) => t.startsWith("django/db/models/query.py · Claude edited it"))).toBe(true);+ expect(await hotkeys()).toEqual(["j", "k", "z", "x", "h"]);+ (await key("zoom"))!.props.onPress();+ shown = textOf(await render(d));+ expect(shown[0]).toMatch(/^django \/ db/);+ expect(await hotkeys()).toContain("u");+ // Zoomed in, the selection and its lighting stay.+ expect(shown.some((t) => t.startsWith("django/db/models/query.py · "))).toBe(true);+ for (let i = 0; i < 4 && (await key("up")) !== undefined; i++) (await key("up"))!.props.onPress();+ expect(textOf(await render(d))[0]).not.toMatch(/ \/ /);+ (await key("previous"))!.props.onPress();+ expect(textOf(await render(d)).some((t) => / · imports query\.py$/.test(t))).toBe(true);+ (await key("clear"))!.props.onPress();+ expect(textOf(await render(d)).some((t) => t.includes(" · Claude edited it") || t.includes(" · imports "))).toBe(false);+ });++ it("each tab's keys are its own: the map's letters only on the Map tab, never a digit (digits are the tabs)", async () => {+ const d = await opened();+ const tree = await render(d);+ const hot = flatten(tree).filter((n) => n.el === "Button").map((n) => n.props.hotkey as string);+ expect(new Set(hot).size).toBe(hot.length);+ expect(flatten(tree).filter((n) => n.el === "Button" && String(n.props.key).startsWith("lens-map-")).every((n) => /^[a-z]$/.test(n.props.hotkey))).toBe(true);+ flatten(tree).find((n) => n.props.key === "lens-tab-flow")!.props.onPress();+ expect(flatten(await render(d)).some((n) => n.el === "Button" && String(n.props.key).startsWith("lens-map-"))).toBe(false);+ });+it("the map is quiet ghost tiles until the Health colours button turns the bands on; lens_map_health starts it on", async () => {const d = await opened();const bands = (tree: Tree) => decode(String(flatten(tree).find((n) => n.el === "Raster")!.props.cells)).some((w, i) => i % 3 === 1 && w === parseInt(DARK_CANVAS_BAND.good.slice(1), 16));@@ -241,8 +291,8 @@ describe("the map pane", () => {const tree = await render(d);const r = flatten(tree).find((n) => n.el === "Raster")!;// The pane's 55 rows less the tab row and the rows under the map (story, scope, toggle).- expect(r.props).toMatchObject({ key: "lens-map", columns: 180, rows: 47 });- expect(r.props.cells).toHaveLength(180 * 47 * 16);+ expect(r.props).toMatchObject({ key: "lens-map", columns: 180, rows: 45 });+ expect(r.props.cells).toHaveLength(180 * 45 * 16);expect(textOf(tree).some((t) => /^1,\d{3} of 2,970 files drawn at this size/.test(t))).toBe(true);});@@ -272,7 +322,7 @@ describe("the map pane", () => {await render(d);await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));await until(() => d.calls.blit.length >= 2);- expect(d.calls.blit[0]).toMatchObject({ requestId: "lens", key: "lens-map", columns: 180, rows: 47 });+ expect(d.calls.blit[0]).toMatchObject({ requestId: "lens", key: "lens-map", columns: 180, rows: 45 });const shown = textOf(await render(d));expect(shown.some((t) => t.startsWith("12 importers: "))).toBe(true);expect(shown).toContain("◉ query.py");diff --git a/packages/claude-mod/test/map.test.ts b/packages/claude-mod/test/map.test.tsindex 9a4d6d5b8..c362b34d9 100644--- a/packages/claude-mod/test/map.test.ts+++ b/packages/claude-mod/test/map.test.ts@@ -109,7 +109,7 @@ describe("layoutMap on the Django feed at 180x50", () => {});it("the legend counts exactly the files drawn", () => {- const parts = scopeParts({ drawn: layout.drawn.length, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: "2h ago", beyondCap: 0, dense: layout.dense, notOnMap: 0 });+ const parts = scopeParts({ drawn: layout.drawn.length, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: "2h ago", beyondCap: 0, dense: layout.dense, notOnMap: 0, zoom: null });expect(parts[0]).toBe(`${layout.drawn.length.toLocaleString("en-US")} of 2,970 files drawn at this size`);});});@@ -173,6 +173,12 @@ describe("cell encoding", () => {expect(text(decode(encodeCells(layout, layout.base, marked)))).toBe("▀".repeat(label.text.length));});+ it("drops a name that falls outside the raster instead of writing past its last row", () => {+ const layout = { ...layoutMap(feed.files, { columns: 60, rows: 20, caseInsensitive: true }), labels: [] };+ const outside = [20, -1].map((row) => ({ row, col: 0, text: "query.py", color: 0xffffff }));+ expect(encodeCells(layout, layout.base, undefined, outside)).toBe(encodeCells(layout, layout.base));+ });+it("encodes a 180x50 frame to the documented size", () => {const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });expect(encodeCells(layout, layout.base)).toHaveLength(144_000);diff --git a/packages/claude-mod/test/mapPane.test.ts b/packages/claude-mod/test/mapPane.test.tsindex 56aafb5e9..e301bebe1 100644--- a/packages/claude-mod/test/mapPane.test.ts+++ b/packages/claude-mod/test/mapPane.test.ts@@ -4,7 +4,7 @@ import { NO_STORY, type Reach, type Story } from "../src/model/story";import { HINTS, MAP_COPY, STORY_COPY, freshnessLine, linesPart, notPlacedLine, reachesPart, scopeParts, searchedPart } from "../src/views/copy";import type { Node } from "../src/views/elements";import { MAP_PALETTES, layoutMap } from "../src/views/map";-import { HEALTH_KEY, MAP_KEY, legendRows, mapPaneView, mapSize, noticeView, packRows, storyView, type MapPaneParts } from "../src/views/mapPane";+import { HEALTH_KEY, MAP_KEY, keyRow, legendRows, mapPaneView, mapSize, noticeView, packRows, storyView, type MapPaneParts } from "../src/views/mapPane";import { NO_LIT, frameCells, resolveLit } from "../src/views/overlay";import { feed, importers } from "./django";@@ -27,7 +27,7 @@ function rows(node: Node): string[] {const DARK = { theme: "dark" as const, health: false };const hex = (n: number) => `#${n.toString(16).padStart(6, "0")}`;-const scope = { drawn: 1_639, shown: 2_347, repositoryTotal: 2_970, indexed: "2h ago", beyondCap: 0, dense: false, notOnMap: 0 };+const scope = { drawn: 1_639, shown: 2_347, repositoryTotal: 2_970, indexed: "2h ago", beyondCap: 0, dense: false, notOnMap: 0, zoom: null };/** The recorded Django turn's story: Flow's record of it, as model/story.ts reads it. */const story: Story = {@@ -48,11 +48,11 @@ const reach: Reach = {};describe("mapSize and legendRows", () => {- it("docked: full width, the pane's rows less the story, scope and toggle rows (and the health legend when on)", () => {- expect(legendRows(180)).toBe(4 + 2 + 1);- expect(legendRows(180, true)).toBe(4 + 1 + 2 + 1);- expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 })).toEqual({ columns: 180, rows: 48 });- expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 }, true)).toEqual({ columns: 180, rows: 47 });+ it("docked: full width, the pane's rows less the breadcrumb, story, detail, scope and key rows (and the health legend when on)", () => {+ expect(legendRows(180)).toBe(1 + 4 + 1 + 2 + 1);+ expect(legendRows(180, true)).toBe(1 + 4 + 1 + 1 + 2 + 1);+ expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 })).toEqual({ columns: 180, rows: 46 });+ expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 }, true)).toEqual({ columns: 180, rows: 45 });});it("inline: a squat share of the width, capped; within the Raster's limits", () => {@@ -141,7 +141,8 @@ describe("mapPaneView", () => {const shown = rows(tree);expect(shown.slice(1, 5).map((r) => r.slice(0, 8))).toEqual(["SEARCHED", "OPENED ", "EDITED ", "REACHES "]);expect(shown.at(-2)).toBe("1,639 of 2,970 files drawn at this size · rest too small to draw · indexed 2h ago");- expect(tree.children.at(-1)).toMatchObject({ type: "Button", props: { key: HEALTH_KEY, hotkey: "h", label: MAP_COPY.healthOff } });+ const keyRow = tree.children.at(-1)!;+ expect(keyRow.type === "Box" && keyRow.children.at(-1)).toMatchObject({ type: "Button", props: { key: HEALTH_KEY, hotkey: "h", label: MAP_COPY.healthOff } });expect(JSON.stringify(tree)).not.toContain(DARK_CANVAS_BAND.at_risk);});@@ -168,3 +169,31 @@ describe("mapPaneView", () => {expect(texts(noticeView(MAP_COPY.loading, 20))).toEqual(["Lens map: loading t…"]);});});++describe("the key row", () => {+ const ALL = { items: true, selected: true, zoomable: true, zoomed: true };+ /** Cells the row takes: each plain Button as `h: label`, a `…` as one, two between. */+ const cells = (row: Node): number => {+ const kids = row.type === "Box" ? row.children : [];+ return kids.reduce((n, k) => n + (k.type === "Button" ? String(k.props.label).length + 3 : k.type === "Text" ? k.children.join("").length : 0), 0) + 2 * (kids.length - 1);+ };+ const hotkeys = (row: Node): string[] => (row.type === "Box" ? row.children.flatMap((k) => (k.type === "Button" ? [String(k.props.hotkey)] : k.type === "Text" ? ["…"] : [])) : []);++ for (const columns of [40, 60, 110]) {+ it(`stays on one row at ${columns} columns, dropping the least useful keys behind a …`, () => {+ for (const health of [false, true]) {+ const row = keyRow(ALL, { theme: "dark", health }, columns);+ expect(cells(row)).toBeLessThanOrEqual(columns);+ expect(hotkeys(row)).toContain("h");+ expect(hotkeys(row)).toContain("j");+ }+ });+ }++ it("keeps every key where they fit, and drops clear before next", () => {+ expect(hotkeys(keyRow(ALL, { theme: "dark", health: false }, 110))).toEqual(["j", "k", "z", "u", "x", "h"]);+ const narrow = hotkeys(keyRow(ALL, { theme: "dark", health: false }, 40));+ expect(narrow.at(-1)).toBe("…");+ expect(narrow).not.toContain("x");+ });+});diff --git a/packages/claude-mod/test/mapSvg.test.ts b/packages/claude-mod/test/mapSvg.test.tsindex 119a9800b..c1b2ac0ea 100644--- a/packages/claude-mod/test/mapSvg.test.ts+++ b/packages/claude-mod/test/mapSvg.test.ts@@ -8,7 +8,7 @@ import { SVG_CHARS, desktopSize, mapSvg, svgPaneView } from "../src/views/mapSvgimport { NO_LIT, framePixels, resolveLit, type Lit } from "../src/views/overlay";import { feed, importers } from "./django";-const scope = { drawn: 0, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: null, beyondCap: 0, dense: false, notOnMap: 0 };+const scope = { drawn: 0, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: null, beyondCap: 0, dense: false, notOnMap: 0, zoom: null };const parts = { story: NO_STORY, reach: null, scope };const hex = (n: number) => `#${n.toString(16).padStart(6, "0")}`;@@ -72,3 +72,13 @@ describe("desktop map", () => {expect(over.children[0]).toMatchObject({ type: "Text", children: ["Lens map has too much detail to draw here; the terminal map shows it"] });});});++describe("the inspector on the desktop", () => {+ it("rings the selected tile in the SVG as the terminal does", () => {+ const layout = layoutMap(feed.files, { columns: 160, rows: 45, caseInsensitive: true });+ const lit = { ...NO_LIT, reads: ["django/db/models/query.py"] };+ const ring = `stroke="#${MAP_PALETTES.dark.ring.toString(16).padStart(6, "0")}"`;+ expect(mapSvg(layout, resolveLit(layout, lit))).not.toContain(ring);+ expect(mapSvg(layout, resolveLit(layout, lit, "django/db/models/query.py"))).toContain(ring);+ });+});diff --git a/packages/claude-mod/test/register.test.ts b/packages/claude-mod/test/register.test.tsindex f932d57b8..d835aa305 100644--- a/packages/claude-mod/test/register.test.ts+++ b/packages/claude-mod/test/register.test.ts@@ -1,4 +1,4 @@-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import type { CheckNext, Hook, McpToolResult, ModApi, On, ToolCheckEvent } from "../src/mod-api";import { DARK } from "@repowise-dev/ui/brand";import { TimeoutError } from "../src/data/transport";@@ -117,6 +117,7 @@ function promptFor(calls: Calls): ModApi["prompt"] {/** A `$` for a git work tree: no index by default, an index with `indexed`, a live server with `savings`. */function fakeDollar(o: DollarOptions = {}) {const calls: Calls = { cwd: 0, invalidate: 0, logs: [], mcp: [], savings: 0, submitted: [], transcript: [] };+ made.push(calls);let release: () => void = () => {};const gate = { hold: false, wait: Promise.resolve() };const session: ModApi["session"] = {@@ -140,6 +141,19 @@ const band = { props: { hasSurvey: false, bodyColumns: 100 } };const THEIRS = { el: "theirs" };let hooks: Hooks;++/**+ * Every fake `$` this test made, so a draw that failed into the never-blank+ * guard cannot pass unnoticed: only a test about failing may log one.+ */+const made: { logs: string[] }[] = [];+afterEach(() => {+ const name = expect.getState().currentTestName ?? "";+ const failed = made.flatMap((c) => c.logs).filter((l) => /render failed|key failed/.test(l));+ made.length = 0;+ if (!/fail|throw/.test(name)) expect(failed).toEqual([]);+});+beforeEach(async () => {hooks = await load();});diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.mdindex 35c3bf373..fdabb75ec 100644--- a/plugins/claude-code/README.md+++ b/plugins/claude-code/README.md@@ -142,7 +142,9 @@ which may use the model your repo configures. SeeIt needs Claude Code 2.1.287 or later and an indexed repo. The map and thesavings row also need `repowise serve --no-ui`. Six `userConfig` togglescontrol it: `lens_margin`, `lens_squeeze`, `lens_review` and `lens_flow` (on by-default), and `lens_pane_autoopen` and `lens_map_health` (off). On an older Claude Code, or where mods are switched+default), and `lens_pane_autoopen` and `lens_map_health` (off). In the map,+`j` and `k` walk the files Claude's turn lit, `z` and `u` zoom into and out of a+folder, `x` clears the selection and `h` switches health colours. On an older Claude Code, or where mods are switchedoff, the rest of the plugin works as before.Guide: [docs/agent/LENS.md](../../docs/agent/LENS.md)diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.jsindex 59b83367c..267559619 100644--- a/plugins/claude-code/hooks/lens/lens.js+++ b/plugins/claude-code/hooks/lens/lens.js@@ -1003,7 +1003,8 @@ var MAP_PALETTES = {read: hex(DARK.textSecondary),named: mix(hex(DARK.accentSecondary), hex(DARK.bgRoot), 0.45),importer: hex(DARK.accentSecondary),- edit: hex(BRAND.accent)+ edit: hex(BRAND.accent),+ ring: hex(BRAND.cream)},light: {tileA: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.08),@@ -1013,7 +1014,8 @@ var MAP_PALETTES = {read: hex(LIGHT.textSecondary),named: mix(hex(LIGHT.accentSecondary), hex(LIGHT.bgRoot), 0.55),importer: hex(LIGHT.accentSecondary),- edit: hex(BRAND.accentTextLight)+ edit: hex(BRAND.accentTextLight),+ ring: hex(LIGHT.textPrimary)}};var DEFAULT_STYLE = { theme: "dark", health: false };@@ -1050,14 +1052,14 @@ __name(keyOf, "keyOf");function nextSplit(files, split, limit) {const weight = /* @__PURE__ */ new Map();for (const f of files) {- const key = keyOf(f.file_path, split);- weight.set(key, (weight.get(key) ?? 0) + f.nloc);+ const key2 = keyOf(f.file_path, split);+ weight.set(key2, (weight.get(key2) ?? 0) + f.nloc);}- const heavy = [...weight].filter(([key, w]) => key !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));- for (const [key] of heavy) {- const deeper = /* @__PURE__ */ new Set([...split, key]);- const parts = new Set(files.filter((f) => keyOf(f.file_path, split) === key).map((f) => keyOf(f.file_path, deeper)));- if (parts.size > 1) return key;+ const heavy = [...weight].filter(([key2, w]) => key2 !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));+ for (const [key2] of heavy) {+ const deeper = /* @__PURE__ */ new Set([...split, key2]);+ const parts = new Set(files.filter((f) => keyOf(f.file_path, split) === key2).map((f) => keyOf(f.file_path, deeper)));+ if (parts.size > 1) return key2;}return null;}@@ -1066,16 +1068,16 @@ function groupKeys(files) {const split = /* @__PURE__ */ new Set();const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;for (let i = 0; i < MAX_SPLITS; i++) {- const key = nextSplit(files, split, limit);- if (key === null) break;- split.add(key);+ const key2 = nextSplit(files, split, limit);+ if (key2 === null) break;+ split.add(key2);}return files.map((f) => keyOf(f.file_path, split));}__name(groupKeys, "groupKeys");var folderDatum = /* @__PURE__ */ __name((name) => ({ name, children: [], kids: /* @__PURE__ */ new Map() }), "folderDatum");-function insertFile(group, key, file) {- const rel2 = key === "" ? file.file_path : file.file_path.slice(key.length + 1);+function insertFile(group, key2, file) {+ const rel2 = key2 === "" ? file.file_path : file.file_path.slice(key2.length + 1);let node = group;for (const dir of rel2.split("/").slice(0, -1)) {let next = node.kids?.get(dir);@@ -1093,10 +1095,10 @@ function treemapOf(files, width2, height) {const keys = groupKeys(files);const groups = /* @__PURE__ */ new Map();files.forEach((file, i) => {- const key = keys[i] ?? "";- const group = groups.get(key) ?? folderDatum(key);- groups.set(key, group);- insertFile(group, key, file);+ const key2 = keys[i] ?? "";+ const group = groups.get(key2) ?? folderDatum(key2);+ groups.set(key2, group);+ insertFile(group, key2, file);});const data = { name: "", children: [...groups.values()] };const root = hierarchy(data).sum((d) => d.file?.nloc ?? 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));@@ -1143,6 +1145,11 @@ function paintBox(base, width2, box2, fill) {for (let y = box2.y0; y < box2.y1; y++) base.fill(fill, y * width2 + box2.x0, y * width2 + box2.x1);}__name(paintBox, "paintBox");+function folderPath(group, node) {+ const below2 = node.ancestors().reverse().slice(2).map((n) => n.data.name);+ return [group.data.name, ...below2].filter((part) => part !== "").join("/");+}+__name(folderPath, "folderPath");function folderTiles(group, inner) {const out = [];for (const node of group.descendants()) {@@ -1150,11 +1157,20 @@ function folderTiles(group, inner) {const tone = (node.parent?.children ?? []).indexOf(node) % 2;const [x0, x1] = pixelSpan(node.x0, node.x1);const [y0, y1] = pixelSpan(node.y0, node.y1);- out.push({ x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1), tone });+ const box2 = { x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1) };+ out.push({ path: folderPath(group, node), ...box2, tone });}return out;}__name(folderTiles, "folderTiles");+var within = /* @__PURE__ */ __name((f, x, y) => x >= f.x0 && x < f.x1 && y >= f.y0 && y < f.y1, "within");+function folderAt(layout, x, y) {+ const tile = layout.folders.filter((f) => within(f, x, y)).at(-1);+ if (tile !== void 0) return tile.path;+ const group = layout.groups.find((g) => within({ x0: g.rect.x, y0: g.rect.y, x1: g.rect.x + g.rect.w, y1: g.rect.y + g.rect.h }, x, y));+ return group === void 0 || group.key === "" ? null : group.key;+}+__name(folderAt, "folderAt");function paintFile(base, width2, f, fill) {const edge = mix(fill, BLACK, 0.3);const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;@@ -1165,9 +1181,9 @@ function paintFile(base, width2, f, fill) {}}__name(paintFile, "paintFile");-function labelText(key, width2) {- const parts = key.split("/");- const rungs = [key, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];+function labelText(key2, width2) {+ const parts = key2.split("/");+ const rungs = [key2, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];const text2 = rungs.find((r) => r.length > 0 && r.length <= width2);return text2 !== void 0 && /^[\x20-\x7e]+$/.test(text2) ? text2 : null;}@@ -1175,21 +1191,42 @@ __name(labelText, "labelText");var LABEL_MIN_COLS = 12;var LABEL_MIN_ROWS = 3;var MAX_LABELS = 8;-function labelFor(g, columns, rows) {+function labelFor(g, columns, rows, root) {const col = Math.ceil(g.rect.x);const row2 = Math.ceil(g.rect.y / 2);const width2 = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;const height = Math.floor((g.rect.y + g.rect.h) / 2) - row2;const small = height < LABEL_MIN_ROWS || width2 < LABEL_MIN_COLS;- if (g.key === "" || small || row2 >= rows) return null;- const text2 = labelText(g.key, width2);+ const key2 = root === null ? g.key : g.key.slice(root.length + 1);+ if (key2 === "" || small || row2 >= rows) return null;+ const text2 = labelText(key2, width2);return text2 === null ? null : { row: row2, col, text: text2 };}__name(labelFor, "labelFor");-function labelsFor(groups, columns, rows) {- return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows)).filter((l) => l !== null).slice(0, MAX_LABELS);+function labelsFor(groups, columns, rows, root = null) {+ return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows, root)).filter((l) => l !== null).slice(0, MAX_LABELS);}__name(labelsFor, "labelsFor");+function fileLabel(f, rows) {+ const text2 = cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1));+ const row2 = Math.ceil(f.py0 / 2);+ const roomy = f.px1 - f.px0 >= text2.length + 2 && Math.floor(f.py1 / 2) > row2;+ return roomy && row2 < rows ? { row: row2, col: f.px0 + 1, text: text2 } : null;+}+__name(fileLabel, "fileLabel");+function fileLabels(files, rows, taken) {+ const used = new Set(taken.flatMap((l) => [...l.text].map((_, k) => `${l.row}:${l.col + k}`)));+ const out = [];+ for (const label of files.map((f) => fileLabel(f, rows))) {+ if (label === null) continue;+ const cells = [...label.text].map((_, k) => `${label.row}:${label.col + k}`);+ if (cells.some((c) => used.has(c))) continue;+ cells.forEach((c) => used.add(c));+ out.push(label);+ }+ return out;+}+__name(fileLabels, "fileLabels");function paintBase(map2, style, dense) {const { width: width2, height } = map2;const base = new Uint32Array(width2 * height).fill(GROUND);@@ -1202,16 +1239,18 @@ function paintBase(map2, style, dense) {return base;}__name(paintBase, "paintBase");+function filesUnder(feed, root) {+ const lines = feed.filter((f) => f.nloc > 0);+ return root === null ? lines : lines.filter((f) => f.file_path.startsWith(`${root}/`));+}+__name(filesUnder, "filesUnder");function layoutMap(feed, canvas) {const { columns, rows, caseInsensitive } = canvas;const style = canvas.style ?? DEFAULT_STYLE;const width2 = columns;const height = rows * 2;- const root = treemapOf(- feed.filter((f) => f.nloc > 0),- width2,- height- );+ const zoom = canvas.root ?? null;+ const root = treemapOf(filesUnder(feed, zoom), width2, height);const groups = [];const files = [];const folders = [];@@ -1231,7 +1270,9 @@ function layoutMap(feed, canvas) {});const dense = drawn.length < files.length * DENSE_SHARE;const base = paintBase({ width: width2, height, groups, folders, files, drawn }, style, dense);- return { columns, rows, width: width2, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base, style, dense, lower, folders };+ const folderNames = labelsFor(groups, columns, rows, zoom);+ const labels = zoom === null || dense ? folderNames : [...folderNames, ...fileLabels(files, rows, folderNames)];+ return { columns, rows, width: width2, height, groups, files, drawn, index, caseInsensitive, labels, base, style, dense, lower, folders, root: zoom };}__name(layoutMap, "layoutMap");function halfCell(top, bottom) {@@ -1250,7 +1291,8 @@ function labelCovered(label, marked, width2) {__name(labelCovered, "labelCovered");var cellGround = /* @__PURE__ */ __name((pixel) => pixel === void 0 || pixel === GROUND ? TERMINAL_DEFAULT : pixel, "cellGround");function writeText(words, layout, label, colors) {- for (let k = 0; k < label.text.length && label.col + k < layout.columns; k++) {+ if (label.row < 0 || label.row >= layout.rows) return;+ for (let k = Math.max(0, -label.col); k < label.text.length && label.col + k < layout.columns; k++) {const col = label.col + k;words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);}@@ -1337,7 +1379,7 @@ function namesFor(layout, o) {return order.map((i) => placeName(layout, taken, layout.files[i], hot.has(i) ? pal.edit : TERMINAL_DEFAULT)).filter((n) => n !== null);}__name(namesFor, "namesFor");-function resolveLit(layout, lit) {+function resolveLit(layout, lit, selected = null) {const o = {hits: indices(layout, lit.hits),reads: indices(layout, lit.reads),@@ -1347,7 +1389,7 @@ function resolveLit(layout, lit) {edit: one(layout, lit.edit),current: one(layout, lit.current)};- return { ...o, names: namesFor(layout, o) };+ return { ...o, names: namesFor(layout, o), selected: one(layout, selected) };}__name(resolveLit, "resolveLit");function center(layout, f) {@@ -1405,6 +1447,24 @@ function rippleReach(layout, overlay, anim) {return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;}__name(rippleReach, "rippleReach");+var inRange = /* @__PURE__ */ __name((v, n) => v >= 0 && v < n, "inRange");+function set(p, x, y, color2) {+ if (!inRange(x, p.layout.width) || !inRange(y, p.layout.height)) return;+ p.px[y * p.layout.width + x] = color2;+ p.marked[y * p.layout.width + x] = 1;+}+__name(set, "set");+function around(box2) {+ const out = [];+ for (let x = box2.x0 - 1; x <= box2.x1; x++) out.push([x, box2.y0 - 1], [x, box2.y1]);+ for (let y = box2.y0; y < box2.y1; y++) out.push([box2.x0 - 1, y], [box2.x1, y]);+ return out;+}+__name(around, "around");+function paintSelection(p, f, color2) {+ for (const [x, y] of around(litPixels(p.layout, f))) set(p, x, y, color2);+}+__name(paintSelection, "paintSelection");function framePixels(layout, overlay, anim) {const p = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };const pal = MAP_PALETTES[layout.style.theme];@@ -1416,6 +1476,8 @@ function framePixels(layout, overlay, anim) {fillAll(p, [overlay.edit, overlay.current].filter((i) => i !== null), pal.edit);const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];if (origin !== void 0 && reach < Infinity) paintRing(p, origin, reach, pal.importer);+ const selected = overlay.selected === null ? void 0 : layout.files[overlay.selected];+ if (selected !== void 0) paintSelection(p, selected, pal.ring);return { pixels: p.px, marked: p.marked };}__name(framePixels, "framePixels");@@ -1479,12 +1541,12 @@ var Animator = class {this.io?.debug(`animation failed: ${String(err)}`);}frame(screen) {- const step = this.progress(Date.now());- const frame = step === void 0 ? null : screen(step);+ const step2 = this.progress(Date.now());+ const frame = step2 === void 0 ? null : screen(step2);const io = this.io;- if (step === void 0 || frame === null || io === null) return this.stop();+ if (step2 === void 0 || frame === null || io === null) return this.stop();if (this.blitting) return;- if (step.t >= 1) this.stop();+ if (step2.t >= 1) this.stop();this.blitting = true;io.blit(frame.key, frame.cells, frame.columns, frame.rows).then((r) => r.deny === void 0 || this.refused(io, r.deny)).catch((err) => this.refused(io, String(err))).finally(() => {this.blitting = false;@@ -1520,7 +1582,7 @@ function sumOver(targets, read) {}__name(sumOver, "sumOver");var targetsOf = /* @__PURE__ */ __name((r) => Object.values(rec(r["targets"])).filter(isRec), "targetsOf");-var flagged = /* @__PURE__ */ __name((targets, key) => targets.some((t) => key in t) ? targets.filter((t) => t[key] === true).length : null, "flagged");+var flagged = /* @__PURE__ */ __name((targets, key2) => targets.some((t) => key2 in t) ? targets.filter((t) => t[key2] === true).length : null, "flagged");function contextFacts(r) {const targets = targetsOf(r);const docs = targets.map((t) => rec(t["docs"]));@@ -1581,7 +1643,7 @@ function symbolFacts(r) {}__name(symbolFacts, "symbolFacts");function listFacts(r) {- return Object.entries(r).filter(([key, v]) => Array.isArray(v) && v.length > 0 && !key.startsWith("_")).slice(0, 3).map(([key, v]) => ({ what: key, n: v.length }));+ return Object.entries(r).filter(([key2, v]) => Array.isArray(v) && v.length > 0 && !key2.startsWith("_")).slice(0, 3).map(([key2, v]) => ({ what: key2, n: v.length }));}__name(listFacts, "listFacts");var READERS = {@@ -1629,9 +1691,9 @@ var PATH_READERS = {function walkPaths(v, depth, add) {if (depth > MAX_DEPTH) return;if (Array.isArray(v)) return v.forEach((item) => walkPaths(item, depth + 1, add));- for (const [key, value] of Object.entries(rec(v))) {- if (key === "_meta") continue;- PATH_READERS[key]?.(value, add);+ for (const [key2, value] of Object.entries(rec(v))) {+ if (key2 === "_meta") continue;+ PATH_READERS[key2]?.(value, add);walkPaths(value, depth + 1, add);}}@@ -1747,8 +1809,8 @@ function shortPath(path, root) {return inside2 ? slashed.slice(base.length + 1) : slashed;}__name(shortPath, "shortPath");-function argValue(key, v, root) {- if (typeof v === "string") return (PATH_ARGS.has(key) ? shortPath(v, root) : v.replace(/\s+/g, " ")).slice(0, ARG_CHARS);+function argValue(key2, v, root) {+ if (typeof v === "string") return (PATH_ARGS.has(key2) ? shortPath(v, root) : v.replace(/\s+/g, " ")).slice(0, ARG_CHARS);if (Array.isArray(v)) return v.map((x) => typeof x === "string" ? x : JSON.stringify(x)).join(", ").slice(0, ARG_CHARS);if (v === void 0 || v === null) return null;return JSON.stringify(v).slice(0, ARG_CHARS);@@ -1756,9 +1818,9 @@ function argValue(key, v, root) {__name(argValue, "argValue");function compactArgs(e, root) {const out = [];- for (const key of ARG_KEYS) {- const value = argValue(key, e[key], root);- if (value !== null && out.length < MAX_ARGS) out.push([key, value]);+ for (const key2 of ARG_KEYS) {+ const value = argValue(key2, e[key2], root);+ if (value !== null && out.length < MAX_ARGS) out.push([key2, value]);}return out;}@@ -1857,10 +1919,10 @@ function withNamed(named2, paths, naming) {let out = named2;let size = Object.keys(named2).length;for (const p of paths) {- const key = pathKey(p);- if (out[key] !== void 0 || size >= MAX_NAMED) continue;+ const key2 = pathKey(p);+ if (out[key2] !== void 0 || size >= MAX_NAMED) continue;if (out === named2) out = { ...named2 };- out[key] = naming;+ out[key2] = naming;size++;}return out;@@ -2029,10 +2091,10 @@ function testsOf(file) {}__name(testsOf, "testsOf");function blastFacts(path, r) {- const key = pathKey(path);- const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key);- const cochange = (r.cochange_warnings ?? []).filter((w) => pathKey(w.changed) === key).map((w) => ({ path: w.missing_partner, score: w.score })).sort((a, b) => b.score - a.score);- const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key));+ const key2 = pathKey(path);+ const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key2);+ const cochange = (r.cochange_warnings ?? []).filter((w) => pathKey(w.changed) === key2).map((w) => ({ path: w.missing_partner, score: w.score })).sort((a, b) => b.score - a.score);+ const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key2));return { importers, cochange, tests };}__name(blastFacts, "blastFacts");@@ -2087,8 +2149,8 @@ function beforeAccept(state2, turn) {return editedFiles(turn).map((path) => [path, state2.blast[pathKey(path)]]).filter((pair) => pair[1] !== void 0).map(([path, facts]) => gapsOf(state2, path, facts, opened)).filter(hasGap);}__name(beforeAccept, "beforeAccept");-function searchedBefore(state2, key, at) {- return allActivities(state2).some((a) => a.kind === "search" && a.startedAt < at && a.hitPaths.some((p) => pathKey(p) === key));+function searchedBefore(state2, key2, at) {+ return allActivities(state2).some((a) => a.kind === "search" && a.startedAt < at && a.hitPaths.some((p) => pathKey(p) === key2));}__name(searchedBefore, "searchedBefore");function viaOf(state2, first) {@@ -2100,11 +2162,11 @@ function workingSet(state2, turn) {const first = /* @__PURE__ */ new Map();const edited = /* @__PURE__ */ new Set();for (const a of turn.activities.filter((x) => isFile(x) && !x.isError && x.paths[0] !== void 0)) {- const key = pathKey(a.paths[0]);- if (!first.has(key)) first.set(key, a);- if (a.kind === "edit") edited.add(key);+ const key2 = pathKey(a.paths[0]);+ if (!first.has(key2)) first.set(key2, a);+ if (a.kind === "edit") edited.add(key2);}- const rows = [...first].map(([key, a]) => ({ path: a.paths[0], kind: edited.has(key) ? "edited" : "read", via: viaOf(state2, a) }));+ const rows = [...first].map(([key2, a]) => ({ path: a.paths[0], kind: edited.has(key2) ? "edited" : "read", via: viaOf(state2, a) }));return [...rows.filter((r) => r.kind === "edited"), ...rows.filter((r) => r.kind === "read")];}__name(workingSet, "workingSet");@@ -2134,8 +2196,8 @@ __name(firstEditMs, "firstEditMs");function firstEdits(state2) {const out = /* @__PURE__ */ new Map();for (const a of allActivities(state2)) {- const key = a.kind === "edit" && a.paths[0] !== void 0 ? pathKey(a.paths[0]) : null;- if (key !== null && !out.has(key)) out.set(key, a.startedAt);+ const key2 = a.kind === "edit" && a.paths[0] !== void 0 ? pathKey(a.paths[0]) : null;+ if (key2 !== null && !out.has(key2)) out.set(key2, a.startedAt);}return out;}@@ -2338,7 +2400,7 @@ __name(drawnPart, "drawnPart");function scopeParts(s) {const parts = drawnPart(s);if (s.indexed !== null) parts.push(indexedPart(s.indexed));- if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} not on the map`);+ if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} ${s.zoom === null ? "not on the map" : "outside this folder"}`);return parts;}__name(scopeParts, "scopeParts");@@ -2369,6 +2431,36 @@ function reachesPending(edit) {}__name(reachesPending, "reachesPending");var REACHES_FAILED = "import graph unavailable";+var MAP_KEYS_COPY = {+ next: "next",+ previous: "previous",+ zoom: "zoom in",+ up: "up",+ clear: "clear"+};+function crumbLine(root) {+ return root.split("/").join(" / ");+}+__name(crumbLine, "crumbLine");+function whyParts(why) {+ const parts = [];+ if (why.edited !== null) parts.push(`Claude edited it${why.edited.lines === null ? "" : `,${linesPart(why.edited.lines)}`}`);+ if (why.opened) parts.push("Claude opened it");+ if (why.imports !== null) parts.push(`imports ${why.imports}`);+ if (why.namedBy !== null) parts.push(`named by ${why.namedBy}`);+ return parts;+}+__name(whyParts, "whyParts");+function detailLine(path, why, knows) {+ const facts = knows.context === null ? [] : knowsParts(knows.context);+ const tests = knows.tests === null ? [] : [testsReach(knows.tests)];+ return [path, ...whyParts(why), ...facts, ...tests].join(" · ");+}+__name(detailLine, "detailLine");+function testsReach(t) {+ return `${countOf(t.total, "test reaches it", "tests reach it")} (${t.basis})`;+}+__name(testsReach, "testsReach");var PANE_COPY = {command: "Open Lens: Claude's steps with Repowise, the map of its turn, ask the index, and the session recap",argumentHint: "[flow | map | ask <question> | recap]",@@ -2380,7 +2472,8 @@ var PANE_COPY = {askBusy: "still answering the last question; ask again when it lands",noEvidence: "no evidence cited",fromIndex: "Built from the index",- fromModel: "Written by this repo's configured model, from the index"+ fromModel: "Written by this repo's configured model, from the index",+ bodyFailed: "Lens could not draw this tab; details in the debug log"};var ASK_CHARS = 4e3;function askingLine(tool) {@@ -2640,8 +2733,8 @@ function box(props, children) {return { type: "Box", props, children };}__name(box, "box");-function button(key, hotkey, label, dimColor = false) {- return { type: "Button", props: { key, label, hotkey, plain: true, ...dimColor ? { dimColor } : {} } };+function button(key2, hotkey, label, dimColor = false) {+ return { type: "Button", props: { key: key2, label, hotkey, plain: true, ...dimColor ? { dimColor } : {} } };}__name(button, "button");function raster(props) {@@ -2661,9 +2754,9 @@ function svg(source, alt) {}__name(svg, "svg");var SUBMIT_IN_HOOK = /* @__PURE__ */ __name(() => void 0, "SUBMIT_IN_HOOK");-function pressFor(key, presses) {- const onPress = presses[key];- if (!onPress) throw new Error(`button ${key} has no action`);+function pressFor(key2, presses) {+ const onPress = presses[key2];+ if (!onPress) throw new Error(`button ${key2} has no action`);return onPress;}__name(pressFor, "pressFor");@@ -2686,14 +2779,24 @@ __name(materialize, "materialize");// src/views/mapPane.tsvar MAP_KEY = "lens-map";var HEALTH_KEY = "lens-map-health";+var MAP_KEYS = {+ next: { key: "lens-map-next", hotkey: "j" },+ previous: { key: "lens-map-previous", hotkey: "k" },+ zoom: { key: "lens-map-zoom", hotkey: "z" },+ up: { key: "lens-map-up", hotkey: "u" },+ clear: { key: "lens-map-clear", hotkey: "x" }+};+var MAP_PRESSES = [...Object.values(MAP_KEYS).map((k) => k.key), HEALTH_KEY];var MAX_COLUMNS = 512;var MAX_ROWS = 256;var MIN_ROWS = 4;var GAP = 2;var SEP = " · ";+var CRUMB_ROWS = 1;var STORY_ROWS = 4;+var DETAIL_ROWS = 1;var SCOPE_ROWS = 2;-var TOGGLE_ROWS = 1;+var KEY_ROWS = 1;var HEAD = 10;var REACH_NAMES = 3;var INLINE_ROWS_PER_COLUMN = 1 / 6;@@ -2723,7 +2826,7 @@ __name(packRows, "packRows");var swatchWidth = /* @__PURE__ */ __name((s) => s.label.length + 2, "swatchWidth");function legendRows(columns, health2 = false) {const bands = health2 ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;- return STORY_ROWS + bands + SCOPE_ROWS + TOGGLE_ROWS;+ return CRUMB_ROWS + STORY_ROWS + DETAIL_ROWS + bands + SCOPE_ROWS + KEY_ROWS;}__name(legendRows, "legendRows");function mapSize(pane, health2 = false) {@@ -2797,19 +2900,49 @@ function storyView(story, reach, style, columns) {return rows.filter(([, segs]) => segs.length > 0).map(([head, segs]) => storyRow(head, segs, columns));}__name(storyView, "storyView");+var NO_KEYS = { items: false, selected: false, zoomable: false, zoomed: false };+var KEY_PRIORITY = ["health", "next", "zoom", "previous", "up", "clear"];+var keyCells = /* @__PURE__ */ __name((label) => label.length + 3, "keyCells");+var MORE = "…";+function keyRow(keys, style, columns) {+ const on = [+ ["next", keys.items],+ ["previous", keys.items],+ ["zoom", keys.zoomable],+ ["up", keys.zoomed],+ ["clear", keys.selected]+ ];+ const all = [...on.filter(([, shown2]) => shown2).map(([name]) => ({ name, label: MAP_KEYS_COPY[name] })), { name: "health", label: style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff }];+ const ranked = [...all].sort((a, b) => KEY_PRIORITY.indexOf(a.name) - KEY_PRIORITY.indexOf(b.name));+ const cells = /* @__PURE__ */ __name((n) => ranked.slice(0, n).reduce((w, k) => w + keyCells(k.label) + GAP, 0) + (n < all.length ? MORE.length : -GAP), "cells");+ let kept = all.length;+ while (kept > 0 && cells(kept) > columns) kept--;+ const shown = new Set(ranked.slice(0, kept).map((k) => k.name));+ const nodes = all.filter((k) => shown.has(k.name)).map((k) => k.name === "health" ? button(HEALTH_KEY, "h", k.label, true) : button(MAP_KEYS[k.name].key, MAP_KEYS[k.name].hotkey, k.label, true));+ return box({ flexDirection: "row", columnGap: GAP }, kept < all.length ? [...nodes, text(MORE, { dimColor: true })] : nodes);+}+__name(keyRow, "keyRow");+var dimLine = /* @__PURE__ */ __name((line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" }), "dimLine");function legendView(parts, style, columns) {const story = storyView(parts.story, parts.reach, style, columns);- const quiet = story.length === 0 ? [text(fit(MAP_COPY.quiet, columns), { dimColor: true, wrap: "truncate-end" })] : story;+ const quiet = story.length === 0 ? [dimLine(MAP_COPY.quiet, columns)] : story;+ const detail = parts.detail ?? null;return [...quiet,+ ...detail === null ? [] : [text(fit(detail, columns), { wrap: "truncate-end" })],...style.health ? swatchRows(BAND_SWATCHES, columns) : [],- ...scopeRows(parts.scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),- button(HEALTH_KEY, "h", style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff, true)+ ...scopeRows(parts.scope, columns).map((f) => dimLine(f, columns)),+ keyRow(parts.keys ?? NO_KEYS, style, columns)];}__name(legendView, "legendView");+function crumbs(layout) {+ return layout.root === null ? [] : [dimLine(crumbLine(layout.root), layout.columns)];+}+__name(crumbs, "crumbs");function mapPaneView(layout, cells, parts) {return box({ key: "lens-map-pane", flexDirection: "column" }, [+ ...crumbs(layout),raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),...legendView(parts, layout.style, layout.columns)]);@@ -2914,7 +3047,7 @@ function row(segs, columns, right = []) {return box({ flexDirection: "row" }, all.filter((s) => s.t !== "").map(segNode));}__name(row, "row");-var dimLine = /* @__PURE__ */ __name((t, columns) => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" }), "dimLine");+var dimLine2 = /* @__PURE__ */ __name((t, columns) => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" }), "dimLine");var pad = /* @__PURE__ */ __name((n) => ({ t: " ".repeat(n) }), "pad");function wrapWords(words, columns) {return packRows(words.split(" "), (w) => w.length, Math.max(1, columns), 1).map((r) => r.join(" "));@@ -2950,7 +3083,7 @@ function header(state2, v, theme2) {const face = box({ flexDirection: "row" }, owl(st, owlEyes(st, v.now, v.still), theme2.amber));const room = v.columns - OWL_WIDTH - 1;const said = notice(v.mode);- const tail = said === null ? [] : [dimLine(said, v.columns)];+ const tail = said === null ? [] : [dimLine2(said, v.columns)];if (turn === void 0) {const [first = "", ...rest] = wrapWords(FLOW_COPY.empty, Math.min(EMPTY_W, room));return [box({ flexDirection: "row", columnGap: 1 }, [face, text(first)]), ...rest.map((l) => text(`${" ".repeat(OWL_WIDTH + 1)}${l}`)), ...tail];@@ -2959,7 +3092,7 @@ function header(state2, v, theme2) {return [box({ flexDirection: "row", columnGap: 1 }, [face, row(statusSegs(turn, v.now, theme2), room)]),text(fit(answerLine(turnTotals(turn)), v.columns), { wrap: "truncate-end" }),- ...prompt === "" ? [] : [dimLine(`"${prompt}"`, v.columns)],+ ...prompt === "" ? [] : [dimLine2(`"${prompt}"`, v.columns)],...tail];}@@ -2983,7 +3116,7 @@ __name(healthLines, "healthLines");function beforeAcceptLines(state2, turn, v) {const files = beforeAccept(state2, turn).flatMap((g) => [row([pad(2), { t: g.path, flex: true }, { t: ` ${FLOW_COPY.asOfIndex}`, dim: true }], v.columns),- ...gapLines(g).map((l) => dimLine(` ${l}`, v.columns))+ ...gapLines(g).map((l) => dimLine2(` ${l}`, v.columns))]);const health2 = healthLines(v.review).map((l) => text(fit(` ${l}`, v.columns)));return section(FLOW_COPY.beforeAccept, [...files, ...health2]);@@ -3011,7 +3144,7 @@ function workingLines(state2, turn, v, theme2) {theme: theme2};const rows = files.slice(0, WORKING_ROWS).map((f) => workingRow(f, t));- const more = files.length > WORKING_ROWS ? [dimLine(` ${moreFiles(files.length - WORKING_ROWS)}`, v.columns)] : [];+ const more = files.length > WORKING_ROWS ? [dimLine2(` ${moreFiles(files.length - WORKING_ROWS)}`, v.columns)] : [];return section(`${FLOW_COPY.workingSet} · ${FLOW_COPY.asOfIndex}`, [...rows, ...more]);}__name(workingLines, "workingLines");@@ -3034,7 +3167,7 @@ function contextLines(turn, columns, theme2) {const legend = cells.map(([k]) => `${SHADE[k]} ${contextPart(k, bytes[k])}`);const first = firstEditMs(turn);const parts = first === null ? legend : [...legend, firstEditText(first)];- const lines = packRows(parts, (p) => p.length, Math.max(10, columns - 2), 2).map((r) => dimLine(` ${r.join(" ")}`, columns));+ const lines = packRows(parts, (p) => p.length, Math.max(10, columns - 2), 2).map((r) => dimLine2(` ${r.join(" ")}`, columns));return section(FLOW_COPY.context, [bar, ...lines]);}__name(contextLines, "contextLines");@@ -3112,7 +3245,7 @@ function callLines(state2, turn, v, theme2) {opened: openedAfter(state2)};const calls = turn.activities.filter(isCall).flatMap((a) => [callLine(a, ctx), ...detailLines(a, ctx)]);- const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine(` ${droppedSteps(turn.dropped)}`, v.columns) }] : [];+ const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine2(` ${droppedSteps(turn.dropped)}`, v.columns) }] : [];return [...dropped, ...calls];}__name(callLines, "callLines");@@ -3138,13 +3271,13 @@ function windowed(lines, room, open) {const shown = new Set(lines.slice(start, end).map((l) => l.id));const above = stepsOutside(lines.slice(0, start), shown);const below2 = stepsOutside(lines.slice(end), shown);- const note = /* @__PURE__ */ __name((n, say) => n === 0 ? [] : [{ node: dimLine(say(n), Number.POSITIVE_INFINITY) }], "note");+ const note = /* @__PURE__ */ __name((n, say) => n === 0 ? [] : [{ node: dimLine2(say(n), Number.POSITIVE_INFINITY) }], "note");return [...note(above, hiddenSteps), ...lines.slice(start, end), ...note(below2, laterSteps)];}__name(windowed, "windowed");function earlierTurns(state2, columns) {- const out = state2.turns.slice(0, -1).reverse().map((t) => dimLine(` ${turnFooter(t.seq, t.durationMs, turnTotals(t), t.end)}`, columns));- if (state2.earlier.turns > 0) out.push(dimLine(` ${earlierLine(state2.earlier)}`, columns));+ const out = state2.turns.slice(0, -1).reverse().map((t) => dimLine2(` ${turnFooter(t.seq, t.durationMs, turnTotals(t), t.end)}`, columns));+ if (state2.earlier.turns > 0) out.push(dimLine2(` ${earlierLine(state2.earlier)}`, columns));return out;}__name(earlierTurns, "earlierTurns");@@ -3233,9 +3366,9 @@ var LensFlow = class {this.pending = setTimeout(() => this.timer(() => (this.pending = void 0, true)), wait);}/** A timer's body: its step says whether to redraw; a failure is logged, never thrown into the runtime. */- timer(step) {+ timer(step2) {try {- if (step()) this.draw();+ if (step2()) this.draw();} catch (err) {this.io?.debug(`flow timer failed: ${String(err)}`);}@@ -3430,7 +3563,7 @@ function litFromFlow(state2) {return {hits: mine.filter((v) => v.kind === "search-hit").map((v) => v.path),reads: [...new Set(opened.map((v) => v.path))],- named: Object.entries(state2.named).filter(([, n]) => n.turn === turn.seq).map(([key]) => key),+ named: Object.entries(state2.named).filter(([, n]) => n.turn === turn.seq).map(([key2]) => key2),importers: [],edits: [...new Set(edits.map((v) => v.path))],edit: edits.at(-1)?.path ?? null,@@ -3471,6 +3604,58 @@ function withImporters(lit, importersOf) {}__name(withImporters, "withImporters");+// src/model/inspect.ts+var KNOWS_NOTHING = { context: null, tests: null, namedBy: null };+var key = /* @__PURE__ */ __name((p) => p.toLowerCase(), "key");+function litPaths(lit) {+ const edits = [...lit.edits].reverse();+ const order = [...edits, ...lit.reads, ...lit.importers, ...lit.named];+ const seen = /* @__PURE__ */ new Set();+ return order.filter((p) => {+ if (seen.has(key(p))) return false;+ seen.add(key(p));+ return true;+ });+}+__name(litPaths, "litPaths");+function step(paths, current, by) {+ if (paths.length === 0) return null;+ const at = current === null ? -1 : paths.findIndex((p) => key(p) === key(current));+ if (at === -1) return (by === 1 ? paths[0] : paths.at(-1)) ?? null;+ return paths[(at + by + paths.length) % paths.length] ?? null;+}+__name(step, "step");+var nameOf2 = /* @__PURE__ */ __name((p) => p.slice(p.lastIndexOf("/") + 1), "nameOf");+var has = /* @__PURE__ */ __name((paths, p) => paths.some((x) => key(x) === key(p)), "has");+function whyLit(path, lit, story, knows) {+ const edit = has(lit.edits, path) ? story.edited.find((e) => e.name === nameOf2(path)) ?? { lines: null } : null;+ return {+ edited: edit === null ? null : { lines: edit.lines },+ opened: edit === null && has(lit.reads, path),+ imports: has(lit.importers, path) && lit.edit !== null ? nameOf2(lit.edit) : null,+ namedBy: knows.namedBy+ };+}+__name(whyLit, "whyLit");+function contextOf(contexts, path) {+ const exact = contexts[path];+ if (exact !== void 0) return exact;+ const lower = key(path);+ const found = Object.keys(contexts).find((k) => key(k) === lower);+ return found === void 0 ? null : contexts[found] ?? null;+}+__name(contextOf, "contextOf");+function knowsOf(path, contexts, flow2) {+ const facts = flow2 === null ? void 0 : flow2.blast[pathKey(path)];+ const tests = facts?.tests ?? null;+ return {+ context: contextOf(contexts, path),+ tests: tests === null ? null : { total: tests.total, basis: tests.basis },+ namedBy: flow2 === null ? null : flow2.named[pathKey(path)]?.tool ?? null+ };+}+__name(knowsOf, "knowsOf");+// ../api-client/src/blast-radius.tsasync function analyzeBlastRadius(repoId, body) {return apiPost(@@ -3581,19 +3766,34 @@ var CALLERS_TIMEOUT_MS = 2e4;var CALLERS_DEPTH = 1;var NO_TURN = /* @__PURE__ */ __name(() => ({ lit: NO_LIT, story: NO_STORY }), "NO_TURN");function scopeFacts(layout, data, repo, offMap) {+ const whole = layout.root === null;return {drawn: layout.drawn.length,- shown: data.files.length,- repositoryTotal: data.repository_total,+ shown: whole ? data.files.length : layout.files.length,+ repositoryTotal: whole ? data.repository_total : layout.files.length,indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,- beyondCap: data.omitted.files,+ beyondCap: whole ? data.omitted.files : 0,dense: layout.dense,- notOnMap: offMap+ notOnMap: offMap,+ zoom: layout.root};}__name(scopeFacts, "scopeFacts");-var keyParts = /* @__PURE__ */ __name((k) => [k.data, k.columns, k.rows, k.style.theme, k.style.health], "keyParts");-var sameKey = /* @__PURE__ */ __name((a, b) => keyParts(a).every((v, i) => v === keyParts(b)[i]), "sameKey");+var cacheKey = /* @__PURE__ */ __name((k) => `${k.root ?? ""}|${k.columns}|${k.rows}|${k.style.theme}|${k.style.health}`, "cacheKey");+var LAYOUT_CACHE = 6;+function parentOf(root) {+ const at = root === null ? -1 : root.lastIndexOf("/");+ return at === -1 ? null : root.slice(0, at);+}+__name(parentOf, "parentOf");+function folderOf(layout, path) {+ const at = layout.index.get(layout.caseInsensitive ? path.toLowerCase() : path);+ if (at === void 0) return null;+ const b = litPixels(layout, layout.files[at]);+ const folder = folderAt(layout, Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2));+ return folder === layout.root ? null : folder;+}+__name(folderOf, "folderOf");var LensMap = class {static {__name(this, "LensMap");@@ -3616,7 +3816,12 @@ var LensMap = class {edited = /* @__PURE__ */ new Set();importers = /* @__PURE__ */ new Map();drawn = null;+ /** What the last render drew, for the keys: its layout and the lit files on it, in cursor order. */+ view = null;layoutCache = null;+ /** The inspector's selection (a repo-relative path) and the folder zoomed into. */+ selected = null;+ zoom = null;reducedMotion = false;/** Health colours on the tiles: off by default (`lens_map_health`), toggled from the pane. */health;@@ -3638,14 +3843,67 @@ var LensMap = class {keyOf(rel2) {return this.repo?.caseInsensitive === false ? rel2 : rel2.toLowerCase();}- /** The pane's toggle: health colours on the tiles, or the quiet ghost map. */- toggleHealth(io) {- this.health = !this.health;+ /** A press of one of the map's keys (MAP_PRESSES): moves the cursor, zooms, or toggles health colours; one redraw. */+ press(io, key2) {+ const act = this.actions()[key2];+ if (act === void 0) return;+ act();io.redraw();}+ actions() {+ return {+ [MAP_KEYS.next.key]: () => this.move(1),+ [MAP_KEYS.previous.key]: () => this.move(-1),+ [MAP_KEYS.clear.key]: () => this.selected = null,+ [MAP_KEYS.zoom.key]: () => this.zoom = this.zoomTarget() ?? this.zoom,+ [MAP_KEYS.up.key]: () => this.zoom = parentOf(this.zoom),+ [HEALTH_KEY]: () => this.health = !this.health+ };+ }+ /** The cursor walks the lit files the last render drew, so a zoomed view walks only its own folder's. */+ move(by) {+ this.selected = step(this.view?.paths ?? [], this.selected, by);+ }+ /** Where the zoom key goes: the folder holding the selection, when one is drawn deeper than the current view. */+ zoomTarget() {+ const layout = this.view?.layout ?? null;+ return layout === null || this.selected === null ? null : folderOf(layout, this.selected);+ }+ /** A new prompt starts with nothing selected and the whole repo in view. */+ turnStarted() {+ this.selected = null;+ this.zoom = null;+ }+ /**+ * The lit files on this layout in cursor order, and the selection among them.+ * A selection the turn stops lighting (or this view no longer draws) is dropped+ * for good, so it never comes back ringed when the file is lit again.+ */+ see(layout, lit) {+ const paths = litPaths(lit).filter((p) => layout.index.has(layout.caseInsensitive ? p.toLowerCase() : p));+ const s = this.selected;+ if (s !== null && !paths.some((p) => p.toLowerCase() === s.toLowerCase())) this.selected = null;+ this.view = { layout, paths };+ return paths;+ }+ /** The detail line, the keys that would act, and the rest of the pane's parts. */+ parts(layout, lighting, scope, paths) {+ const turn = lighting.turn;+ const selected = this.selected;+ const knows = selected === null ? KNOWS_NOTHING : turn.knows?.(selected) ?? KNOWS_NOTHING;+ const detail = selected === null ? null : detailLine(selected, whyLit(selected, lighting.lit, turn.story, knows), knows);+ const keys = {+ items: paths.length > 0,+ selected: selected !== null,+ zoomable: selected !== null && folderOf(layout, selected) !== null,+ zoomed: layout.root !== null+ };+ return { story: turn.story, reach: lighting.reach, scope, detail, keys };+ }/** What the turn lit, with the latest edit's importers joined as they stand now. */lighting() {- return withImporters(this.turn().lit, (p) => this.importersOf(p));+ const turn = this.turn();+ return { ...withImporters(turn.lit, (p) => this.importersOf(p)), turn };}/** The band row the map wants shown, if any. */bandLine() {@@ -3660,8 +3918,8 @@ var LensMap = class {this.animator.end();}/**- * A `/clear`: the conversation's trail and edits go, so nothing of it stays- * lit. The feed, the repo and the importers already asked for (index data,+ * A `/clear`: the conversation's trail and edits go, with the selection and+ * the zoom, so nothing of it stays lit. The feed, the repo and the importers already asked for (index data,* by path) stay, and so does an open pane.*/clearConversation(io) {@@ -3669,6 +3927,7 @@ var LensMap = class {this.edited.clear();this.editPath = null;this.band = null;+ this.turnStarted();io.redraw();}setRepo(io, repo) {@@ -3711,10 +3970,16 @@ var LensMap = class {const desktop = pane.surface === "desktop";const style = { theme: pane.theme, health: this.health };const size = mapSize(pane, this.health);- const layout = this.layoutFor({ data, ...desktop ? desktopSize(size) : size, style }, repo.caseInsensitive);- const { lit, reach } = this.lighting();- const overlay = resolveLit(layout, lit);- const parts = { story: this.turn().story, reach, scope: scopeFacts(layout, data, repo, notOnMap(layout, lit)) };+ const at = desktop ? desktopSize(size) : size;+ let layout = this.layoutFor({ data, ...at, style, root: this.zoom }, repo.caseInsensitive);+ if (layout.root !== null && layout.files.length === 0) {+ this.zoom = null;+ layout = this.layoutFor({ data, ...at, style, root: null }, repo.caseInsensitive);+ }+ const lighting = this.lighting();+ const paths = this.see(layout, lighting.lit);+ const overlay = resolveLit(layout, lighting.lit, this.selected);+ const parts = this.parts(layout, lighting, scopeFacts(layout, data, repo, notOnMap(layout, lighting.lit)), paths);if (desktop) return svgPaneView(layout, overlay, parts);this.drawn = { layout, root: repo.root };return mapPaneView(layout, frameCells(layout, overlay, mapStep(this.animator.progress(Date.now()))), parts);@@ -3729,12 +3994,15 @@ var LensMap = class {if (status === "ready") return null;return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;}- /** The layout for this feed, size and style; laid out again only when one of them changed. */- layoutFor(key, caseInsensitive) {- const c = this.layoutCache;- if (c !== null && sameKey(c.key, key)) return c.layout;- const layout = layoutMap(key.data.files, { columns: key.columns, rows: key.rows, caseInsensitive, style: key.style });- this.layoutCache = { key, layout };+ /** The layout for this feed, size, style and zoom; kept per (zoom, size, style) for the feed, a few at a time. */+ layoutFor(key2, caseInsensitive) {+ if (this.layoutCache?.data !== key2.data) this.layoutCache = { data: key2.data, layouts: /* @__PURE__ */ new Map() };+ const layouts = this.layoutCache.layouts;+ const cached = layouts.get(cacheKey(key2));+ if (cached !== void 0) return cached;+ const layout = layoutMap(key2.data.files, { columns: key2.columns, rows: key2.rows, caseInsensitive, style: key2.style, root: key2.root });+ if (layouts.size >= LAYOUT_CACHE) layouts.delete(layouts.keys().next().value);+ layouts.set(cacheKey(key2), layout);return layout;}apply(io, action) {@@ -3766,9 +4034,9 @@ var LensMap = class {/** One edited file's importers, asked once; the answer is kept by path. */loadCallers(io, repo, abs) {const rel2 = relativeTo(abs, repo.root, repo.caseInsensitive);- const key = rel2 === null ? null : this.keyOf(rel2);- if (rel2 === null || key === null || this.importers.has(key)) return;- this.importers.set(key, { status: "loading" });+ const key2 = rel2 === null ? null : this.keyOf(rel2);+ if (rel2 === null || key2 === null || this.importers.has(key2)) return;+ this.importers.set(key2, { status: "loading" });const request = { changed_files: [rel2], max_depth: CALLERS_DEPTH };withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers").then((r) => {const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel2);@@ -3818,19 +4086,19 @@ var LensMap = class {*/animate(io, kind) {if (!this.canAnimate(kind)) return io.redraw();- this.animator.play(io, kind, kind === "flash" ? FLASH_MS : RIPPLE_MS, (step) => this.frame(step));+ this.animator.play(io, kind, kind === "flash" ? FLASH_MS : RIPPLE_MS, (step2) => this.frame(step2));}/** The current trail on the drawn map at one step, or null once the map is off screen. */- frame(step) {+ frame(step2) {const on = this.drawn;- const anim = mapStep(step);+ const anim = mapStep(step2);if (on === null || anim === void 0) return null;- const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit), anim);+ const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit, this.selected), anim);return { key: MAP_KEY, cells, columns: on.layout.columns, rows: on.layout.rows };}};-function mapStep(step) {- return step !== void 0 && (step.kind === "flash" || step.kind === "ripple") ? step : void 0;+function mapStep(step2) {+ return step2 !== void 0 && (step2.kind === "flash" || step2.kind === "ripple") ? step2 : void 0;}__name(mapStep, "mapStep");@@ -4603,7 +4871,7 @@ function bind($) {blastLanded: /* @__PURE__ */ __name((path, r) => flowBlast(bound, path, r), "blastLanded"),redraw: /* @__PURE__ */ __name(() => $.ui.invalidate("ui.render"), "redraw"),debug: /* @__PURE__ */ __name((message) => $.ui.log(`lens: ${message}`, { to: "debug" }), "debug"),- blit: /* @__PURE__ */ __name((key, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key, cells, columns, rows }), "blit"),+ blit: /* @__PURE__ */ __name((key2, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: key2, cells, columns, rows }), "blit"),// Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.// Opened unasked on a read: the map is what it opens to. This happens at most once, and never// after the person opened the pane (/lens, Why), the only ways to have picked a tab by then.@@ -4795,6 +5063,7 @@ async function onTurnStart($, e, next) {started2 = null;}dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });+ map.turnStarted();} catch (err) {bind($).debug(`turn.start failed: ${String(err)}`);}@@ -5131,11 +5400,11 @@ function tabPresses($, bar) {}__name(tabPresses, "tabPresses");function flowRowPresses($) {- return Object.fromEntries(flowPresses(flow.state).map(([key, id]) => [key, () => pressFlow($, key, id)]));+ return Object.fromEntries(flowPresses(flow.state).map(([key2, id]) => [key2, () => pressFlow($, key2, id)]));}__name(flowRowPresses, "flowRowPresses");-function pressFlow($, key, id) {- noteFlow(bind($), () => id !== null ? { type: "toggle", id } : { type: "step", by: key === FLOW_NEXT ? 1 : -1 });+function pressFlow($, key2, id) {+ noteFlow(bind($), () => id !== null ? { type: "toggle", id } : { type: "step", by: key2 === FLOW_NEXT ? 1 : -1 });}__name(pressFlow, "pressFlow");function selectTab($, tab) {@@ -5160,10 +5429,11 @@ var TAB_BODIES = {map: /* @__PURE__ */ __name((b, e) => mapBody(b, e), "map")};function mapTurn() {- if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state) };+ const knows = /* @__PURE__ */ __name((path) => knowsOf(path, state.contexts, flowOn ? flow.state : null), "knows");+ if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state), knows };const root = state.repoRoot;const lit = root === null ? NO_LIT : litFromTrail(map.trail, root, isWindowsPath(root));- return { lit, story: storyFromTrail(map.trail) };+ return { lit, story: storyFromTrail(map.trail), knows };}__name(mapTurn, "mapTurn");function mapBody(b, e) {@@ -5173,20 +5443,29 @@ function mapBody(b, e) {return map.paneTree(b, { surface: e.surface, notice: notice2, bodyColumns, placement, bodyRows: scroll.bodyRows - TAB_ROWS, theme });}__name(mapBody, "mapBody");-function pressHealth($) {+function pressMap($, key2) {try {- map.toggleHealth(bind($));+ map.press(bind($), key2);} catch (err) {- bind($).debug(`health toggle failed: ${String(err)}`);+ bind($).debug(`map key failed: ${String(err)}`);}}-__name(pressHealth, "pressHealth");+__name(pressMap, "pressMap");+function mapPresses($) {+ return Object.fromEntries(MAP_PRESSES.map((key2) => [key2, () => pressMap($, key2)]));+}+__name(mapPresses, "mapPresses");function tabBody(b, e) {const tab = state.pane.tab;if (tab !== "map") map.offScreen();if (tab !== "flow") flow.hide();const rows = (e.props.placement === "dock" ? e.props.scroll.bodyRows : PANE_ROWS) - TAB_ROWS;- return TAB_BODIES[tab](b, e, rows);+ try {+ return TAB_BODIES[tab](b, e, rows);+ } catch (err) {+ b.debug(`${tab} tab render failed: ${String(err)}`);+ return text(fit(PANE_COPY.bodyFailed, e.props.bodyColumns), { dimColor: true, wrap: "truncate-end" });+ }}__name(tabBody, "tabBody");async function onPane($, e, next) {@@ -5194,7 +5473,7 @@ async function onPane($, e, next) {const b = bind($);try {const bar = tabBar(flowOn);- const presses = { ...tabPresses($, bar), ...flowRowPresses($), [HEALTH_KEY]: () => pressHealth($) };+ const presses = { ...tabPresses($, bar), ...flowRowPresses($), ...mapPresses($) };return materialize(paneView(state.pane.tab, tabBody(b, e), bar), $.ui.resolve(e), presses);} catch (err) {b.debug(`pane render failed: ${String(err)}`);