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
fix(plugin): pass the plugin directory's checks (#3043)
Raghav Chamadiya61a9a025611e
diff --git a/docs/agent/LENS.md b/docs/agent/LENS.mdindex 8177bc2e4..06d7f5c90 100644--- a/docs/agent/LENS.md+++ b/docs/agent/LENS.md@@ -436,13 +436,18 @@ session does not reset anything.What Lens does and does not do, as the code enforces it:-- **Lens never denies, holds, rewrites or approves Claude's tool calls.** Every- tool call passes through Lens unchanged, and so does its result. The one- approval Lens gives is for its own read-only Repowise lookups: calls made by- Lens itself, to the plugin's own MCP server, for `get_context`,- `get_change_risk`, `get_why` and `get_answer`, with the reason- `Repowise Lens: its own read-only index lookup`. Every other permission- question keeps Claude Code's own answer.+- **Lens never denies, holds, rewrites or approves a tool call.** Every tool+ call passes through Lens unchanged, and so does its result. Lens registers+ no `tool.check` hook, so every permission question, its own included, gets+ Claude Code's own answer. Lens's lookups (`get_context`, `get_change_risk`,+ `get_why` and `get_answer` on the plugin's MCP server) ask permission like+ any MCP call. To let them run without a prompt, allow+ `mcp__plugin_repowise_repowise__get_context`,+ `mcp__plugin_repowise_repowise__get_change_risk`,+ `mcp__plugin_repowise_repowise__get_why` and+ `mcp__plugin_repowise_repowise__get_answer` once, with `/permissions` or in+ `permissions.allow` in your settings. A refused lookup leaves that part of+ Lens empty and the rest working.- **Flow only counts what passes.** It records each tool call's name, a fewarguments, its timing and the size of its result, never the result itself(Repowise replies keep a short summary and their first 2 KB). What Flowdiff --git a/packages/claude-mod/build.mjs b/packages/claude-mod/build.mjsindex 2ec10f4a7..1cdda644d 100644--- a/packages/claude-mod/build.mjs+++ b/packages/claude-mod/build.mjs@@ -5,8 +5,11 @@//// The mod runtime loads only files inside the plugin dir, so the shared// packages are inlined. Never minified: the engine's static check reads `$`-// calls by name. Output is deterministic (relative paths, no legal comments,-// LF) so a rebuild on any OS matches the committed file.+// calls by name. No keepNames either: its helper sets each function's name+// through Object.defineProperty, reflective code the plugin directory holds+// for review, and nothing in Lens reads a function's name. Output is+// deterministic (relative paths, no legal comments, LF) so a rebuild on any+// OS matches the committed file.import { readFile, writeFile, mkdir } from "node:fs/promises";import { dirname, resolve } from "node:path";@@ -25,7 +28,6 @@ const result = await build({format: "esm",platform: "neutral",mainFields: ["module", "main"],- keepNames: true,minify: false,legalComments: "none",charset: "utf8",@@ -36,6 +38,19 @@ const result = await build({const banner = "// Generated by packages/claude-mod (npm run build:mod). Do not edit.\n";const output = banner + result.outputFiles[0].text.replace(/\r\n/g, "\n");+// The plugin directory reads every `on` in the bundle as register's `on`: a+// variable or parameter of that name anywhere else fails its check. Ceiling:+// a regex, not a parse; it catches declarations and parameters, the usual way+// a source file brings the name back.+const onDeclared = [...output.matchAll(/\b(?:const|let|var|function)\s+on\b|[(,]\s*on\s*(?:[,)=]|:\s)/g)].filter(+ (m) => !output.startsWith("function register(on,", m.index - "function register".length),+);+if (onDeclared.length > 0) {+ const lines = onDeclared.map((m) => output.slice(0, m.index).split("\n").length);+ console.error(`lens.js declares "on" outside register (lines ${lines.join(", ")}). Rename it in the source.`);+ process.exit(1);+}+if (check) {let current = "";try {diff --git a/packages/claude-mod/mod-test/lens.test.ts b/packages/claude-mod/mod-test/lens.test.tsindex 5a5643bcb..d9e448ad9 100644--- a/packages/claude-mod/mod-test/lens.test.ts+++ b/packages/claude-mod/mod-test/lens.test.ts@@ -93,37 +93,13 @@ test('outside a git work tree the band stays empty', async ($, on) => {const OWN_TOOL = 'mcp__plugin_repowise_repowise__get_context'const CORE = { decision: 'ask', reason: 'core' }-/** Stands in for another plugin that asks about Lens's tool. */-const foreign = {- name: 'foreign',- register(on: any) {- on('turn.start', async ($: any, e: any, next: any) => {- const verdict = await $.tool.check({ tool: 'mcp__plugin_repowise_repowise__get_context', input: {} })- return { ...(await next(e)), verdict }- })- },-}--test("Claude's own call to a Lens tool keeps the engine's verdict", async ($, on) => {+test("Lens leaves every permission decision to Claude Code, its own lookups included", async ($, on) => {on('tool.check', () => CORE)expect(await $.tool.check({ tool: OWN_TOOL, input: {}, tool_use_id: 'toolu_01abc' } as any)).toEqual(CORE)- // A plugin-shaped id is not enough: the engine raised it, not Lens.expect(await $.tool.check({ tool: OWN_TOOL, input: {}, tool_use_id: 'toolu_plugin_01' } as any)).toEqual(CORE)-})--test('a tool outside the allowlist is never approved', async ($, on) => {- on('tool.check', () => CORE)- const tool = 'mcp__plugin_repowise_repowise__get_dead_code'- expect(await $.tool.check({ tool, input: {}, tool_use_id: 'toolu_plugin_01' } as any)).toEqual(CORE)expect(await $.tool.check({ tool: 'Bash', input: { command: 'ls' }, tool_use_id: 'toolu_plugin_02' } as any)).toEqual(CORE)})-test("another plugin's question about a Lens tool keeps the engine's verdict", { plugins: [foreign] }, async ($, on) => {- on('tool.check', () => CORE)- on('turn.start', () => ({ turnId: 't1' }))- expect(await ($ as any).turn.start({ turnId: 't1', prompt: 'hi' })).toMatchObject({ verdict: CORE })-})-const SPINNER = {plugin: 'repowise',component: 'Spinner',diff --git a/packages/claude-mod/src/data/mcp.ts b/packages/claude-mod/src/data/mcp.tsindex 5730dfe98..93d8a77bf 100644--- a/packages/claude-mod/src/data/mcp.ts+++ b/packages/claude-mod/src/data/mcp.ts@@ -1,8 +1,9 @@/**- * Lens's own read-only calls to this plugin's repowise MCP server, and the- * rule for approving them. The engine approves a call only when it STARTS- * while one of Lens's hooks is live, so a caller starts the call inside its- * hook (awaited or `void`), never from a timer or a late promise.+ * Lens's own read-only calls to this plugin's repowise MCP server. They go+ * through Claude Code's permission rules like any MCP call, and the engine+ * runs one only when it STARTS while one of Lens's hooks is live, so a caller+ * starts the call inside its hook (awaited or `void`), never from a timer or+ * a late promise.*/import type { Host } from "../host";@@ -10,14 +11,11 @@ import type { McpToolResult } from "../mod-api";import type { FileContext } from "../model/session";import { withTimeout } from "./transport";-/** This plugin's name, as `next.origin.plugin` reports it. */-export const PLUGIN_NAME = "repowise";-/** Only the tools a shipped Lens feature calls. All read-only. */export const LENS_TOOLS = ["get_context", "get_change_risk", "get_why", "get_answer"] as const;export type LensTool = (typeof LENS_TOOLS)[number];-/** Both spellings of this plugin's server seen at runtime; Lens calls and approves no other. */+/** Both spellings of this plugin's server seen at runtime; Lens calls no other. */const PLUGIN_SERVER_FORMS: readonly string[] = ["plugin:repowise:repowise", "plugin_repowise_repowise"];const DEFAULT_TIMEOUT_MS = 10_000;@@ -65,26 +63,6 @@ export async function mcpReady(host: Host, timeoutMs = DEFAULT_TIMEOUT_MS): Promreturn resolvedServer !== null;}-/** How a server's tools are named in `tool.check` (`mcp__plugin_repowise_repowise__get_context`). */-export function toolName(serverForm: string, tool: string): string {- return `mcp__${serverForm.replace(/[^A-Za-z0-9_-]/g, "_")}__${tool}`;-}--const OWN_TOOL_NAMES: ReadonlySet<string> = new Set(- PLUGIN_SERVER_FORMS.flatMap((form) => LENS_TOOLS.map((tool) => toolName(form, tool))),-);--/**- * Whether a `tool.check` is for one of Lens's own calls: a plugin-made call- * (id `toolu_plugin_`), raised by this plugin, to an allowlisted tool on this- * plugin's server. Anything else keeps the engine's verdict.- */-export function isOwnLensCall(e: { tool: string; tool_use_id?: string | undefined }, originPlugin: unknown): boolean {- if (originPlugin !== PLUGIN_NAME) return false;- if (typeof e.tool_use_id !== "string" || !e.tool_use_id.startsWith("toolu_plugin_")) return false;- return OWN_TOOL_NAMES.has(e.tool);-}-function parse<T>(result: McpToolResult, tool: string): T {const text = result.content[0]?.text;if (result.isError) throw new Error(`${tool} failed: ${String(text).slice(0, 200)}`);@@ -98,7 +76,7 @@ function parse<T>(result: McpToolResult, tool: string): T {/*** Calls one allowlisted tool and returns the parsed `result`. The call starts* synchronously, so it starts while the calling hook is live (the engine- * approves Lens's call only then); with no server name resolved yet it does+ * runs Lens's call only then); with no server name resolved yet it does* not start at all and rejects, and the caller tries again from a later hook.* Rejects on timeout or a tool error; nothing retries after the hook.*/diff --git a/packages/claude-mod/src/flow-controller.ts b/packages/claude-mod/src/flow-controller.tsindex 05cf36681..4abd49c89 100644--- a/packages/claude-mod/src/flow-controller.ts+++ b/packages/claude-mod/src/flow-controller.ts@@ -47,8 +47,8 @@ export class LensFlow {private ticker: ReturnType<typeof setInterval> | undefined;private happy: ReturnType<typeof setTimeout> | undefined;- setReducedMotion(on: boolean): void {- this.still = on;+ setReducedMotion(reduced: boolean): void {+ this.still = reduced;}/** Another tab is shown, or the pane is gone: nothing of Flow is on screen. */diff --git a/packages/claude-mod/src/map-controller.ts b/packages/claude-mod/src/map-controller.tsindex e5a052399..85386ef6f 100644--- a/packages/claude-mod/src/map-controller.ts+++ b/packages/claude-mod/src/map-controller.ts@@ -231,8 +231,8 @@ export class LensMap {}/** The person's `prefersReducedMotion` setting: resting frames only. */- setReducedMotion(on: boolean): void {- this.reducedMotion = on;+ setReducedMotion(reduced: boolean): void {+ this.reducedMotion = reduced;}dispose(): void {@@ -423,9 +423,9 @@ export class LensMap {/** Whether an animation would show anything: a map on screen, motion allowed, a ripple with somewhere to go. */private canAnimate(kind: Anim["kind"]): boolean {- const on = this.drawn;- if (this.reducedMotion || on === null) return false;- return kind === "flash" || rippleRadius(on.layout, resolveLit(on.layout, this.lighting().lit)) > 0;+ const drawn = this.drawn;+ if (this.reducedMotion || drawn === null) return false;+ return kind === "flash" || rippleRadius(drawn.layout, resolveLit(drawn.layout, this.lighting().lit)) > 0;}/**@@ -439,12 +439,12 @@ export class LensMap {/** The current trail on the drawn map at one step, or null once the map is off screen. */private frame(step: Step): Frame {- const on = this.drawn;+ const drawn = this.drawn;const anim = mapStep(step);- if (on === null || anim === undefined) return null;+ if (drawn === null || anim === undefined) return null;// 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 };+ const cells = frameCells(drawn.layout, resolveLit(drawn.layout, this.lighting().lit, this.selected), anim);+ return { key: MAP_KEY, cells, columns: drawn.layout.columns, rows: drawn.layout.rows };}}diff --git a/packages/claude-mod/src/mod-api.ts b/packages/claude-mod/src/mod-api.tsindex 1b2331dbe..60d169591 100644--- a/packages/claude-mod/src/mod-api.ts+++ b/packages/claude-mod/src/mod-api.ts@@ -115,16 +115,6 @@ export interface ToolCallEvent {[arg: string]: unknown;}-export interface ToolCheckEvent {- tool: string;- input: unknown;- /** Absent on a query (`$.tool.check`). */- tool_use_id?: string;-}--/** `next` of `tool.check` also says whose call is being decided. */-export type CheckNext = ((e: ToolCheckEvent) => Promise<unknown>) & { origin: { plugin: string; tier?: string } };-export interface SpinnerEvent {props: { word: string; message: string | null; suffix: string; mode: string };}@@ -173,7 +163,6 @@ export interface On {(event: "turn.start", hook: Hook<TurnStartEvent>): unknown;(event: "ui.render", matcher: { component: "AbovePrompt" }, hook: Hook<RenderEvent>): unknown;(event: "tool.call", hook: Hook<ToolCallEvent>): unknown;- (event: "tool.check", hook: ($: ModApi, e: ToolCheckEvent, next: CheckNext) => Promise<unknown>): unknown;(event: "ui.render", matcher: { component: "Spinner" }, hook: Hook<SpinnerEvent>): unknown;(event: "ui.render", matcher: { component: "ToolResult" }, hook: Hook<ToolResultEvent>): unknown;(event: "ui.render", matcher: { component: "ToolUse" }, hook: Hook<ToolUseEvent>): unknown;diff --git a/packages/claude-mod/src/register.ts b/packages/claude-mod/src/register.tsindex 808214a8b..51982bdde 100644--- a/packages/claude-mod/src/register.ts+++ b/packages/claude-mod/src/register.ts@@ -6,7 +6,7 @@import { getSavings } from "@repowise-dev/api-client/costs";import { discover, isWindowsPath, readFreshness, type Discovery } from "./data/discovery";-import { callTool, fetchFileContext, isOwnLensCall, mcpReady, resetMcp, warmMcp } from "./data/mcp";+import { callTool, fetchFileContext, mcpReady, resetMcp, warmMcp } from "./data/mcp";import { withTimeout } from "./data/transport";import { fit } from "./format";import type { Host } from "./host";@@ -19,7 +19,6 @@ 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,CommandRunEvent,ModApi,On,@@ -32,7 +31,6 @@ import type {SessionStartEvent,SpinnerEvent,ToolCallEvent,- ToolCheckEvent,ToolResultEvent,ToolUseEvent,TurnCompleteEvent,@@ -366,7 +364,7 @@ async function fetchReview(b: Bound): Promise<SessionAction> {/*** Starts a review of the working tree, not awaited. Only ever called while a* Lens hook is live (an edit's tool.call, or turn.complete), which is when the- * engine approves the call.+ * engine runs the call.*/function startReview(b: Bound): StartedReview {const review: StartedReview = { gen: reviewGeneration, covers: editsThisTurn, settled: false, outcome: fetchReview(b) };@@ -520,7 +518,7 @@ async function onPostCompact(/*** Asks the index, one question at a time. Only called from a live hook (the* Ask field's `ui.input`, or `/lens ask`): `callTool` starts the call at- * once, which is when the engine approves Lens's own lookup.+ * once, which is when the engine runs Lens's own lookup.*/function startAsk(b: Bound, question: string): void {const q = question.trim();@@ -545,7 +543,7 @@ function startAsk(b: Bound, question: string): void {}// The Ask field's Enter. The lookup starts here, in Lens's own hook, so the-// engine approves it; the field's own closure does nothing.+// engine runs it; the field's own closure does nothing.async function onAskInput($: ModApi, e: UiInputEvent, next: (e: UiInputEvent) => Promise<unknown>): Promise<unknown> {try {if (e.kind === "submit" && e.element === ASK_KEY) startAsk(bind($), e.value);@@ -592,7 +590,7 @@ async function onBand($: ModApi, e: RenderEvent, next: (e: RenderEvent) => Promi/*** Fetches a file's context once per session, started here and not awaited:- * the engine approves Lens's call because it starts while this hook is live,+ * the engine runs Lens's call because it starts while this hook is live,* and the spinner shows it from the first render after it lands.* Ceiling: cached for the session, so an index update mid-session is not seen.*/@@ -716,19 +714,6 @@ function editLanded(b: Bound, e: ToolCallEvent, result: unknown): void {}}-// The one approval Lens gives: its own read-only lookups. Every other-// question keeps the engine's verdict, untouched.-async function onToolCheck($: ModApi, e: ToolCheckEvent, next: CheckNext): Promise<unknown> {- try {- if (isOwnLensCall(e, next.origin?.plugin)) {- return { decision: "allow", reason: "Repowise Lens: its own read-only index lookup" };- }- } catch (err) {- bind($).debug(`tool.check failed: ${String(err)}`);- }- return next(e);-}-// Rewrites only the suffix prop, so the engine keeps drawing (and animating) the line.async function onSpinner($: ModApi, e: SpinnerEvent, next: (e: SpinnerEvent) => Promise<unknown>): Promise<unknown> {let line: string | null = null;@@ -949,9 +934,10 @@ export function register(on: On, options: PluginOptions = {}): void {// The brief is only offered: nothing here hooks `session.compact`.on("classic.PostCompact", onPostCompact);on("tool.call", onToolCall);- on("tool.check", onToolCheck);on("ui.render", { component: "Spinner" }, onSpinner);- if (options["lens_squeeze"] !== false) on("ui.render", { component: "ToolResult" }, onToolResult);+ if (options["lens_squeeze"] !== false) {+ on("ui.render", { component: "ToolResult" }, onToolResult);+ }if (options["lens_margin"] !== false) {on("classic.PostToolUse", onPostToolUse);on("ui.render", { component: "ToolUse" }, onToolUse);diff --git a/packages/claude-mod/src/views/copy.ts b/packages/claude-mod/src/views/copy.tsindex ad039bc87..01d546c25 100644--- a/packages/claude-mod/src/views/copy.ts+++ b/packages/claude-mod/src/views/copy.ts@@ -624,7 +624,7 @@ export function freshnessText(b: Pick<Behind, "indexBehind" | "ageDays">): strin}const ageText = (days: number): string => `index ${countOf(days, "day", "days")} old`;-const when = (on: boolean, text: string): string | null => (on ? text : null);+const when = (shown: boolean, text: string): string | null => (shown ? text : null);const named = <T>(v: T | null, text: (v: T) => string): string | null => (v === null ? null : text(v));/** How the reply says it was answered, in the order the detail lists it; each part only when the reply said it. */diff --git a/packages/claude-mod/src/views/flow.ts b/packages/claude-mod/src/views/flow.tsindex e820b2fe3..a4e3f54d1 100644--- a/packages/claude-mod/src/views/flow.ts+++ b/packages/claude-mod/src/views/flow.ts@@ -55,7 +55,7 @@ import { packRows } from "./mapPane";import { OWL_WIDTH, owl, owlEyes, type OwlState } from "./owl";import { THISTLE, flowTheme, hills, loch, type FlowTheme } from "./theme";-export const FLOW_KEY = "lens-flow";+export const FLOW_BOX_ID = "lens-flow";export const FLOW_NEXT = "lens-flow-next";export const FLOW_PREV = "lens-flow-prev";/** How long the owl stays happy after a turn ends. */@@ -102,7 +102,7 @@ export interface FlowViewInput {}/** The Button key of an openable row. */-export const rowKey = (id: string): string => `${FLOW_KEY}-${id}`;+export const rowKey = (id: string): string => `${FLOW_BOX_ID}-${id}`;/** Every Button key the tab may draw, with the row it opens (null for the hotkeys). */export function flowPresses(state: FlowState): Array<[key: string, id: string | null]> {@@ -464,5 +464,5 @@ export function flowView(state: FlowState, v: FlowViewInput): Node {const room = Math.max(MIN_BODY, v.rows - head.length - fixed.length - after.length - 1);const calls = turn === undefined ? [] : windowed(callLines(state, turn, v, theme), room, state.open);const callNodes = section(FLOW_COPY.calls, calls.map((l) => l.node));- return box({ key: FLOW_KEY, flexDirection: "column" }, [...head, ...fixed, ...callNodes, ...after]);+ return box({ key: FLOW_BOX_ID, flexDirection: "column" }, [...head, ...fixed, ...callNodes, ...after]);}diff --git a/packages/claude-mod/src/views/mapPane.ts b/packages/claude-mod/src/views/mapPane.tsindex 78e95ef77..1295554f2 100644--- a/packages/claude-mod/src/views/mapPane.ts+++ b/packages/claude-mod/src/views/mapPane.ts@@ -229,14 +229,14 @@ const MORE = "…";* under a blit.*/export function keyRow(keys: MapKeyState, style: MapStyle, columns: number): Node {- const on: [MapKeyName, boolean][] = [+ const offered: [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 all = [...offered.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);diff --git a/packages/claude-mod/test/flowView.test.ts b/packages/claude-mod/test/flowView.test.tsindex 9143498bd..f04639409 100644--- a/packages/claude-mod/test/flowView.test.ts+++ b/packages/claude-mod/test/flowView.test.ts@@ -26,7 +26,7 @@ import {turnFooter,} from "../src/views/copy";import type { Node } from "../src/views/elements";-import { ACTIVE_MARK, FLOW_KEY, FLOW_NEXT, FLOW_PREV, HAPPY_MS, flowPresses, flowView, rowKey, type FlowViewInput } from "../src/views/flow";+import { ACTIVE_MARK, FLOW_BOX_ID, FLOW_NEXT, FLOW_PREV, HAPPY_MS, flowPresses, flowView, rowKey, type FlowViewInput } from "../src/views/flow";import { BLINK_MS, EYES, owl, owlEyes } from "../src/views/owl";import { THISTLE, flowTheme, hills, loch } from "../src/views/theme";import { fixture } from "./fake-host";@@ -210,7 +210,7 @@ describe("Flow copy", () => {describe("the Flow tab", () => {it("empty: the owl asleep and what the tab will show, wrapped to 70 columns", () => {const tree = view(initialFlow);- expect(tree.type === "Box" && tree.props.key).toBe(FLOW_KEY);+ expect(tree.type === "Box" && tree.props.key).toBe(FLOW_BOX_ID);const shown = lines(tree);expect(shown[0]).toBe(hills(120));expect(shown[1]).toBe("{─,─} Lens is listening. Send a prompt and this tab shows what only Lens");diff --git a/packages/claude-mod/test/mcp.test.ts b/packages/claude-mod/test/mcp.test.tsindex 40d0b78e6..f11be41ac 100644--- a/packages/claude-mod/test/mcp.test.ts+++ b/packages/claude-mod/test/mcp.test.ts@@ -2,12 +2,9 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {callTool,fetchFileContext,- isOwnLensCall,LENS_TOOLS,mcpReady,- PLUGIN_NAME,resetMcp,- toolName,warmMcp,} from "../src/data/mcp";import type { McpToolResult } from "../src/mod-api";@@ -161,43 +158,8 @@ describe("fetchFileContext", () => {});});-describe("isOwnLensCall", () => {- const own = { tool: "mcp__plugin_repowise_repowise__get_context", tool_use_id: "toolu_plugin_ab12" };-- it("approves Lens's own call to an allowlisted tool on this plugin's server", () => {- expect(isOwnLensCall(own, PLUGIN_NAME)).toBe(true);- });-- it("refuses a call another plugin made, or the engine", () => {- expect(isOwnLensCall(own, "other-plugin")).toBe(false);- expect(isOwnLensCall(own, "engine")).toBe(false);- expect(isOwnLensCall(own, undefined)).toBe(false);- });-- it("refuses Claude's own call to the same tool, and a query with no call id", () => {- expect(isOwnLensCall({ ...own, tool_use_id: "toolu_01abc" }, PLUGIN_NAME)).toBe(false);- expect(isOwnLensCall({ tool: own.tool }, PLUGIN_NAME)).toBe(false);- });-- it("refuses a tool outside the allowlist, or on another server", () => {- expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_dead_code" }, PLUGIN_NAME)).toBe(false);- expect(isOwnLensCall({ ...own, tool: "mcp__evil__get_context" }, PLUGIN_NAME)).toBe(false);- expect(isOwnLensCall({ ...own, tool: "Bash" }, PLUGIN_NAME)).toBe(false);- });-- it("approves both forms of this plugin's server and never a name connect resolved to elsewhere", async () => {- expect(isOwnLensCall({ ...own, tool: toolName("plugin:repowise:repowise", "get_context") }, PLUGIN_NAME)).toBe(true);- await warmed(fakeHost({ server: "repowise" }));- expect(isOwnLensCall({ ...own, tool: toolName("repowise", "get_context") }, PLUGIN_NAME)).toBe(false);- });-- it("allowlists only the tools a shipped feature calls", () => {+describe("LENS_TOOLS", () => {+ it("lists only the read-only tools a shipped feature calls", () => {expect(LENS_TOOLS).toEqual(["get_context", "get_change_risk", "get_why", "get_answer"]);- expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_why" }, PLUGIN_NAME)).toBe(true);- expect(isOwnLensCall({ ...own, tool: "mcp__plugin_repowise_repowise__get_answer" }, PLUGIN_NAME)).toBe(true);- });-- it("spells a server's tools the way tool.check names them", () => {- expect(toolName("plugin:repowise:repowise", "get_context")).toBe("mcp__plugin_repowise_repowise__get_context");});});diff --git a/packages/claude-mod/test/register.test.ts b/packages/claude-mod/test/register.test.tsindex d835aa305..349965eba 100644--- a/packages/claude-mod/test/register.test.ts+++ b/packages/claude-mod/test/register.test.ts@@ -1,5 +1,5 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import type { CheckNext, Hook, McpToolResult, ModApi, On, ToolCheckEvent } from "../src/mod-api";+import type { Hook, McpToolResult, ModApi, On } from "../src/mod-api";import { DARK } from "@repowise-dev/ui/brand";import { TimeoutError } from "../src/data/transport";import { buttonsOf, fixture, mcpResult } from "./fake-host";@@ -167,7 +167,6 @@ describe("register", () => {"session.start","session.end","tool.call",- "tool.check","turn.complete","turn.start","ui.input:lens-ask",@@ -280,35 +279,6 @@ const SESSIONS = JSON.parse(fixture("mcp/get_context-sessions.json")) as McpToolconst READ = { tool: "Read", tool_use_id: "toolu_01", file_path: "/work/app/src/requests/sessions.py" };const SPINNER = { props: { word: "Sauteing", message: null, suffix: "…", mode: "tool-use" } };-function checkNext(plugin: string, verdict: unknown): CheckNext {- return Object.assign(async (_e: ToolCheckEvent) => verdict, { origin: { plugin, tier: "user" } });-}--describe("tool.check", () => {- const own = { tool: "mcp__plugin_repowise_repowise__get_context", input: {}, tool_use_id: "toolu_plugin_1" };- const core = { decision: "ask", reason: "core" };-- it("approves Lens's own lookup", async () => {- const { $ } = fakeDollar();- expect(await hooks["tool.check"]!($, own, checkNext("repowise", core))).toMatchObject({ decision: "allow" });- const review = { ...own, tool: "mcp__plugin_repowise_repowise__get_change_risk" };- expect(await hooks["tool.check"]!($, review, checkNext("repowise", core))).toMatchObject({ decision: "allow" });- });-- it("returns the engine's verdict for Claude's call, another plugin's call, and any other tool", async () => {- const { $ } = fakeDollar();- const asks = [- [{ ...own, tool_use_id: "toolu_01abc" }, "engine"],- [own, "someone-else"],- [{ ...own, tool: "mcp__plugin_repowise_repowise__get_dead_code" }, "repowise"],- [{ ...own, tool: "Bash", input: { command: "rm -rf /" } }, "repowise"],- ] as const;- for (const [e, plugin] of asks) {- expect(await hooks["tool.check"]!($, e, checkNext(plugin, core))).toBe(core);- }- });-});-describe("tool.call and the spinner", () => {async function indexedSession(mcp?: () => Promise<McpToolResult>) {const d = fakeDollar({ indexed: true, ...(mcp ? { mcp } : {}) });diff --git a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.mdindex 90f156c5e..ec596faf7 100644--- a/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md+++ b/packages/cli/src/repowise/cli/agent_targets/_data/codex_prompts/repowise-init.md@@ -175,22 +175,13 @@ Then continue to Step 4 for the model-written wiki, or Step 5 otherwise.**Skip this entire step unless the user chose the model-written wiki.** Amissing key is not a blocker: `init` renders the template wiki and exits 0-without one. If you cannot find a key, do not stop and do not ask again. Run+without one. If the user has no key, do not stop and do not ask again. Run`repowise init --yes` and tell the user their wiki is rendered from structureand can be upgraded per-page later with `repowise generate`.-Check which API keys are already set by running:-```bash-echo "ANTHROPIC=${ANTHROPIC_API_KEY:+set}" "OPENAI=${OPENAI_API_KEY:+set}" "GEMINI=${GEMINI_API_KEY:+set}${GOOGLE_API_KEY:+set}" "OLLAMA=${OLLAMA_BASE_URL:+set}"-```--If one or more keys are detected, suggest the detected provider:-- `ANTHROPIC_API_KEY` set → suggest `--provider anthropic`-- `OPENAI_API_KEY` set → suggest `--provider openai`-- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set → suggest `--provider gemini`-- `OLLAMA_BASE_URL` set → suggest `--provider ollama`--If no key is detected, ask:+Do not read, test or print the user's environment variables or key values+yourself. `repowise init` picks up a provider key from the environment on its+own, so a user who already has one set needs no `--provider`. Ask:"Which LLM provider do you want to use?"- **Anthropic** (Claude) — needs `ANTHROPIC_API_KEY`@@ -199,7 +190,7 @@ If no key is detected, ask:- **Ollama** (fully local, no API key, slower) — needs Ollama running locally- **LiteLLM** (100+ providers) — needs LiteLLM config-Then ask them to set the required environment variable. Show the exact export command:+If they have not set that key yet, ask them to set it in their own shell. Show the exact export command:```bashexport ANTHROPIC_API_KEY="sk-ant-..."```diff --git a/plugins/claude-code/.claude-plugin/icon.png b/plugins/claude-code/.claude-plugin/icon.pngnew file mode 100644index 000000000..268fd0a4fBinary files /dev/null and b/plugins/claude-code/.claude-plugin/icon.png differdiff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.jsonindex b3fc690b1..68e002d0a 100644--- a/plugins/claude-code/.claude-plugin/plugin.json+++ b/plugins/claude-code/.claude-plugin/plugin.json@@ -1,5 +1,6 @@{"name": "repowise",+ "displayName": "Repowise","description": "Codebase intelligence for Claude Code. Indexes your codebase into five layers (Graph, Git, Docs, Decisions, Code Health) and exposes them through task-shaped MCP tools, so Claude understands architecture, ownership, hotspots, why code is built the way it is, and where the defect risk lives.","version": "0.55.0","author": {@@ -10,6 +11,11 @@"homepage": "https://repowise.dev","repository": "https://github.com/repowise-dev/repowise","license": "AGPL-3.0",+ "icon": "./.claude-plugin/icon.png",+ "documentationUrl": "https://docs.repowise.dev",+ "supportUrl": "https://github.com/repowise-dev/repowise/issues",+ "privacyPolicyUrl": "https://repowise.dev/legal/privacy",+ "termsOfServiceUrl": "https://repowise.dev/legal/terms","userConfig": {"lens_margin": {"type": "boolean",diff --git a/plugins/claude-code/CHANGELOG.md b/plugins/claude-code/CHANGELOG.mdindex fec8a4f32..36ea5b0ee 100644--- a/plugins/claude-code/CHANGELOG.md+++ b/plugins/claude-code/CHANGELOG.md@@ -2,6 +2,23 @@All notable changes to the Repowise Claude Code plugin are documented here.+## Unreleased++### Changed+- Lens no longer approves its own MCP lookups. It registers no `tool.check`+ hook, so `get_context`, `get_change_risk`, `get_why` and `get_answer` calls+ from Lens ask Claude Code's permission like any other MCP call. The README's+ Permissions section lists the four allow rules that let them run without a+ prompt.+- Each command's `allowed-tools` now names the exact `repowise` commands it+ runs (for example `Bash(repowise health:*)`) in place of any Bash command.+ `/repowise:init` no longer pre-approves `Write`, and asks with+ `AskUserQuestion`.+- `/repowise:init` no longer reads provider key variables from the+ environment; `repowise init` detects a configured key itself.+- The plugin README lists what Lens runs, reads, fetches and submits, and the+ manifest carries the directory listing fields and an icon.+## 0.55.0### Addeddiff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.mdindex 98f35f62a..c189e8f76 100644--- a/plugins/claude-code/README.md+++ b/plugins/claude-code/README.md@@ -179,16 +179,17 @@ CLI you install with pip:- **Hooks:** the three hooks run `repowise-augment` when it is on PATH and donothing otherwise. They read the local index only.- **Lens:** reads the local index through the plugin's own MCP server and,- for the map, through `repowise serve` on a loopback address. It makes no- network requests of its own.+ for the map, through `repowise serve` on a loopback address. It contacts no+ other host. The [Lens list](#what-lens-runs-and-reads) below says exactly what it runs and+ reads.Network traffic from the `repowise` CLI and MCP server:- **Anonymous usage telemetry** to `https://api.repowise.dev/telemetry/events`:command and tool names, coarse counts and timings, and an anonymous installid. Never source code, file paths, repo or symbol names, or query text. Turn- it off with `DO_NOT_TRACK=1` or `REPOWISE_TELEMETRY_DISABLED=1`; details at- https://repowise.dev/telemetry.+ it off with `DO_NOT_TRACK=1` or `REPOWISE_TELEMETRY_DISABLED=1`; details in+ [docs/reference/TELEMETRY.md](https://github.com/repowise-dev/repowise/blob/main/docs/reference/TELEMETRY.md).- **Your model and embedding provider**, only if you configure one: pagegeneration in `init` and `update`, and `get_answer`, send code excerpts andyour question to that provider. With no provider configured nothing is sent,@@ -198,6 +199,85 @@ Network traffic from the `repowise` CLI and MCP server:- **repowise.dev**, only when you run an account command yourself(`repowise login`, `repowise publish`, or sending feedback).+### What Lens runs and reads++Lens is the mod in `hooks/lens/lens.js`, built from `packages/claude-mod`.+Everything it does goes through Claude Code's mods API:++- **Programs it runs** (`$.process.run`, read-only, 5 second timeout):+ `git rev-parse --is-inside-work-tree` to tell whether the session is in a git+ repo, and `git rev-parse HEAD` plus `git diff --name-only <indexed> <HEAD> --`+ to count the files changed since the last index (`<indexed>` is the commit in+ `.repowise/state.json`, used only when it is a bare hex sha). To check that a+ `repowise serve` or `repowise update` named in a lock file is still running+ it runs `tasklist /FI "PID eq <pid>" /NH /FO CSV` on Windows and+ `ps -p <pid> -o pid=` elsewhere.+- **Files it reads** (`$.fs`): `.repowise/state.json`, `.repowise/serve.lock.json`+ and `.repowise/.update.lock` in the repo and the folders above the session's+ directory. It writes no files.+- **MCP tools it calls itself** (`$.mcp.call`, on this plugin's own `repowise`+ server only): `get_context` for a file Claude starts reading or editing (the+ caller count and owner in the spinner), `get_change_risk` after a turn that+ edits files (the review card), and `get_why` or `get_answer` when you ask a+ question in the Ask tab or with `/lens ask`. `get_answer` may use the model+ your repo configures; the others are local. These calls go through Claude+ Code's permission rules like Claude's own; see [Permissions](#permissions)+ below.+- **The one host it fetches** (`$.http.fetch`): the `repowise serve` address in+ `.repowise/serve.lock.json`, and only when that address is plain `http` on a+ loopback host (`127.0.0.1`, `localhost` or `::1`). It asks that server for+ its health, its repo list, the health map, the blast radius of a file Claude+ edited (the file's path) and the savings ledger. Nothing it reads from the+ conversation goes anywhere else.+- **What it reads from the conversation:** each tool call's name, a few of its+ arguments (file paths, the start of a Bash command) and the size of its+ result; the first 160 characters of your prompt at `turn.start`; and at+ `turn.complete` the answer's+ text (to place the review card under it), the turn's duration and how it+ ended. It keeps these in memory for the session's Flow tab and map, and+ writes none of it to disk.+- **Prompts it submits** (`$.prompt.submit`), only when you press the button:+ `Run tests` sends `Run the tests Repowise names for this change, ...: <test+ ids>`. `Brief Claude` (offered after a compaction) sends `The context was+ compacted. This brief is built from the Repowise index and this session's+ edits:` followed by up to three lines, `Files edited:`, `Decisions in play:`+ and `Open review items:`, at most 1,200 characters. `Why` submits nothing:+ it fills the Ask field with `why <decision title>` and waits for Enter.+- **Hooks that decide or change something:** Lens registers no `tool.check`+ hook, so it never approves or denies a tool call. Its `tool.call` hook passes+ every call and result on unchanged. `turn.complete` adds the review card as+ a line under Claude's answer, which Claude does not read. `command.run`+ answers only `/lens`+ (opening the pane on the tab you name, and asking with `/lens ask`).+ `classic.PostCompact` only offers the brief, and `classic.PostToolUse` reads+ the note the Repowise hook added for an edit to show it in the margin; both+ pass their event and result on unchanged.+- **No reflective tricks:** the bundle is plain, unminified esbuild output with+ no `Proxy`, getters or `then` methods of its own.++#### Permissions++Lens's own lookups ask Claude Code's permission like any MCP tool call. To let+them run without a prompt, allow the four read-only tools once, for example+with `/permissions` or in `.claude/settings.json`:++```json+{+ "permissions": {+ "allow": [+ "mcp__plugin_repowise_repowise__get_context",+ "mcp__plugin_repowise_repowise__get_change_risk",+ "mcp__plugin_repowise_repowise__get_why",+ "mcp__plugin_repowise_repowise__get_answer"+ ]+ }+}+```++Without the rules, a lookup that is refused (in auto mode, `dontAsk`, or+`claude -p`) leaves that part of Lens empty: no file card in the spinner, no+review card, or an error line in the Ask tab. The rest of Lens works.+## LicenseAGPL-3.0, same as repowise. See the [repository](https://github.com/repowise-dev/repowise).diff --git a/plugins/claude-code/commands/ask.md b/plugins/claude-code/commands/ask.mdindex 95724d873..97cffa841 100644--- a/plugins/claude-code/commands/ask.md+++ b/plugins/claude-code/commands/ask.md@@ -1,6 +1,6 @@---description: Ask a codebase question and get a cited, synthesised answer with a confidence rating (costs an LLM call).-allowed-tools: Bash, Read+allowed-tools: Bash(repowise ask:*), Read---# Repowise Askdiff --git a/plugins/claude-code/commands/context.md b/plugins/claude-code/commands/context.mdindex f4943cb4c..e4361ba23 100644--- a/plugins/claude-code/commands/context.md+++ b/plugins/claude-code/commands/context.md@@ -1,6 +1,6 @@---description: Triage card for files, modules, or symbols — layer, hotspot, fix history, freshness (relationships, not source bytes).-allowed-tools: Bash, Read+allowed-tools: Bash(repowise context:*), Read---# Repowise Contextdiff --git a/plugins/claude-code/commands/coverage.md b/plugins/claude-code/commands/coverage.mdindex 3b11b35b6..b94f005d7 100644--- a/plugins/claude-code/commands/coverage.md+++ b/plugins/claude-code/commands/coverage.md@@ -1,6 +1,6 @@---description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, repowise JSON, or coverage.py .coverage; builds the per-test map when contexts are present), or gate a change on its patch coverage in CI.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise coverage:*), Read---# Repowise Coveragediff --git a/plugins/claude-code/commands/dead-code.md b/plugins/claude-code/commands/dead-code.mdindex 1e0fdb0c2..f404fee0d 100644--- a/plugins/claude-code/commands/dead-code.md+++ b/plugins/claude-code/commands/dead-code.md@@ -1,6 +1,6 @@---description: Report unreachable files, unused exports, and zombie packages, tiered by confidence.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise dead-code:*), Read---# Repowise Dead Codediff --git a/plugins/claude-code/commands/decision.md b/plugins/claude-code/commands/decision.mdindex 33c34fff8..6bb9d02aa 100644--- a/plugins/claude-code/commands/decision.md+++ b/plugins/claude-code/commands/decision.md@@ -1,6 +1,6 @@---description: Work with architectural decisions — list, inspect health, add, or confirm auto-proposed decisions.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise decision:*), Read---# Repowise Decisionsdiff --git a/plugins/claude-code/commands/doctor.md b/plugins/claude-code/commands/doctor.mdindex 53cf2312c..a06da65ea 100644--- a/plugins/claude-code/commands/doctor.md+++ b/plugins/claude-code/commands/doctor.md@@ -1,6 +1,6 @@---description: Diagnose the Repowise setup — install, API keys, index/store drift — and optionally repair it.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise doctor:*), Read---# Repowise Doctordiff --git a/plugins/claude-code/commands/export.md b/plugins/claude-code/commands/export.mdindex 7466d8001..e3f72ab90 100644--- a/plugins/claude-code/commands/export.md+++ b/plugins/claude-code/commands/export.md@@ -1,6 +1,6 @@---description: Export the wiki (or architecture model) to markdown, HTML, JSON, or Structurizr DSL.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise export:*), Read---# Repowise Exportdiff --git a/plugins/claude-code/commands/health.md b/plugins/claude-code/commands/health.mdindex 54bcfe289..cf59c7d96 100644--- a/plugins/claude-code/commands/health.md+++ b/plugins/claude-code/commands/health.md@@ -1,6 +1,6 @@---description: Show Repowise code-health — KPIs, lowest-scoring files, refactoring targets, trends, or per-file markers.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise health:*), Read---# Repowise Healthdiff --git a/plugins/claude-code/commands/impacted-tests.md b/plugins/claude-code/commands/impacted-tests.mdindex c92b7c67e..d36c9e050 100644--- a/plugins/claude-code/commands/impacted-tests.md+++ b/plugins/claude-code/commands/impacted-tests.md@@ -1,6 +1,6 @@---description: Print the tests whose coverage intersects a change's changed lines — for a commit, base..head range, or staged diff.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise impacted-tests:*), Read---# Repowise Impacted Testsdiff --git a/plugins/claude-code/commands/init.md b/plugins/claude-code/commands/init.mdindex 9ae9de816..d82d436c6 100644--- a/plugins/claude-code/commands/init.md+++ b/plugins/claude-code/commands/init.md@@ -1,6 +1,6 @@---description: Set up Repowise for this codebase. Installs if needed, asks about your preferences, and runs the indexing.-allowed-tools: Bash, Read, Write, AskFollowupQuestion+allowed-tools: Bash(repowise --version), Bash(repowise init:*), Bash(repowise status:*), Bash(git rev-parse --git-common-dir), Bash(pip install repowise), Bash(python -m pip install repowise), Read, AskUserQuestion---# Repowise Init@@ -176,22 +176,13 @@ Then continue to Step 4 for the model-written wiki, or Step 5 otherwise.**Skip this entire step unless the user chose the model-written wiki.** Amissing key is not a blocker: `init` renders the template wiki and exits 0-without one. If you cannot find a key, do not stop and do not ask again. Run+without one. If the user has no key, do not stop and do not ask again. Run`repowise init --yes` and tell the user their wiki is rendered from structureand can be upgraded per-page later with `repowise generate`.-Check which API keys are already set by running:-```bash-echo "ANTHROPIC=${ANTHROPIC_API_KEY:+set}" "OPENAI=${OPENAI_API_KEY:+set}" "GEMINI=${GEMINI_API_KEY:+set}${GOOGLE_API_KEY:+set}" "OLLAMA=${OLLAMA_BASE_URL:+set}"-```--If one or more keys are detected, suggest the detected provider:-- `ANTHROPIC_API_KEY` set → suggest `--provider anthropic`-- `OPENAI_API_KEY` set → suggest `--provider openai`-- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set → suggest `--provider gemini`-- `OLLAMA_BASE_URL` set → suggest `--provider ollama`--If no key is detected, ask:+Do not read, test or print the user's environment variables or key values+yourself. `repowise init` picks up a provider key from the environment on its+own, so a user who already has one set needs no `--provider`. Ask:"Which LLM provider do you want to use?"- **Anthropic** (Claude) — needs `ANTHROPIC_API_KEY`@@ -200,7 +191,7 @@ If no key is detected, ask:- **Ollama** (fully local, no API key, slower) — needs Ollama running locally- **LiteLLM** (100+ providers) — needs LiteLLM config-Then ask them to set the required environment variable. Show the exact export command:+If they have not set that key yet, ask them to set it in their own shell. Show the exact export command:```bashexport ANTHROPIC_API_KEY="sk-ant-..."```diff --git a/plugins/claude-code/commands/reindex.md b/plugins/claude-code/commands/reindex.mdindex 234daab4a..be7c3fb72 100644--- a/plugins/claude-code/commands/reindex.md+++ b/plugins/claude-code/commands/reindex.md@@ -1,6 +1,6 @@---description: Rebuild the Repowise vector store by re-embedding all wiki pages. No LLM calls — only embedding API calls.-allowed-tools: Bash, Read, AskFollowupQuestion+allowed-tools: Bash(repowise reindex:*), Read, AskUserQuestion---# Repowise Reindexdiff --git a/plugins/claude-code/commands/risk.md b/plugins/claude-code/commands/risk.mdindex 6f09c919c..94a4c098a 100644--- a/plugins/claude-code/commands/risk.md+++ b/plugins/claude-code/commands/risk.md@@ -1,6 +1,6 @@---description: Rank a live change for review using a repo-relative percentile and an auditable supporting diff-shape score.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise risk:*), Read---# Repowise Riskdiff --git a/plugins/claude-code/commands/search.md b/plugins/claude-code/commands/search.mdindex 97e5ddef6..8a5cdfd7d 100644--- a/plugins/claude-code/commands/search.md+++ b/plugins/claude-code/commands/search.md@@ -1,6 +1,6 @@---description: Search the Repowise wiki using natural language, full-text, or symbol search.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise search:*), Read---# Repowise Searchdiff --git a/plugins/claude-code/commands/security.md b/plugins/claude-code/commands/security.mdindex a4ff00be0..da1a91c97 100644--- a/plugins/claude-code/commands/security.md+++ b/plugins/claude-code/commands/security.md@@ -1,6 +1,6 @@---description: Scan for security signals — working-tree scanning already runs during init/update; use --history to walk full git history for leaked secrets.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise security scan:*), Read---# Repowise Securitydiff --git a/plugins/claude-code/commands/status.md b/plugins/claude-code/commands/status.mdindex 7544d7464..2c039ac25 100644--- a/plugins/claude-code/commands/status.md+++ b/plugins/claude-code/commands/status.md@@ -1,6 +1,6 @@---description: Check the health of your Repowise index — sync state, page counts, provider, and token usage.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise status:*), Read---# Repowise Statusdiff --git a/plugins/claude-code/commands/symbol.md b/plugins/claude-code/commands/symbol.mdindex a722edfc4..0904a9289 100644--- a/plugins/claude-code/commands/symbol.md+++ b/plugins/claude-code/commands/symbol.md@@ -1,6 +1,6 @@---description: Read one symbol's body with live-verified line bounds (path::Name, live range, or distill omission ref).-allowed-tools: Bash, Read+allowed-tools: Bash(repowise symbol:*), Read---# Repowise Symboldiff --git a/plugins/claude-code/commands/update.md b/plugins/claude-code/commands/update.mdindex 249114805..079a3be7c 100644--- a/plugins/claude-code/commands/update.md+++ b/plugins/claude-code/commands/update.md@@ -1,6 +1,6 @@---description: Trigger an incremental Repowise update to sync documentation with recent code changes.-allowed-tools: Bash, Read+allowed-tools: Bash(repowise update:*), Read---# Repowise Updatediff --git a/plugins/claude-code/commands/why.md b/plugins/claude-code/commands/why.mdindex 7415ef430..7c7958e19 100644--- a/plugins/claude-code/commands/why.md+++ b/plugins/claude-code/commands/why.md@@ -1,6 +1,6 @@---description: Why the code is shaped this way — decisions, rationale, and git archaeology (question, path, or decision-health dashboard).-allowed-tools: Bash, Read+allowed-tools: Bash(repowise why:*), Read---# Repowise Whydiff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.jsindex 1675cb01d..86b8c0627 100644--- a/plugins/claude-code/hooks/lens/lens.js+++ b/plugins/claude-code/hooks/lens/lens.js@@ -1,21 +1,16 @@// Generated by packages/claude-mod (npm run build:mod). Do not edit.-var __defProp = Object.defineProperty;-var __name = (target, value) => __defProp(target, "name", { value, configurable: true });-// ../api-client/src/client.tsvar config = { baseUrl: "" };function configureApiClient(next) {config = next;BASE_URL = next.baseUrl;}-__name(configureApiClient, "configureApiClient");var BASE_URL = "";function resolveToken() {const { token } = config;if (typeof token === "function") return token();return token ?? null;}-__name(resolveToken, "resolveToken");function requestHeaders(extra) {const headers = {"Content-Type": "application/json",@@ -27,7 +22,6 @@ function requestHeaders(extra) {}return headers;}-__name(requestHeaders, "requestHeaders");var ApiClientError = class extends Error {constructor(status, detail) {super(`API error ${status}: ${detail}`);@@ -37,9 +31,6 @@ var ApiClientError = class extends Error {}status;detail;- static {- __name(this, "ApiClientError");- }};function stringifyDetail(detail) {if (typeof detail === "string") return detail;@@ -51,7 +42,6 @@ function stringifyDetail(detail) {}return null;}-__name(stringifyDetail, "stringifyDetail");async function handleResponse(res) {if (!res.ok) {let detail = res.statusText;@@ -65,11 +55,9 @@ async function handleResponse(res) {if (res.status === 204) return void 0;return res.json();}-__name(handleResponse, "handleResponse");function doFetch(url, init) {return (config.fetch ?? fetch)(url, init);}-__name(doFetch, "doFetch");function headersToRecord(headers) {const out = {};if (!headers) return out;@@ -84,9 +72,8 @@ function headersToRecord(headers) {}return out;}-__name(headersToRecord, "headersToRecord");function createAdapterFetch(minimal) {- const adapted = /* @__PURE__ */ __name(async (input2, init) => {+ const adapted = async (input2, init) => {const url = typeof input2 === "string" ? input2 : "href" in input2 ? input2.href : input2.url;const body = init?.body;if (body != null && typeof body !== "string") {@@ -101,13 +88,12 @@ function createAdapterFetch(minimal) {ok: res.ok,status: res.status,statusText: `HTTP ${res.status}`,- json: /* @__PURE__ */ __name(async () => JSON.parse(res.text), "json"),- text: /* @__PURE__ */ __name(async () => res.text, "text")+ json: async () => JSON.parse(res.text),+ text: async () => res.text};- }, "adapted");+ };return adapted;}-__name(createAdapterFetch, "createAdapterFetch");async function apiGet(path, params, fetchOptions) {const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");if (params) {@@ -124,7 +110,6 @@ async function apiGet(path, params, fetchOptions) {});return handleResponse(res);}-__name(apiGet, "apiGet");async function apiPost(path, body, fetchOptions, params) {const url = new URL(`${BASE_URL}${path}`, typeof window !== "undefined" ? window.location.href : "http://localhost");if (params) {@@ -142,7 +127,6 @@ async function apiPost(path, body, fetchOptions, params) {});return handleResponse(res);}-__name(apiPost, "apiPost");// ../api-client/src/costs.tsasync function getSavings(repoId, opts = {}) {@@ -150,19 +134,16 @@ async function getSavings(repoId, opts = {}) {days: opts.days});}-__name(getSavings, "getSavings");// ../api-client/src/health.tsasync function getHealth() {return apiGet("/health");}-__name(getHealth, "getHealth");// ../api-client/src/repos.tsasync function listRepos() {return apiGet("/api/repos");}-__name(listRepos, "listRepos");// ../types/src/repos.tsfunction normalizeRepoPath(p, isWindows) {@@ -170,7 +151,6 @@ function normalizeRepoPath(p, isWindows) {const trimmed = slashed.replace(/\/+$/, "");return isWindows ? trimmed.toLowerCase() : trimmed;}-__name(normalizeRepoPath, "normalizeRepoPath");// ../types/src/serve-lock.tsfunction isServeLock(value) {@@ -178,7 +158,6 @@ function isServeLock(value) {const v = value;return typeof v.pid === "number" && typeof v.host === "string" && typeof v.port === "number" && typeof v.url === "string" && (typeof v.ui_port === "number" || v.ui_port === null) && typeof v.server_version === "string" && typeof v.started_at === "string";}-__name(isServeLock, "isServeLock");var LOOPBACK_V4 = /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/;function isLoopbackUrl(url) {try {@@ -189,17 +168,12 @@ function isLoopbackUrl(url) {return false;}}-__name(isLoopbackUrl, "isLoopbackUrl");// src/data/transport.tsfunction connectApiClient(host, baseUrl) {configureApiClient({ baseUrl, fetch: createAdapterFetch(host.http) });}-__name(connectApiClient, "connectApiClient");var TimeoutError = class extends Error {- static {- __name(this, "TimeoutError");- }constructor(label, ms) {super(`${label} timed out after ${ms} ms`);this.name = "TimeoutError";@@ -212,7 +186,6 @@ function withTimeout(work, ms, label) {});return Promise.race([work, timeout]).finally(() => clearTimeout(timer));}-__name(withTimeout, "withTimeout");// src/data/discovery.tsvar HEALTH_TIMEOUT_MS = 800;@@ -224,11 +197,9 @@ var SHA = /^[0-9a-f]{7,64}$/i;function isWindowsPath(p) {return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");}-__name(isWindowsPath, "isWindowsPath");function join(dir, rel2) {return `${dir.replace(/[\\/]+$/, "")}/${rel2}`;}-__name(join, "join");function parentDir(p) {const trimmed = p.replace(/[\\/]+$/, "");const cut = Math.max(trimmed.lastIndexOf("/"), trimmed.lastIndexOf("\\"));@@ -236,7 +207,6 @@ function parentDir(p) {if (cut === 0) return trimmed === "" ? null : "/";return trimmed.slice(0, cut);}-__name(parentDir, "parentDir");async function findIndexedRoot(host, cwd2) {let dir = cwd2;for (let i = 0; dir !== null && i < MAX_WALK; i++) {@@ -245,7 +215,6 @@ async function findIndexedRoot(host, cwd2) {}return null;}-__name(findIndexedRoot, "findIndexedRoot");async function readJson(host, path) {try {return JSON.parse(await host.fs.read(path));@@ -253,12 +222,10 @@ async function readJson(host, path) {return null;}}-__name(readJson, "readJson");async function readServeLock(host, repoRoot) {const parsed = await readJson(host, join(repoRoot, ".repowise/serve.lock.json"));return isServeLock(parsed) ? parsed : null;}-__name(readServeLock, "readServeLock");async function isPidAlive(host, pid, cwd2) {try {if (isWindowsPath(cwd2)) {@@ -271,7 +238,6 @@ async function isPidAlive(host, pid, cwd2) {return null;}}-__name(isPidAlive, "isPidAlive");async function probeServer(host, lock, repoRoot) {connectApiClient(host, lock.url);try {@@ -290,7 +256,6 @@ async function probeServer(host, lock, repoRoot) {return { kind: "down" };}}-__name(probeServer, "probeServer");async function mcpReachable(host) {try {return await withTimeout(host.mcp.connect(), CONNECT_TIMEOUT_MS, "mcp connect");@@ -298,20 +263,17 @@ async function mcpReachable(host) {return false;}}-__name(mcpReachable, "mcpReachable");async function unindexedMode(host, cwd2) {const inWorkTree = (await git(host, cwd2, ["rev-parse", "--is-inside-work-tree"]))?.trim() === "true";if (!inWorkTree) return "no-repo";return await mcpReachable(host) ? "no-index" : "no-cli";}-__name(unindexedMode, "unindexedMode");async function serverState(host, repoRoot) {const lock = await readServeLock(host, repoRoot);if (!lock || !isLoopbackUrl(lock.url)) return { kind: "down" };if (await isPidAlive(host, lock.pid, repoRoot) === false) return { kind: "down" };return probeServer(host, lock, repoRoot);}-__name(serverState, "serverState");async function discover(host) {const cwd2 = await host.session.cwd();const repoRoot = await findIndexedRoot(host, cwd2);@@ -322,7 +284,6 @@ async function discover(host) {const liteReason = server.kind === "down" ? "no-server" : server.kind;return { mode: "lite", liteReason, repoRoot };}-__name(discover, "discover");async function git(host, cwd2, args) {try {const out = await withTimeout(host.process.run(["git", ...args], cwd2), GIT_TIMEOUT_MS, "git");@@ -331,13 +292,11 @@ async function git(host, cwd2, args) {return null;}}-__name(git, "git");async function updateRunning(host, repoRoot) {const lock = await readJson(host, join(repoRoot, ".repowise/.update.lock"));const pid = lock?.pid;return typeof pid === "number" && await isPidAlive(host, pid, repoRoot) === true;}-__name(updateRunning, "updateRunning");async function readFreshness(host, repoRoot) {const state2 = await readJson(host, join(repoRoot, ".repowise/state.json"));const indexed = state2?.last_sync_commit;@@ -349,11 +308,8 @@ async function readFreshness(host, repoRoot) {const changedFiles = diff === null ? null : diff.split("\n").filter((l) => l.trim() !== "").length;return { changedFiles };}-__name(readFreshness, "readFreshness");// src/data/mcp.ts-var PLUGIN_NAME = "repowise";-var LENS_TOOLS = ["get_context", "get_change_risk", "get_why", "get_answer"];var PLUGIN_SERVER_FORMS = ["plugin:repowise:repowise", "plugin_repowise_repowise"];var DEFAULT_TIMEOUT_MS = 1e4;var resolvedServer = null;@@ -362,7 +318,6 @@ function resetMcp() {resolvedServer = null;resolving = null;}-__name(resetMcp, "resetMcp");function warmMcp(host) {if (resolvedServer !== null || resolving !== null) return;const asked = host.mcp.server().then((name) => {@@ -372,27 +327,12 @@ function warmMcp(host) {});resolving = asked;}-__name(warmMcp, "warmMcp");async function mcpReady(host, timeoutMs = DEFAULT_TIMEOUT_MS) {warmMcp(host);const pending = resolving;if (resolvedServer === null && pending !== null) await withTimeout(pending, timeoutMs, "MCP connect").catch(() => void 0);return resolvedServer !== null;}-__name(mcpReady, "mcpReady");-function toolName(serverForm, tool) {- return `mcp__${serverForm.replace(/[^A-Za-z0-9_-]/g, "_")}__${tool}`;-}-__name(toolName, "toolName");-var OWN_TOOL_NAMES = new Set(- PLUGIN_SERVER_FORMS.flatMap((form) => LENS_TOOLS.map((tool) => toolName(form, tool)))-);-function isOwnLensCall(e, originPlugin) {- if (originPlugin !== PLUGIN_NAME) return false;- if (typeof e.tool_use_id !== "string" || !e.tool_use_id.startsWith("toolu_plugin_")) return false;- return OWN_TOOL_NAMES.has(e.tool);-}-__name(isOwnLensCall, "isOwnLensCall");function parse(result, tool) {const text2 = result.content[0]?.text;if (result.isError) throw new Error(`${tool} failed: ${String(text2).slice(0, 200)}`);@@ -400,7 +340,6 @@ function parse(result, tool) {const parsed = JSON.parse(text2);return parsed !== null && typeof parsed === "object" && "result" in parsed ? parsed.result : parsed;}-__name(parse, "parse");function callTool(host, tool, args, opts = {}) {if (resolvedServer === null) {warmMcp(host);@@ -409,13 +348,11 @@ function callTool(host, tool, args, opts = {}) {const call = host.mcp.call(resolvedServer, tool, args).then((r) => parse(r, tool));return withTimeout(call, opts.timeoutMs ?? DEFAULT_TIMEOUT_MS, tool);}-__name(callTool, "callTool");function recentOwner(o) {const name = o?.recent_owner;const share = o?.recent_owner_pct;return typeof name === "string" && name !== "" && typeof share === "number" ? { name, share } : null;}-__name(recentOwner, "recentOwner");async function fetchFileContext(host, path) {const result = await callTool(host, "get_context", {targets: [path],@@ -432,7 +369,6 @@ async function fetchFileContext(host, path) {recentOwner: recentOwner(target.ownership)};}-__name(fetchFileContext, "fetchFileContext");// ../ui/src/lib/format.tsfunction parseDate(date) {@@ -442,12 +378,10 @@ function parseDate(date) {}return new Date(date);}-__name(parseDate, "parseDate");var NUMBER_FORMAT = new Intl.NumberFormat("en-US");function formatNumber(n) {return NUMBER_FORMAT.format(n);}-__name(formatNumber, "formatNumber");function formatRelativeTime(date) {const d = parseDate(date);const now = Date.now();@@ -467,31 +401,26 @@ function formatRelativeTime(date) {if (months < 12) return `${months}mo ago`;return `${Math.floor(months / 12)}y ago`;}-__name(formatRelativeTime, "formatRelativeTime");function formatRelativeTimeOrNull(iso, fallback = "—") {if (!iso) return fallback;const d = parseDate(iso);if (Number.isNaN(d.getTime()) || d.getTime() > Date.now()) return fallback;return formatRelativeTime(d);}-__name(formatRelativeTimeOrNull, "formatRelativeTimeOrNull");// src/format.tsfunction countOf(n, singular, plural) {return `${formatNumber(n)} ${n === 1 ? singular : plural}`;}-__name(countOf, "countOf");function fit(text2, columns) {if (columns <= 0) return "";if (text2.length <= columns) return text2;return `${text2.slice(0, columns - 1).trimEnd()}…`;}-__name(fit, "fit");var NOT_ONE_CELL = /[\u0000-\u001f\u007f-\u009f\ud800-\udfffᄀ-ᅟ⺀-가-힣豈-︰-﹏-⦆¢-₩]/;function cellSafe(text2) {return Array.from(text2, (ch) => ch.length === 1 && !NOT_ONE_CELL.test(ch) ? ch : "?").join("");}-__name(cellSafe, "cellSafe");// ../../node_modules/d3-hierarchy/src/hierarchy/count.jsfunction count(node) {@@ -500,11 +429,9 @@ function count(node) {else while (--i >= 0) sum += children[i].value;node.value = sum;}-__name(count, "count");function count_default() {return this.eachAfter(count);}-__name(count_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/each.jsfunction each_default(callback, that) {@@ -514,7 +441,6 @@ function each_default(callback, that) {}return this;}-__name(each_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.jsfunction eachBefore_default(callback, that) {@@ -529,7 +455,6 @@ function eachBefore_default(callback, that) {}return this;}-__name(eachBefore_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.jsfunction eachAfter_default(callback, that) {@@ -547,7 +472,6 @@ function eachAfter_default(callback, that) {}return this;}-__name(eachAfter_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/find.jsfunction find_default(callback, that) {@@ -558,7 +482,6 @@ function find_default(callback, that) {}}}-__name(find_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/sum.jsfunction sum_default(value) {@@ -568,7 +491,6 @@ function sum_default(value) {node.value = sum;});}-__name(sum_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/sort.jsfunction sort_default(compare) {@@ -578,7 +500,6 @@ function sort_default(compare) {}});}-__name(sort_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/path.jsfunction path_default(end) {@@ -594,7 +515,6 @@ function path_default(end) {}return nodes;}-__name(path_default, "default");function leastCommonAncestor(a, b) {if (a === b) return a;var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;@@ -607,7 +527,6 @@ function leastCommonAncestor(a, b) {}return c;}-__name(leastCommonAncestor, "leastCommonAncestor");// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.jsfunction ancestors_default() {@@ -617,13 +536,11 @@ function ancestors_default() {}return nodes;}-__name(ancestors_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.jsfunction descendants_default() {return Array.from(this);}-__name(descendants_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.jsfunction leaves_default() {@@ -635,7 +552,6 @@ function leaves_default() {});return leaves;}-__name(leaves_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/links.jsfunction links_default() {@@ -647,7 +563,6 @@ function links_default() {});return links;}-__name(links_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.jsfunction* iterator_default() {@@ -664,7 +579,6 @@ function* iterator_default() {}} while (next.length);}-__name(iterator_default, "default");// ../../node_modules/d3-hierarchy/src/hierarchy/index.jsfunction hierarchy(data, children) {@@ -687,37 +601,30 @@ function hierarchy(data, children) {}return root.eachBefore(computeHeight);}-__name(hierarchy, "hierarchy");function node_copy() {return hierarchy(this).eachBefore(copyData);}-__name(node_copy, "node_copy");function objectChildren(d) {return d.children;}-__name(objectChildren, "objectChildren");function mapChildren(d) {return Array.isArray(d) ? d[1] : null;}-__name(mapChildren, "mapChildren");function copyData(node) {if (node.data.value !== void 0) node.value = node.data.value;node.data = node.data.data;}-__name(copyData, "copyData");function computeHeight(node) {var height = 0;donode.height = height;while ((node = node.parent) && node.height < ++height);}-__name(computeHeight, "computeHeight");function Node(data) {this.data = data;this.depth = this.height = 0;this.parent = null;}-__name(Node, "Node");Node.prototype = hierarchy.prototype = {constructor: Node,count: count_default,@@ -741,19 +648,16 @@ function required(f) {if (typeof f !== "function") throw new Error();return f;}-__name(required, "required");// ../../node_modules/d3-hierarchy/src/constant.jsfunction constantZero() {return 0;}-__name(constantZero, "constantZero");function constant_default(x) {return function() {return x;};}-__name(constant_default, "default");// ../../node_modules/d3-hierarchy/src/treemap/round.jsfunction round_default(node) {@@ -762,7 +666,6 @@ function round_default(node) {node.x1 = Math.round(node.x1);node.y1 = Math.round(node.y1);}-__name(round_default, "default");// ../../node_modules/d3-hierarchy/src/treemap/dice.jsfunction dice_default(parent, x0, y0, x1, y1) {@@ -772,7 +675,6 @@ function dice_default(parent, x0, y0, x1, y1) {node.x0 = x0, node.x1 = x0 += node.value * k;}}-__name(dice_default, "default");// ../../node_modules/d3-hierarchy/src/treemap/slice.jsfunction slice_default(parent, x0, y0, x1, y1) {@@ -782,7 +684,6 @@ function slice_default(parent, x0, y0, x1, y1) {node.y0 = y0, node.y1 = y0 += node.value * k;}}-__name(slice_default, "default");// ../../node_modules/d3-hierarchy/src/treemap/squarify.jsvar phi = (1 + Math.sqrt(5)) / 2;@@ -816,17 +717,15 @@ function squarifyRatio(ratio, parent, x0, y0, x1, y1) {}return rows;}-__name(squarifyRatio, "squarifyRatio");-var squarify_default = (/* @__PURE__ */ __name((function custom(ratio) {+var squarify_default = (function custom(ratio) {function squarify(parent, x0, y0, x1, y1) {squarifyRatio(ratio, parent, x0, y0, x1, y1);}- __name(squarify, "squarify");squarify.ratio = function(x) {return custom((x = +x) > 1 ? x : 1);};return squarify;-}), "custom"))(phi);+})(phi);// ../../node_modules/d3-hierarchy/src/treemap/index.jsfunction treemap_default() {@@ -840,7 +739,6 @@ function treemap_default() {if (round) root.eachBefore(round_default);return root;}- __name(treemap, "treemap");function positionNode(node) {var p = paddingStack[node.depth], x0 = node.x0 + p, y0 = node.y0 + p, x1 = node.x1 - p, y1 = node.y1 - p;if (x1 < x0) x0 = x1 = (x0 + x1) / 2;@@ -860,7 +758,6 @@ function treemap_default() {tile(node, x0, y0, x1, y1);}}- __name(positionNode, "positionNode");treemap.round = function(x) {return arguments.length ? (round = !!x, treemap) : round;};@@ -893,7 +790,6 @@ function treemap_default() {};return treemap;}-__name(treemap_default, "default");// ../types/src/health.tsvar EXCELLENT_MIN = 8.5;@@ -921,7 +817,6 @@ function bandForScore(score) {if (score >= NEEDS_WORK_MIN) return "needs_work";return "at_risk";}-__name(bandForScore, "bandForScore");// ../ui/src/brand.tsvar BRAND = {@@ -989,7 +884,7 @@ var DARK_CANVAS_BAND = {var UPPER_HALF = 9600;var LOWER_HALF = 9604;var SPACE = 32;-var hex = /* @__PURE__ */ __name((s) => parseInt(s.slice(1), 16), "hex");+var hex = (s) => parseInt(s.slice(1), 16);var GROUND = hex(DARK.bgRoot);var TERMINAL_DEFAULT = 16777216;var LABEL_FG = hex(DARK.textSecondary);@@ -1028,28 +923,24 @@ var EDGE_MIN = 3;function colorForScore(score) {return score === null ? NEUTRAL : hex(DARK_CANVAS_BAND[bandForScore(score)]);}-__name(colorForScore, "colorForScore");function mix(a, b, amount) {- const ch = /* @__PURE__ */ __name((shift) => {+ const ch = (shift) => {const x = a >> shift & 255;const y = b >> shift & 255;return Math.round(x + (y - x) * amount) << shift;- }, "ch");+ };return (ch(16) | ch(8) | ch(0)) >>> 0;}-__name(mix, "mix");-var byName = /* @__PURE__ */ __name((a, b) => a < b ? -1 : a > b ? 1 : 0, "byName");+var byName = (a, b) => a < b ? -1 : a > b ? 1 : 0;function dirsOf(path) {return path.split("/").slice(0, -1);}-__name(dirsOf, "dirsOf");function keyOf(path, split) {const dirs = dirsOf(path);let depth = Math.min(1, dirs.length);while (depth < dirs.length && split.has(dirs.slice(0, depth).join("/"))) depth++;return dirs.slice(0, depth).join("/");}-__name(keyOf, "keyOf");function nextSplit(files, split, limit) {const weight = /* @__PURE__ */ new Map();for (const f of files) {@@ -1064,7 +955,6 @@ function nextSplit(files, split, limit) {}return null;}-__name(nextSplit, "nextSplit");function groupKeys(files) {const split = /* @__PURE__ */ new Set();const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;@@ -1075,8 +965,7 @@ function groupKeys(files) {}return files.map((f) => keyOf(f.file_path, split));}-__name(groupKeys, "groupKeys");-var folderDatum = /* @__PURE__ */ __name((name) => ({ name, children: [], kids: /* @__PURE__ */ new Map() }), "folderDatum");+var folderDatum = (name) => ({ name, children: [], kids: /* @__PURE__ */ new Map() });function insertFile(group, key2, file) {const rel2 = key2 === "" ? file.file_path : file.file_path.slice(key2.length + 1);let node = group;@@ -1091,7 +980,6 @@ function insertFile(group, key2, file) {}node.children?.push({ name: file.file_path, file });}-__name(insertFile, "insertFile");function treemapOf(files, width2, height) {const keys = groupKeys(files);const groups = /* @__PURE__ */ new Map();@@ -1105,19 +993,16 @@ function treemapOf(files, width2, height) {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));return treemap_default().tile(squarify_default).size([width2, height])(root);}-__name(treemapOf, "treemapOf");-var rectOf = /* @__PURE__ */ __name((n) => ({ x: n.x0, y: n.y0, w: n.x1 - n.x0, h: n.y1 - n.y0 }), "rectOf");+var rectOf = (n) => ({ x: n.x0, y: n.y0, w: n.x1 - n.x0, h: n.y1 - n.y0 });function pixelSpan(from, to) {return [Math.ceil(from - 0.5), Math.ceil(to - 0.5)];}-__name(pixelSpan, "pixelSpan");function groupInterior(rect, width2, height) {const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);const gutter = x1 - x0 >= GUTTER_MIN && y1 - y0 >= GUTTER_MIN;return { x0, y0, x1: gutter && x1 < width2 ? x1 - 1 : x1, y1: gutter && y1 < height ? y1 - 1 : y1 };}-__name(groupInterior, "groupInterior");function placeFile(leaf, group, inner) {const file = leaf.data.file;const rect = rectOf(leaf);@@ -1135,22 +1020,18 @@ function placeFile(leaf, group, inner) {py1: Math.min(y1, inner.y1)};}-__name(placeFile, "placeFile");function tileFor(f, i, style) {const pal = MAP_PALETTES[style.theme];if (style.health) return colorForScore(f.score);return i % 2 === 0 ? pal.tileA : pal.tileB;}-__name(tileFor, "tileFor");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()) {@@ -1163,15 +1044,13 @@ function folderTiles(group, inner) {}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");+var within = (f, x, y) => x >= f.x0 && x < f.x1 && y >= f.y0 && y < f.y1;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;@@ -1181,14 +1060,12 @@ function paintFile(base, width2, f, fill) {if (edgeX >= 0) base[y * width2 + edgeX] = edge;}}-__name(paintFile, "paintFile");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;}-__name(labelText, "labelText");var LABEL_MIN_COLS = 12;var LABEL_MIN_ROWS = 3;var MAX_LABELS = 8;@@ -1203,18 +1080,15 @@ function labelFor(g, columns, rows, root) {const text2 = labelText(key2, width2);return text2 === null ? null : { row: row2, col, text: text2 };}-__name(labelFor, "labelFor");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 = [];@@ -1227,24 +1101,21 @@ function fileLabels(files, rows, taken) {}return out;}-__name(fileLabels, "fileLabels");function paintBase(map2, style, dense) {const { width: width2, height } = map2;const base = new Uint32Array(width2 * height).fill(GROUND);const pal = MAP_PALETTES[style.theme];- const tone = /* @__PURE__ */ __name((t) => t === 0 ? pal.tileB : pal.tileA, "tone");+ const tone = (t) => t === 0 ? pal.tileB : pal.tileA;if (!style.health) map2.groups.forEach((g, i) => paintBox(base, width2, groupInterior(g.rect, width2, height), tone(i % 2)));if (!style.health) for (const f of map2.folders) paintBox(base, width2, f, tone(1 - f.tone));if (dense && !style.health) return base;for (const i of map2.drawn) paintFile(base, width2, map2.files[i], tileFor(map2.files[i], i, style));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;@@ -1275,13 +1146,11 @@ function layoutMap(feed, canvas) {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) {if (top === GROUND && bottom === GROUND) return [SPACE, TERMINAL_DEFAULT, TERMINAL_DEFAULT];if (top === GROUND) return [LOWER_HALF, bottom, TERMINAL_DEFAULT];return [UPPER_HALF, top, bottom === GROUND ? TERMINAL_DEFAULT : bottom];}-__name(halfCell, "halfCell");function labelCovered(label, marked, width2) {if (marked === void 0) return false;for (let c = label.col; c < label.col + label.text.length; c++) {@@ -1289,8 +1158,7 @@ function labelCovered(label, marked, width2) {}return false;}-__name(labelCovered, "labelCovered");-var cellGround = /* @__PURE__ */ __name((pixel) => pixel === void 0 || pixel === GROUND ? TERMINAL_DEFAULT : pixel, "cellGround");+var cellGround = (pixel) => pixel === void 0 || pixel === GROUND ? TERMINAL_DEFAULT : pixel;function writeText(words, layout, label, colors) {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++) {@@ -1298,7 +1166,6 @@ function writeText(words, layout, label, colors) {words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);}}-__name(writeText, "writeText");function writeFolderLabels(words, layout, pixels, marked) {const fg = layout.style.health ? LABEL_FG : MAP_PALETTES[layout.style.theme].folder;for (const label of layout.labels) {@@ -1306,7 +1173,6 @@ function writeFolderLabels(words, layout, pixels, marked) {writeText(words, layout, label, (col) => [fg, cellGround(pixels[2 * label.row * layout.width + col])]);}}-__name(writeFolderLabels, "writeFolderLabels");function encodeCells(layout, pixels, marked, names2 = []) {const { columns, rows, width: width2 } = layout;const words = new Uint32Array(columns * rows * 3);@@ -1319,7 +1185,6 @@ function encodeCells(layout, pixels, marked, names2 = []) {for (const name of names2) writeText(words, layout, name, () => [name.color, TERMINAL_DEFAULT]);return new Uint8Array(words.buffer).toBase64();}-__name(encodeCells, "encodeCells");// src/views/overlay.tsvar NO_LIT = { hits: [], reads: [], named: [], importers: [], edits: [], edit: null, current: null };@@ -1328,7 +1193,7 @@ var FLASH_MS = 600;var RIPPLE_MS = 1200;var NAME_MAX = 18;var FLASH_LIFT = 0.6;-var keyOf2 = /* @__PURE__ */ __name((layout, path) => layout.caseInsensitive ? path.toLowerCase() : path, "keyOf");+var keyOf2 = (layout, path) => layout.caseInsensitive ? path.toLowerCase() : path;function indices(layout, paths, lowered = false) {const out = [];for (const p of paths) {@@ -1337,30 +1202,26 @@ function indices(layout, paths, lowered = false) {}return out;}-__name(indices, "indices");-var one = /* @__PURE__ */ __name((layout, path) => path === null ? null : layout.index.get(keyOf2(layout, path)) ?? null, "one");+var one = (layout, path) => path === null ? null : layout.index.get(keyOf2(layout, path)) ?? null;function notOnMap(layout, lit) {const all = new Set([...lit.hits, ...lit.reads, ...lit.importers, ...lit.edit === null ? [] : [lit.edit]].map((p) => keyOf2(layout, p)));return [...all].filter((p) => !layout.index.has(p)).length;}-__name(notOnMap, "notOnMap");function litPixels(layout, f) {if (f.px1 > f.px0 && f.py1 > f.py0) return { x0: f.px0, y0: f.py0, x1: f.px1, y1: f.py1 };const x = Math.min(layout.width - 1, Math.max(0, Math.floor(f.rect.x + f.rect.w / 2)));const row2 = Math.min(layout.rows - 1, Math.max(0, Math.floor((f.rect.y + f.rect.h / 2) / 2)));return { x0: x, y0: row2 * 2, x1: x + 1, y1: row2 * 2 + 2 };}-__name(litPixels, "litPixels");var ROW_TRIES = [0, 1, -1, 2, -2];-var rowIn = /* @__PURE__ */ __name((layout, row2) => row2 >= 0 && row2 < layout.rows, "rowIn");-var spanIn = /* @__PURE__ */ __name((layout, col, len) => col >= 0 && col + len <= layout.columns, "spanIn");-var inside = /* @__PURE__ */ __name((layout, row2, col, len) => rowIn(layout, row2) && spanIn(layout, col, len), "inside");+var rowIn = (layout, row2) => row2 >= 0 && row2 < layout.rows;+var spanIn = (layout, col, len) => col >= 0 && col + len <= layout.columns;+var inside = (layout, row2, col, len) => rowIn(layout, row2) && spanIn(layout, col, len);function freeSpan(taken, layout, at, len) {if (!inside(layout, at.row, at.col, len)) return false;for (let c = at.col - 1; c <= at.col + len; c++) if (taken.has(at.row * layout.columns + c)) return false;return true;}-__name(freeSpan, "freeSpan");function placeName(layout, taken, f, color2) {const text2 = fit(cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1)), NAME_MAX);const box2 = litPixels(layout, f);@@ -1371,7 +1232,6 @@ function placeName(layout, taken, f, color2) {for (let c = at.col; c < at.col + text2.length; c++) taken.add(at.row * layout.columns + c);return { ...at, text: text2, color: color2 };}-__name(placeName, "placeName");function namesFor(layout, o) {const pal = MAP_PALETTES[layout.style.theme];const order = [...new Set([o.edit, o.current, ...[...o.reads].reverse()].filter((i) => i !== null))];@@ -1379,7 +1239,6 @@ function namesFor(layout, o) {const hot = /* @__PURE__ */ new Set([o.edit, o.current]);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, selected = null) {const o = {hits: indices(layout, lit.hits),@@ -1392,24 +1251,20 @@ function resolveLit(layout, lit, selected = null) {};return { ...o, names: namesFor(layout, o), selected: one(layout, selected) };}-__name(resolveLit, "resolveLit");function center(layout, f) {const b = litPixels(layout, f);return [Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2)];}-__name(center, "center");function distance(layout, a, b) {const [ax, ay] = center(layout, a);const [bx, by] = center(layout, b);return Math.hypot(ax - bx, ay - by);}-__name(distance, "distance");function rippleRadius(layout, overlay) {const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];if (!origin || overlay.importers.length === 0) return 0;return Math.max(...overlay.importers.map((i) => distance(layout, origin, layout.files[i]))) + 3;}-__name(rippleRadius, "rippleRadius");function fillFile(p, f, color2) {const { width: width2 } = p.layout;const b = litPixels(p.layout, f);@@ -1418,11 +1273,9 @@ function fillFile(p, f, color2) {p.marked.fill(1, y * width2 + b.x0, y * width2 + b.x1);}}-__name(fillFile, "fillFile");function fillAll(p, files, color2) {for (const i of files) fillFile(p, p.layout.files[i], color2);}-__name(fillAll, "fillAll");function paintRing(p, origin, reach, color2) {const [ox, oy] = center(p.layout, origin);const { width: width2, height } = p.layout;@@ -1433,39 +1286,32 @@ function paintRing(p, origin, reach, color2) {}}}-__name(paintRing, "paintRing");function hitColor(pal, anim) {return anim?.kind === "flash" ? mix(pal.hit, pal.read, FLASH_LIFT * (1 - anim.t)) : pal.hit;}-__name(hitColor, "hitColor");function reached(layout, overlay, reach) {const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];if (origin === void 0 || reach === Infinity) return overlay.importers;return overlay.importers.filter((i) => distance(layout, origin, layout.files[i]) <= reach);}-__name(reached, "reached");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");+var inRange = (v, n) => v >= 0 && v < n;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];@@ -1481,18 +1327,13 @@ function framePixels(layout, overlay, anim) {if (selected !== void 0) paintSelection(p, selected, pal.ring);return { pixels: p.px, marked: p.marked };}-__name(framePixels, "framePixels");function frameCells(layout, overlay, anim) {const { pixels, marked } = framePixels(layout, overlay, anim);return encodeCells(layout, pixels, marked, overlay.names);}-__name(frameCells, "frameCells");// src/animator.tsvar Animator = class {- static {- __name(this, "Animator");- }anim = null;timer;blitting = false;@@ -1566,24 +1407,22 @@ var PARSE_CHARS = 64 * 1024;var EXCERPT_CHARS = 2 * 1024;var MAX_PATHS = 200;var MAX_DEPTH = 6;-var isRec = /* @__PURE__ */ __name((v) => typeof v === "object" && v !== null && !Array.isArray(v), "isRec");-var rec = /* @__PURE__ */ __name((v) => isRec(v) ? v : {}, "rec");-var str = /* @__PURE__ */ __name((v) => typeof v === "string" && v !== "" ? v : null, "str");-var num = /* @__PURE__ */ __name((v) => typeof v === "number" && Number.isFinite(v) ? v : null, "num");-var bool = /* @__PURE__ */ __name((v) => typeof v === "boolean" ? v : null, "bool");-var count2 = /* @__PURE__ */ __name((v) => Array.isArray(v) ? v.length : num(v), "count");+var isRec = (v) => typeof v === "object" && v !== null && !Array.isArray(v);+var rec = (v) => isRec(v) ? v : {};+var str = (v) => typeof v === "string" && v !== "" ? v : null;+var num = (v) => typeof v === "number" && Number.isFinite(v) ? v : null;+var bool = (v) => typeof v === "boolean" ? v : null;+var count2 = (v) => Array.isArray(v) ? v.length : num(v);function fact(what, n, of = null) {if (n === null) return [];return of !== null && of > n ? [{ what, n, of }] : [{ what, n }];}-__name(fact, "fact");function sumOver(targets, read) {const found = targets.map(read).filter((n) => n !== null);return found.length === 0 ? null : found.reduce((a, b) => a + b, 0);}-__name(sumOver, "sumOver");-var targetsOf = /* @__PURE__ */ __name((r) => Object.values(rec(r["targets"])).filter(isRec), "targetsOf");-var flagged = /* @__PURE__ */ __name((targets, key2) => targets.some((t) => key2 in t) ? targets.filter((t) => t[key2] === true).length : null, "flagged");+var targetsOf = (r) => Object.values(rec(r["targets"])).filter(isRec);+var flagged = (targets, key2) => targets.some((t) => key2 in t) ? targets.filter((t) => t[key2] === true).length : null;function contextFacts(r) {const targets = targetsOf(r);const docs = targets.map((t) => rec(t["docs"]));@@ -1599,7 +1438,6 @@ function contextFacts(r) {...fact("hotspots", flagged(targets, "hotspot") || null)];}-__name(contextFacts, "contextFacts");function riskFacts(r) {const targets = targetsOf(r);return [@@ -1610,7 +1448,6 @@ function riskFacts(r) {...fact("hotspots", flagged(targets, "is_hotspot") || null)];}-__name(riskFacts, "riskFacts");function answerFacts(r) {return [...fact("citations", count2(r["citations"])),@@ -1619,7 +1456,6 @@ function answerFacts(r) {...fact("guesses", count2(r["best_guesses"]))];}-__name(answerFacts, "answerFacts");function whyFacts(r) {const git2 = rec(r["git_archaeology"]);return [@@ -1628,11 +1464,9 @@ function whyFacts(r) {...fact("commits", count2(git2["git_log"] ?? git2["file_commits"]))];}-__name(whyFacts, "whyFacts");function searchFacts(r) {return fact("results", count2(r["results"]));}-__name(searchFacts, "searchFacts");function symbolFacts(r) {const start = num(r["start_line"]);const end = num(r["end_line"]);@@ -1642,11 +1476,9 @@ function symbolFacts(r) {...fact("callees", count2(r["callees"]))];}-__name(symbolFacts, "symbolFacts");function listFacts(r) {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 = {get_context: contextFacts,get_risk: riskFacts,@@ -1659,7 +1491,6 @@ function insideOf(tool, r) {const known = READERS[tool]?.(r) ?? [];return known.length > 0 ? known : listFacts(r);}-__name(insideOf, "insideOf");function behindOf(r, meta) {const budget = rec(meta["response_budget"]);const used = num(budget["serialized_chars"]);@@ -1681,13 +1512,12 @@ function behindOf(r, meta) {semantic: bool(meta["semantic_search"])};}-__name(behindOf, "behindOf");var PATH_READERS = {- path: /* @__PURE__ */ __name((v, add) => add(v), "path"),- file: /* @__PURE__ */ __name((v, add) => add(v), "file"),- file_path: /* @__PURE__ */ __name((v, add) => add(v), "file_path"),- citations: /* @__PURE__ */ __name((v, add) => Array.isArray(v) ? v.forEach(add) : void 0, "citations"),- targets: /* @__PURE__ */ __name((v, add) => isRec(v) ? Object.keys(v).forEach(add) : void 0, "targets")+ path: (v, add) => add(v),+ file: (v, add) => add(v),+ file_path: (v, add) => add(v),+ citations: (v, add) => Array.isArray(v) ? v.forEach(add) : void 0,+ targets: (v, add) => isRec(v) ? Object.keys(v).forEach(add) : void 0};function walkPaths(v, depth, add) {if (depth > MAX_DEPTH) return;@@ -1698,7 +1528,6 @@ function walkPaths(v, depth, add) {walkPaths(value, depth + 1, add);}}-__name(walkPaths, "walkPaths");function pathsOf(r) {const found = /* @__PURE__ */ new Set();walkPaths(r, 0, (p) => {@@ -1706,18 +1535,15 @@ function pathsOf(r) {});return [...found];}-__name(pathsOf, "pathsOf");var EMPTY_BEHIND = behindOf({}, {});function utf8Bytes(text2) {return new TextEncoder().encode(text2).length;}-__name(utf8Bytes, "utf8Bytes");function errorOf(body) {const err = body["error"];if (typeof err === "string") return err.split("\n")[0] ?? err;return str(rec(err)["message"]);}-__name(errorOf, "errorOf");function summarizeBody(tool, body, bytes, excerpt = "") {const r = rec(body);const meta = rec(r["_meta"]);@@ -1732,7 +1558,6 @@ function summarizeBody(tool, body, bytes, excerpt = "") {error: errorOf(r)};}-__name(summarizeBody, "summarizeBody");function summarizeReply(tool, text2) {const bytes = utf8Bytes(text2);const excerpt = text2.slice(0, EXCERPT_CHARS);@@ -1741,7 +1566,6 @@ function summarizeReply(tool, text2) {const summary = summarizeBody(tool, resultOf(parsed), bytes, excerpt);return summary.error === null ? { ...summary, error: errorOf(parsed) } : summary;}-__name(summarizeReply, "summarizeReply");function parseObject(text2) {try {const v = JSON.parse(text2);@@ -1750,18 +1574,15 @@ function parseObject(text2) {return null;}}-__name(parseObject, "parseObject");function resultOf(parsed) {const result = isRec(parsed["result"]) ? parsed["result"] : parsed;return isRec(parsed["_meta"]) && !isRec(result["_meta"]) ? { ...result, _meta: parsed["_meta"] } : result;}-__name(resultOf, "resultOf");function unparsed(tool, text2, bytes, excerpt) {const first = text2.trim().split("\n")[0] ?? "";const error = text2.length <= PARSE_CHARS && first !== "" ? first : null;return { tool, bytes, parsed: false, inside: [], behind: EMPTY_BEHIND, paths: [], excerpt, error };}-__name(unparsed, "unparsed");// src/model/flow.tsvar MAX_TURNS = 6;@@ -1785,11 +1606,9 @@ var END_OF = { answer: "answer", aborted: "stopped", refusal: "failed", error: "function turnEnd(reason, isAborted) {return END_OF[reason ?? ""] ?? (isAborted === true ? "stopped" : "answer");}-__name(turnEnd, "turnEnd");function repowiseTool(name) {return REPOWISE_TOOL.exec(name)?.[1] ?? null;}-__name(repowiseTool, "repowiseTool");var KIND_OF = {Read: "read",Edit: "edit",@@ -1809,14 +1628,12 @@ function shortPath(path, root) {const inside2 = slashed.toLowerCase().startsWith(`${base.toLowerCase()}/`);return inside2 ? slashed.slice(base.length + 1) : slashed;}-__name(shortPath, "shortPath");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);}-__name(argValue, "argValue");function compactArgs(e, root) {const out = [];for (const key2 of ARG_KEYS) {@@ -1825,8 +1642,7 @@ function compactArgs(e, root) {}return out;}-__name(compactArgs, "compactArgs");-var lineCount = /* @__PURE__ */ __name((s) => typeof s === "string" ? s.split("\n").length : null, "lineCount");+var lineCount = (s) => typeof s === "string" ? s.split("\n").length : null;function editLines(e) {const written = e.tool === "Write" ? lineCount(e["content"]) : null;if (written !== null) return { written };@@ -1834,24 +1650,20 @@ function editLines(e) {const after = lineCount(e["new_string"]);return before !== null && after !== null ? { delta: after - before } : null;}-__name(editLines, "editLines");function askedFiles(e, root) {const targets = e["targets"];const list2 = Array.isArray(targets) ? targets : [];return list2.filter((t) => typeof t === "string" && !t.includes("::")).map((t) => shortPath(t, root));}-__name(askedFiles, "askedFiles");function isClaudeCall(e) {return typeof e.tool_use_id === "string" && typeof e.tool === "string" && !e.tool_use_id.startsWith(OWN_CALL_PREFIX);}-__name(isClaudeCall, "isClaudeCall");function activityOf(e, at, root) {if (!isClaudeCall(e)) return null;const rw = repowiseTool(e.tool);const kind = rw !== null ? "repowise" : KIND_OF[e.tool] ?? "other";return { ...BLANK, id: e.tool_use_id, kind, tool: rw ?? e.tool, agentId: agentOf(e), startedAt: at, args: compactArgs(e, root), ...BY_KIND[kind](e, root) };}-__name(activityOf, "activityOf");var BLANK = {endedAt: null,paths: [],@@ -1865,23 +1677,21 @@ var BLANK = {hits: null,hitPaths: []};-var agentOf = /* @__PURE__ */ __name((e) => typeof e.agentId === "string" ? e.agentId : null, "agentOf");+var agentOf = (e) => typeof e.agentId === "string" ? e.agentId : null;function fileOf(e, root) {const file = e["file_path"] ?? e["notebook_path"];return { paths: typeof file === "string" ? [shortPath(file, root)] : [] };}-__name(fileOf, "fileOf");function commandOf(e) {const command = e["command"];return { command: typeof command === "string" ? command.slice(0, COMMAND_CHARS) : null };}-__name(commandOf, "commandOf");var BY_KIND = {- repowise: /* @__PURE__ */ __name((e, root) => ({ ...fileOf(e, root), asked: askedFiles(e, root) }), "repowise"),+ repowise: (e, root) => ({ ...fileOf(e, root), asked: askedFiles(e, root) }),read: fileOf,- edit: /* @__PURE__ */ __name((e, root) => ({ ...fileOf(e, root), lines: editLines(e) }), "edit"),+ edit: (e, root) => ({ ...fileOf(e, root), lines: editLines(e) }),search: fileOf,- shell: /* @__PURE__ */ __name((e) => commandOf(e), "shell"),+ shell: (e) => commandOf(e),other: fileOf};function searchHits(outcome, root) {@@ -1891,12 +1701,10 @@ function searchHits(outcome, root) {const names2 = result.filenames.filter((f) => typeof f === "string");return { hits: names2.length, hitPaths: names2.slice(0, MAX_HIT_PATHS).map((f) => shortPath(f, root)) };}-__name(searchHits, "searchHits");function outcomeText(outcome) {const text2 = outcome?.text;return typeof text2 === "string" ? text2 : null;}-__name(outcomeText, "outcomeText");function toolEnded(e, outcome, at, root) {if (!isClaudeCall(e)) return null;const rw = repowiseTool(e.tool);@@ -1907,15 +1715,12 @@ function toolEnded(e, outcome, at, root) {const bytes = summary?.bytes ?? (text2 === null ? null : new TextEncoder().encode(text2).length);return { type: "toolEnded", id: e.tool_use_id, at, isError, bytes, reply, ...searchHits(outcome, root) };}-__name(toolEnded, "toolEnded");function pathKey(path) {return path.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();}-__name(pathKey, "pathKey");function namingOf(named2, path) {return named2[pathKey(path)] ?? null;}-__name(namingOf, "namingOf");function withNamed(named2, paths, naming) {let out = named2;let size = Object.keys(named2).length;@@ -1928,12 +1733,11 @@ function withNamed(named2, paths, naming) {}return out;}-__name(withNamed, "withNamed");-var isFile = /* @__PURE__ */ __name((a) => a.kind === "read" || a.kind === "edit", "isFile");-var isAnswered = /* @__PURE__ */ __name((a) => a.kind === "repowise" && a.endedAt !== null && !a.isError, "isAnswered");+var isFile = (a) => a.kind === "read" || a.kind === "edit";+var isAnswered = (a) => a.kind === "repowise" && a.endedAt !== null && !a.isError;function turnTotals(turn) {const files = turn.activities.filter(isFile);- const keys = /* @__PURE__ */ __name((list2) => new Set(list2.map((a) => pathKey(a.paths[0] ?? ""))), "keys");+ const keys = (list2) => new Set(list2.map((a) => pathKey(a.paths[0] ?? "")));const answered = turn.activities.filter(isAnswered);const edits = files.filter((a) => a.kind === "edit");return {@@ -1947,40 +1751,33 @@ function turnTotals(turn) {editNamed: edits.some((a) => a.namedBy !== null)};}-__name(turnTotals, "turnTotals");function fold(earlier, turn) {const t = turnTotals(turn);return { turns: earlier.turns + 1, repowise: earlier.repowise + t.repowise, reads: earlier.reads + t.reads, edits: earlier.edits + t.edits };}-__name(fold, "fold");function withTurn(state2, turn) {const turns = [...state2.turns, turn];if (turns.length <= MAX_TURNS) return { ...state2, turns };const gone = turns.shift();return { ...state2, turns, earlier: fold(state2.earlier, gone) };}-__name(withTurn, "withTurn");var INJECTED = /\s*<\\?((?:agent-message|system-reminder|task-notification|local-command-[\w-]+|command-[\w-]+))\b[^>]*>[\s\S]*?(?:<\/\1>|$)\s*/g;function userWords(text2) {return text2.replace(INJECTED, " ").trim();}-__name(userWords, "userWords");function newTurn(state2, turnId, prompt, at) {const seq = (state2.turns.at(-1)?.seq ?? state2.earlier.turns) + 1;return { seq, turnId, prompt: userWords(prompt).slice(0, PROMPT_CHARS), startedAt: at, endedAt: null, durationMs: null, end: null, activities: [], dropped: 0 };}-__name(newTurn, "newTurn");function openTurn(state2, at) {const last = state2.turns.at(-1);return last !== void 0 && last.endedAt === null ? state2 : withTurn(state2, newTurn(state2, null, "", at));}-__name(openTurn, "openTurn");function mapLast(state2, f) {const last = state2.turns.at(-1);const next = last === void 0 ? last : f(last);return next === last ? state2 : { ...state2, turns: [...state2.turns.slice(0, -1), next] };}-__name(mapLast, "mapLast");function mapActivity(state2, id, f) {const i = state2.turns.findIndex((t) => t.activities.some((a) => a.id === id));if (i < 0) return state2;@@ -1989,26 +1786,21 @@ function mapActivity(state2, id, f) {const turns = state2.turns.map((t, j) => j === i ? { ...turn, activities } : t);return { ...state2, turns };}-__name(mapActivity, "mapActivity");function pushActivity(t, activity) {const all = [...t.activities, activity];const over = all.length - MAX_ACTIVITIES;return over > 0 ? { ...t, activities: all.slice(over), dropped: t.dropped + over } : { ...t, activities: all };}-__name(pushActivity, "pushActivity");function append(state2, activity) {return mapLast(openTurn(state2, activity.startedAt), (t) => pushActivity(t, activity));}-__name(append, "append");function closeTurn(state2, at, durationMs, end) {return mapLast(state2, (t) => t.endedAt !== null ? t : { ...t, endedAt: at, durationMs: durationMs ?? at - t.startedAt, end });}-__name(closeTurn, "closeTurn");function started(state2, activity) {const namedBy = isFile(activity) && activity.paths[0] !== void 0 ? namingOf(state2.named, activity.paths[0]) : null;return append(state2, { ...activity, namedBy });}-__name(started, "started");function ended(state2, action) {const { id, at, isError, bytes, reply, hits, hitPaths } = action;const next = mapActivity(state2, id, (a) => ({ ...a, endedAt: at, isError, bytes, reply, hits, hitPaths }));@@ -2016,11 +1808,9 @@ function ended(state2, action) {const turn = next.turns.find((t) => t.activities.some((a) => a.id === id));return { ...next, named: withNamed(next.named, reply.paths, { id, tool: reply.tool, at, turn: turn.seq }) };}-__name(ended, "ended");function openable(state2) {return state2.turns.flatMap((t) => t.activities.filter((a) => a.kind === "repowise").map((a) => a.id));}-__name(openable, "openable");function stepped(state2, by) {const ids2 = openable(state2);if (ids2.length === 0) return state2;@@ -2028,7 +1818,6 @@ function stepped(state2, by) {const i = at < 0 ? by === 1 ? 0 : ids2.length - 1 : Math.min(ids2.length - 1, Math.max(0, at + by));return ids2[i] === state2.open ? state2 : { ...state2, open: ids2[i] };}-__name(stepped, "stepped");function reduceFlow(state2, action) {switch (action.type) {case "turnStarted": {@@ -2049,7 +1838,6 @@ function reduceFlow(state2, action) {return stepped(state2, action.by);}}-__name(reduceFlow, "reduceFlow");function visits(state2) {const out = [];let order = 0;@@ -2061,23 +1849,19 @@ function visits(state2) {}return out;}-__name(visits, "visits");function visitsOf(a, turn, order) {if (a.isError) return [];if (a.kind === "search") return a.hitPaths.map((path2) => ({ path: path2, kind: "search-hit", order, at: a.endedAt ?? a.startedAt, turn }));const path = a.paths[0];return (a.kind === "read" || a.kind === "edit") && path !== void 0 ? [{ path, kind: a.kind, order, at: a.startedAt, turn }] : [];}-__name(visitsOf, "visitsOf");function isWorking(state2) {const last = state2.turns.at(-1);return last !== void 0 && last.endedAt === null;}-__name(isWorking, "isWorking");function inFlight(state2) {return state2.turns.at(-1)?.activities.find((a) => a.kind === "repowise" && a.endedAt === null) ?? null;}-__name(inFlight, "inFlight");// src/model/turnFacts.tsvar COCHANGE_SHOWN = 2;@@ -2090,7 +1874,6 @@ function testsOf(file) {const inferred = file.inferred_tests_total ?? 0;return inferred > 0 ? { total: inferred, files: file.inferred_tests ?? [], basis: "inferred" } : null;}-__name(testsOf, "testsOf");function blastFacts(path, r) {const key2 = pathKey(path);const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key2);@@ -2098,17 +1881,14 @@ function blastFacts(path, r) {const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key2));return { importers, cochange, tests };}-__name(blastFacts, "blastFacts");-var allActivities = /* @__PURE__ */ __name((state2) => state2.turns.flatMap((t) => t.activities), "allActivities");+var allActivities = (state2) => state2.turns.flatMap((t) => t.activities);function openedKeys(state2) {return new Set(allActivities(state2).filter(isFile).map((a) => pathKey(a.paths[0] ?? "")));}-__name(openedKeys, "openedKeys");function testCommands(state2) {return allActivities(state2).map((a) => a.command).filter((c) => c !== null && TEST_RUNNER.test(c));}-__name(testCommands, "testCommands");-var asWord = /* @__PURE__ */ __name((command, word) => !GENERIC.has(word) && new RegExp(`(^|[^\\w])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^\\w])`).test(command), "asWord");+var asWord = (command, word) => !GENERIC.has(word) && new RegExp(`(^|[^\\w])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^\\w])`).test(command);function names(command, test) {const slashed = test.replace(/\\/g, "/");const parts = slashed.split("/");@@ -2117,12 +1897,10 @@ function names(command, test) {const cmd = command.replace(/\\/g, "/");return cmd.includes(slashed) || asWord(cmd, stem) || asWord(cmd, folder);}-__name(names, "names");function testsRun(state2, tests) {const commands = testCommands(state2);return tests.filter((t) => commands.some((c) => names(c, t))).length;}-__name(testsRun, "testsRun");function gapsOf(state2, path, facts, opened) {const seen = facts.importers.filter((p) => opened.has(pathKey(p))).length;const t = facts.tests;@@ -2134,8 +1912,7 @@ function gapsOf(state2, path, facts, opened) {tests: t !== null && run < t.total ? { total: t.total, run, basis: t.basis } : null};}-__name(gapsOf, "gapsOf");-var hasGap = /* @__PURE__ */ __name((g) => g.importers !== null || g.cochange.length > 0 || g.tests !== null, "hasGap");+var hasGap = (g) => g.importers !== null || g.cochange.length > 0 || g.tests !== null;function editedFiles(turn) {const out = /* @__PURE__ */ new Map();for (const a of turn.activities) {@@ -2144,21 +1921,17 @@ function editedFiles(turn) {}return [...out.values()];}-__name(editedFiles, "editedFiles");function beforeAccept(state2, turn) {const opened = openedKeys(state2);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, 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) {if (first.namedBy !== null) return { kind: "repowise", tool: first.namedBy.tool };return searchedBefore(state2, pathKey(first.paths[0] ?? ""), first.startedAt) ? { kind: "search" } : { kind: "direct" };}-__name(viaOf, "viaOf");function workingSet(state2, turn) {const first = /* @__PURE__ */ new Map();const edited = /* @__PURE__ */ new Set();@@ -2170,7 +1943,6 @@ function workingSet(state2, turn) {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");var CONTEXT_KINDS = ["repowise", "read", "search", "shell", "other"];var CONTEXT_OF = {repowise: "repowise",@@ -2188,12 +1960,10 @@ function contextBytes(turn) {}return out;}-__name(contextBytes, "contextBytes");function firstEditMs(turn) {const edit = turn.activities.find((a) => a.kind === "edit");return edit === void 0 ? null : edit.startedAt - turn.startedAt;}-__name(firstEditMs, "firstEditMs");function firstEdits(state2) {const out = /* @__PURE__ */ new Map();for (const a of allActivities(state2)) {@@ -2202,13 +1972,11 @@ function firstEdits(state2) {}return out;}-__name(firstEdits, "firstEdits");function answeredBeforeEdit(state2) {const edits = firstEdits(state2);- const before = /* @__PURE__ */ __name((a) => a.asked.some((p) => (edits.get(pathKey(p)) ?? Number.POSITIVE_INFINITY) < a.startedAt), "before");+ const before = (a) => a.asked.some((p) => (edits.get(pathKey(p)) ?? Number.POSITIVE_INFINITY) < a.startedAt);return new Set(allActivities(state2).filter((a) => a.kind === "repowise" && before(a)).map((a) => a.id));}-__name(answeredBeforeEdit, "answeredBeforeEdit");// src/views/copy.tsvar HINTS = {@@ -2222,14 +1990,12 @@ function freshnessLine(f) {const changed = f.changedFiles === null ? "" : ` (${countOf(f.changedFiles, "file", "files")} changed)`;return `index behind HEAD${changed} · repowise update`;}-__name(freshnessLine, "freshnessLine");function spinnerLine(file, ctx) {const parts = [file.slice(file.lastIndexOf("/") + 1)];if (ctx.callerFiles) parts.push(countOf(ctx.callerFiles, "caller file", "caller files"));if (ctx.contributors) parts.push(countOf(ctx.contributors, "contributor", "contributors"));return parts.join(" · ");}-__name(spinnerLine, "spinnerLine");function squeezeLine(s) {const parts = [`${countOf(s.originalLines, "line", "lines")} → ${s.keptLines.toLocaleString("en-US")}`];if (s.omittedTokens > 0) parts.push(`~${countOf(s.omittedTokens, "token", "tokens")} omitted`);@@ -2239,7 +2005,6 @@ function squeezeLine(s) {parts.push(`repowise expand ${s.refs[0]}${more}`);return parts.join(" · ");}-__name(squeezeLine, "squeezeLine");function marginLine(note) {if (note.kind === "decision") {return note.reviewed ? `a standing decision covers this file: ${note.title}` : `a decision found in this file, not yet reviewed: ${note.title}`;@@ -2247,7 +2012,6 @@ function marginLine(note) {const where = note.symbol === null ? "" : `, mostly in ${note.symbol}`;return `fixed ${countOf(note.count, "time", "times")} in 6 months, most recently ${note.age}${where}`;}-__name(marginLine, "marginLine");function savingsLine(d, columns) {const inferred = d.inferredTokens > 0 ? ` (${d.inferredTokens.toLocaleString("en-US")} inferred)` : "";const usd = d.usd >= 5e-3 ? ` · $${d.usd.toFixed(2)}` : "";@@ -2255,7 +2019,6 @@ function savingsLine(d, columns) {const full = `${head} since this session started · all agents on this repo`;return full.length <= columns ? full : `${head} this session · all agents`;}-__name(savingsLine, "savingsLine");var REVIEWING = "Reviewing the change...";var REVIEW_TIMEOUT_S = 20;var REVIEW_TIMED_OUT = `Change review timed out after ${REVIEW_TIMEOUT_S} s`;@@ -2266,92 +2029,74 @@ var OVERLAP_MARK = "◦";function reviewFailed(message) {return `Change review could not run: ${message}`;}-__name(reviewFailed, "reviewFailed");function reviewScope(ref, workingTree, changed) {const where = workingTree ? ref : `${ref} (no uncommitted changes)`;return changed === null ? where : `${where}, ${countOf(changed, "changed file", "changed files")}`;}-__name(reviewScope, "reviewScope");function noNewFindings(analyzed) {return `no new findings in ${analyzed === 1 ? "the 1 changed file" : `all ${analyzed.toLocaleString("en-US")} changed files`}`;}-__name(noNewFindings, "noNewFindings");function healthImproved(resolved) {return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;}-__name(healthImproved, "healthImproved");var HEALTH_NOT_REPORTED = "not reported";var NO_NEW_FINDINGS = "no new findings";var PARTLY_COMPARED = "partly compared, no new findings";function notCompared(why) {return why === "" ? "not compared" : `not compared: ${why}`;}-__name(notCompared, "notCompared");function improvedShort(resolved) {return `improved, ${resolved.toLocaleString("en-US")} resolved`;}-__name(improvedShort, "improvedShort");function newFindings(total2, required2) {return `${countOf(total2, "new finding", "new findings")}, ${required2 ? "review required" : "low severity"}`;}-__name(newFindings, "newFindings");function resolvedToo(resolved) {return `${countOf(resolved, "finding", "findings")} resolved`;}-__name(resolvedToo, "resolvedToo");function findingLine(f) {const at = f.lines === void 0 ? f.path : `${f.path}:${f.lines[0]}`;return `${f.severity} ${f.biomarker}: ${f.reason} (${at})`;}-__name(findingLine, "findingLine");function moreFindings(more) {return `and ${more.toLocaleString("en-US")} more (Details)`;}-__name(moreFindings, "moreFindings");function partialScope(analyzed, changed, reasons) {const why = Object.entries(reasons).map(([reason, n]) => `${n.toLocaleString("en-US")} ${reason.replace(/_/g, " ")}`).join(", ");const skipped = changed - analyzed;return `Scope: compared ${analyzed.toLocaleString("en-US")} of ${countOf(changed, "changed file", "changed files")}; ${skipped.toLocaleString("en-US")} not analysed${why ? ` (${why})` : ""}, so this is not a clean bill`;}-__name(partialScope, "partialScope");function diffShape(percentile) {const where = percentile === null || percentile === void 0 ? "not ranked (no recent commits to compare)" : `bigger than ${Math.round(percentile)}% of this repo's recent commits`;return `Diff shape: ${where}; size, not danger`;}-__name(diffShape, "diffShape");function testsBasis(measured) {return measured ? "measured by stored coverage" : "inferred from the dependency graph, not measured";}-__name(testsBasis, "testsBasis");function testsLine(t) {const count3 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");const shown = t.truncated ? ` (first ${t.tests.length.toLocaleString("en-US")} shown)` : "";return `Tests to run: ${count3}, ${testsBasis(t.measured)}${shown}: ${t.tests.join(", ")}`;}-__name(testsLine, "testsLine");function overlapLine(branches, files, more) {const who = countOf(branches.length, "other branch", "other branches") + (more ? " or more" : "");const what = files.length === 1 ? files[0] : countOf(files.length, "changed file", "changed files");const verb = branches.length === 1 && !more ? "edits" : "edit";return `${OVERLAP_MARK} ${who} also ${verb} ${what} (${branches.join(", ")})`;}-__name(overlapLine, "overlapLine");function overlapShort(branches) {return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;}-__name(overlapShort, "overlapShort");function directiveLines(d) {const out = [`Change review: ${d.status.replace(/_/g, " ")}`, d.headline];if (d.reasons?.length) out.push("Reasons:", ...d.reasons.map((r) => ` ${r}`));if (d.next_actions?.length) out.push("Next actions:", ...d.next_actions.map((a) => ` ${a}`));return out;}-__name(directiveLines, "directiveLines");function runTestsPrompt(t) {const rest = t.truncated ? ` (the first ${t.tests.length} of ${t.total})` : "";return `Run the tests Repowise names for this change${rest}, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;}-__name(runTestsPrompt, "runTestsPrompt");var MAP_COPY = {title: "Lens",looking: "Lens map: looking for the local server",@@ -2374,63 +2119,52 @@ var STORY_COPY = {function mapAlt(drawn) {return `Map of the repo: ${countOf(drawn, "file", "files")} drawn as tiles, with the files Claude searched, opened and edited this turn lit, and the files that import its edit`;}-__name(mapAlt, "mapAlt");function notPlacedLine(reason) {return `Lens map needs a wider terminal: ${reason}`;}-__name(notPlacedLine, "notPlacedLine");var SCOPE_REST = "rest too small to draw";function indexedPart(age) {return `indexed ${age}`;}-__name(indexedPart, "indexedPart");function cappedPart(s) {const largest = `${formatNumber(s.shown)} largest of ${countOf(s.repositoryTotal, "file", "files")}`;if (s.dense) return [`${largest}; drawn as folders at this size`];if (s.drawn >= s.shown) return [`${largest} drawn`];return [`${formatNumber(s.drawn)} of the ${formatNumber(s.shown)} largest (of ${countOf(s.repositoryTotal, "file", "files")}) drawn at this size`, SCOPE_REST];}-__name(cappedPart, "cappedPart");function drawnPart(s) {if (s.beyondCap > 0) return cappedPart(s);if (s.dense) return [`${countOf(s.repositoryTotal, "file", "files")}, drawn as folders at this size`];if (s.drawn >= s.repositoryTotal) return [`${countOf(s.repositoryTotal, "file", "files")}, all drawn`];return [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];}-__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")} ${s.zoom === null ? "not on the map" : "outside this folder"}`);return parts;}-__name(scopeParts, "scopeParts");function searchedPart(pattern, hits) {const count3 = hits === null ? "matches not counted" : countOf(hits, "file", "files");return pattern === "" ? `last search matched ${count3}` : `${pattern}: ${count3}`;}-__name(searchedPart, "searchedPart");function linesPart(lines) {if (lines === null) return "";if ("written" in lines) return ` ${countOf(lines.written, "line", "lines")} written`;const sign = lines.delta > 0 ? "+" : lines.delta < 0 ? "-" : "";return ` ${sign}${countOf(Math.abs(lines.delta), "line", "lines")}`;}-__name(linesPart, "linesPart");function namedByPart(name, tool) {return `◆ ${name} named by ${tool}`;}-__name(namedByPart, "namedByPart");function reachesPart(total2, names2) {const shown = names2.map((n) => n.opened ? `${n.name} (opened)` : n.name);const more = total2 - names2.length;return `${countOf(total2, "importer", "importers")}: ${[...shown, ...more > 0 ? [`+${formatNumber(more)}`] : []].join(", ")}`;}-__name(reachesPart, "reachesPart");function reachesPending(edit) {return `finding the files that import ${edit}`;}-__name(reachesPending, "reachesPending");var REACHES_FAILED = "import graph unavailable";var MAP_KEYS_COPY = {next: "next",@@ -2442,7 +2176,6 @@ var MAP_KEYS_COPY = {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)}`}`);@@ -2451,17 +2184,14 @@ function whyParts(why) {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]",@@ -2480,19 +2210,15 @@ var ASK_CHARS = 4e3;function askingLine(tool) {return tool === "get_why" ? "asking the decision records..." : "asking the index...";}-__name(askingLine, "askingLine");function askFailedLine(message) {return `Could not answer: ${message}`;}-__name(askFailedLine, "askFailedLine");function askCut(chars) {return `reply cut at ${formatNumber(chars)} characters`;}-__name(askCut, "askCut");function moreRows(more) {return `and ${formatNumber(more)} more`;}-__name(moreRows, "moreRows");var RECAP_COPY = {files: "Files",fromReview: "from the last change review",@@ -2518,26 +2244,21 @@ function filesTouched(edited, touched) {const all = touched.capped ? `${formatNumber(touched.count)}+` : formatNumber(touched.count);return `${formatNumber(edited)} edited of ${all} ${touched.count === 1 && !touched.capped ? "file" : "files"} touched`;}-__name(filesTouched, "filesTouched");function findingsCounts(resolved, total2) {return `${formatNumber(resolved)} resolved · ${countOf(total2, "new finding", "new findings")}`;}-__name(findingsCounts, "findingsCounts");function testsToRunCount(t) {const count3 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");return `${count3}, ${t.measured ? "measured" : "inferred"}`;}-__name(testsToRunCount, "testsToRunCount");function decisionsSurfaced(titles) {return `${formatNumber(titles.length)}: ${titles.join("; ")}`;}-__name(decisionsSurfaced, "decisionsSurfaced");function recapFooter(modelAsks) {if (modelAsks === 0) return `${RECAP_COPY.noModel} ${RECAP_COPY.fromIndex}`;const asks = countOf(modelAsks, "Ask reply", "Ask replies");return `${RECAP_COPY.noModel} ${asks} from get_answer may have been written by this repo's configured model.`;}-__name(recapFooter, "recapFooter");var BRIEF_COPY = {compacted: "context compacted",button: "Brief Claude",@@ -2550,11 +2271,9 @@ var BRIEF_CHARS = 1200;function briefDecision(title, reviewed) {return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;}-__name(briefDecision, "briefDecision");function briefTests(t) {return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;}-__name(briefTests, "briefTests");var FLOW_COPY = {waiting: "Waiting for Claude",empty: "Lens is listening. Send a prompt and this tab shows what only Lens sees: what an edit reaches, where Claude's context came from, and what Repowise answered.",@@ -2586,26 +2305,22 @@ function clockText(ms) {const s = Math.max(0, Math.floor(ms / 1e3));return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;}-__name(clockText, "clockText");function durationText(ms) {if (ms < 1e3) return `${Math.max(0, Math.round(ms))} ms`;if (ms < 1e4) return `${(ms / 1e3).toFixed(1)} s`;const s = Math.round(ms / 1e3);return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;}-__name(durationText, "durationText");function sizeText(bytes) {if (bytes < 1024) return `${bytes} B`;if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;}-__name(sizeText, "sizeText");var END_WORD = { answer: "Done", stopped: "Stopped", failed: "Did not finish" };function statusLine(end, ms, edited) {const head = end === null ? `Working · ${clockText(ms)}` : `${END_WORD[end]} · ${durationText(ms)}`;return edited === 0 ? head : `${head} · edited ${countOf(edited, "file", "files")}`;}-__name(statusLine, "statusLine");function answerLine(t) {const parts = [t.repowise === 0 ? FLOW_COPY.noRepowise : `Repowise ${countOf(t.repowise, "call", "calls")}`];const named2 = t.named > 0 ? `, ${formatNumber(t.named)} named by Repowise first` : "";@@ -2613,24 +2328,19 @@ function answerLine(t) {if (t.editNamed) parts.push(FLOW_COPY.editNamed);return parts.join(" · ");}-__name(answerLine, "answerLine");function importersLine(total2, opened) {return `${countOf(total2, "direct importer", "direct importers")}; Claude opened ${opened === 0 ? "none" : formatNumber(opened)}`;}-__name(importersLine, "importersLine");function cochangeLine(partners) {return `not opened, usually changes with it (co-change score): ${partners.map((p) => `${p.path} ${p.score.toFixed(2)}`).join(", ")}`;}-__name(cochangeLine, "cochangeLine");function testsReachLine(total2, basis, run, file) {return `${countOf(total2, "test file", "test files")} reach ${file} (${basis}); ${run === 0 ? "none" : formatNumber(run)} run`;}-__name(testsReachLine, "testsReachLine");function introducedLine(n, first) {const what = first === null ? "" : `: ${first.biomarker.replace(/_/g, " ")} in ${first.path.split("/").at(-1)}`;return `this turn introduced ${countOf(n, "finding", "findings")}${what}`;}-__name(introducedLine, "introducedLine");var HEALTH_PARTLY = "health compared in part only; no new findings in the part compared";function knowsParts(k) {const parts = [];@@ -2639,42 +2349,33 @@ function knowsParts(k) {if (k.recentOwner !== null) parts.push(`recent owner ${k.recentOwner.name} ${Math.round(k.recentOwner.share * 100)} %`);return parts;}-__name(knowsParts, "knowsParts");function moreFiles(n) {return `+${formatNumber(n)} more`;}-__name(moreFiles, "moreFiles");var CONTEXT_LABEL = { repowise: "Repowise", read: "file reads", search: "search", shell: "shell", other: "other" };function contextPart(kind, bytes) {return `${CONTEXT_LABEL[kind]} ${sizeText(bytes)}`;}-__name(contextPart, "contextPart");function firstEditText(ms) {return `first edit after ${durationText(ms)}`;}-__name(firstEditText, "firstEditText");function turnFooter(turn, ms, t, end = "answer") {const how = end === null || end === "answer" ? "" : ` · ${END_WORD[end].toLowerCase()}`;const took = ms === null ? "" : ` · ${durationText(ms)}`;return `Turn ${turn}${how}${took} · ${countOf(t.repowise, "Repowise call", "Repowise calls")} · ${countOf(t.reads, "file read", "files read")} · ${formatNumber(t.edits)} edited`;}-__name(turnFooter, "turnFooter");function earlierLine(t) {return `Earlier: ${countOf(t.turns, "turn", "turns")} · ${countOf(t.repowise, "Repowise call", "Repowise calls")} · ${countOf(t.reads, "file read", "files read")} · ${formatNumber(t.edits)} edited`;}-__name(earlierLine, "earlierLine");function hiddenSteps(n) {return `${countOf(n, "earlier call", "earlier calls")} hidden · j / k step through calls`;}-__name(hiddenSteps, "hiddenSteps");function laterSteps(n) {return `${countOf(n, "later call", "later calls")} below · j / k step through calls`;}-__name(laterSteps, "laterSteps");function droppedSteps(n) {return `${countOf(n, "earlier step", "earlier steps")} of this turn not kept`;}-__name(droppedSteps, "droppedSteps");var INSIDE_UNITS = {targets: ["target", "targets"],docs: ["documentation page", "documentation pages"],@@ -2698,15 +2399,13 @@ function insideFact(f) {const [one2, many] = INSIDE_UNITS[f.what] ?? [f.what.replace(/_/g, " "), f.what.replace(/_/g, " ")];return f.of === void 0 ? countOf(f.n, one2, many) : `${formatNumber(f.n)} of ${countOf(f.of, one2, many)}`;}-__name(insideFact, "insideFact");function freshnessText(b) {if (b.indexBehind !== null) return b.indexBehind ? "index behind HEAD" : "index current";return b.ageDays === null ? null : `index ${countOf(b.ageDays, "day", "days")} old`;}-__name(freshnessText, "freshnessText");-var ageText = /* @__PURE__ */ __name((days) => `index ${countOf(days, "day", "days")} old`, "ageText");-var when = /* @__PURE__ */ __name((on, text2) => on ? text2 : null, "when");-var named = /* @__PURE__ */ __name((v, text2) => v === null ? null : text2(v), "named");+var ageText = (days) => `index ${countOf(days, "day", "days")} old`;+var when = (shown, text2) => shown ? text2 : null;+var named = (v, text2) => v === null ? null : text2(v);var BEHIND = [(b) => named(b.commit, (c) => `indexed at ${c}`),(b) => named(b.ageDays, ageText),@@ -2723,59 +2422,49 @@ var BEHIND = [function behindParts(b, bytes = null) {return BEHIND.map((part) => part(b, bytes)).filter((p) => p !== null);}-__name(behindParts, "behindParts");// src/views/elements.tsfunction text(value, props = {}) {return { type: "Text", props, children: [value] };}-__name(text, "text");function box(props, children) {return { type: "Box", props, children };}-__name(box, "box");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) {return { type: "Raster", props };}-__name(raster, "raster");function input(props) {return { type: "Input", props };}-__name(input, "input");function markdown(text2) {return { type: "Markdown", props: { text: text2 } };}-__name(markdown, "markdown");function svg(source, alt) {return { type: "Svg", props: { source, alt } };}-__name(svg, "svg");-var SUBMIT_IN_HOOK = /* @__PURE__ */ __name(() => void 0, "SUBMIT_IN_HOOK");+var SUBMIT_IN_HOOK = () => void 0;function pressFor(key2, presses) {const onPress = presses[key2];if (!onPress) throw new Error(`button ${key2} has no action`);return onPress;}-__name(pressFor, "pressFor");var PROPS = {- Text: /* @__PURE__ */ __name((n) => ({ ...n.props, children: n.children }), "Text"),- Box: /* @__PURE__ */ __name((n, table, presses) => ({ ...n.props, children: n.children.map((child) => materialize(child, table, presses)) }), "Box"),- Button: /* @__PURE__ */ __name((n, _table, presses) => ({ ...n.props, onPress: pressFor(n.props.key, presses) }), "Button"),- Input: /* @__PURE__ */ __name((n) => ({ ...n.props, onSubmit: SUBMIT_IN_HOOK }), "Input"),- Raster: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Raster"),- Markdown: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Markdown"),- Svg: /* @__PURE__ */ __name((n) => ({ ...n.props }), "Svg")+ Text: (n) => ({ ...n.props, children: n.children }),+ Box: (n, table, presses) => ({ ...n.props, children: n.children.map((child) => materialize(child, table, presses)) }),+ Button: (n, _table, presses) => ({ ...n.props, onPress: pressFor(n.props.key, presses) }),+ Input: (n) => ({ ...n.props, onSubmit: SUBMIT_IN_HOOK }),+ Raster: (n) => ({ ...n.props }),+ Markdown: (n) => ({ ...n.props }),+ Svg: (n) => ({ ...n.props })};function materialize(node, table, presses = {}) {const build = table[node.type];if (!build) throw new Error(`element ${node.type} is not on this surface`);return build(PROPS[node.type](node, table, presses));}-__name(materialize, "materialize");// src/views/mapPane.tsvar MAP_KEY = "lens-map";@@ -2802,7 +2491,7 @@ var HEAD = 10;var REACH_NAMES = 3;var INLINE_ROWS_PER_COLUMN = 1 / 6;var INLINE_MAX_ROWS = 20;-var hexOf = /* @__PURE__ */ __name((n) => `#${n.toString(16).padStart(6, "0")}`, "hexOf");+var hexOf = (n) => `#${n.toString(16).padStart(6, "0")}`;var BAND_SWATCHES = [...HEALTH_BAND_ORDER.map((band) => ({ glyph: "■", color: DARK_CANVAS_BAND[band], label: HEALTH_BAND_LABEL[band] })),{ glyph: "■", color: DARK_CANVAS.nodeNeutral, label: MAP_COPY.noScore }@@ -2823,19 +2512,16 @@ function packRows(items, width2, columns, gap) {}return rows;}-__name(packRows, "packRows");-var swatchWidth = /* @__PURE__ */ __name((s) => s.label.length + 2, "swatchWidth");+var swatchWidth = (s) => s.label.length + 2;function legendRows(columns, health2 = false) {const bands = health2 ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;return CRUMB_ROWS + STORY_ROWS + DETAIL_ROWS + bands + SCOPE_ROWS + KEY_ROWS;}-__name(legendRows, "legendRows");function mapSize(pane, health2 = false) {const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));const wanted = pane.placement === "dock" ? pane.bodyRows - legendRows(columns, health2) : Math.min(INLINE_MAX_ROWS, Math.round(columns * INLINE_ROWS_PER_COLUMN));return { columns, rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, wanted)) };}-__name(mapSize, "mapSize");function swatchRows(items, columns) {return packRows(items, swatchWidth, columns, GAP).map((row2) => box(@@ -2844,9 +2530,8 @@ function swatchRows(items, columns) {));}-__name(swatchRows, "swatchRows");function scopeRows(scope, columns) {- const rows = /* @__PURE__ */ __name((parts2) => packRows(parts2, (p) => p.length, columns, SEP.length), "rows");+ const rows = (parts2) => packRows(parts2, (p) => p.length, columns, SEP.length);let parts = scopeParts(scope);for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {if (rows(parts).length <= 2) break;@@ -2854,7 +2539,6 @@ function scopeRows(scope, columns) {}return rows(parts).slice(0, 2).map((row2) => row2.join(SEP));}-__name(scopeRows, "scopeRows");function storyRow(head, segs, columns) {let room = Math.max(0, columns - HEAD);const parts = [text(head.padEnd(HEAD), { dimColor: true })];@@ -2866,7 +2550,6 @@ function storyRow(head, segs, columns) {}return box({ flexDirection: "row" }, parts);}-__name(storyRow, "storyRow");function reachSegs(reach, plum) {if (reach.callers.status === "loading") return [{ text: reachesPending(reach.edit.slice(reach.edit.lastIndexOf("/") + 1)) }];if (reach.callers.status === "failed") return [{ text: REACHES_FAILED }];@@ -2874,22 +2557,18 @@ function reachSegs(reach, plum) {const names2 = paths.slice(0, REACH_NAMES).map((p) => ({ name: p.slice(p.lastIndexOf("/") + 1), opened: reach.opened.has(p.toLowerCase()) }));return [{ text: reachesPart(paths.length, names2), color: plum }];}-__name(reachSegs, "reachSegs");function searchedSegs(story) {return story.searched.length === 0 ? [] : [{ text: story.searched.map((s) => searchedPart(s.pattern, s.hits)).join(SEP) }];}-__name(searchedSegs, "searchedSegs");function openedSegs(story, plum) {if (story.opened.length === 0) return [];const named2 = story.opened.find((o) => o.namedBy !== null);const names2 = { text: story.opened.map((o) => o.name).join(SEP) };return named2 === void 0 ? [names2] : [names2, { text: ` ${namedByPart(named2.name, named2.namedBy)}`, color: plum }];}-__name(openedSegs, "openedSegs");function editedSegs(story, amber) {return story.edited.map((e, i) => ({ text: `${i === 0 ? "" : SEP}◉ ${e.name}${linesPart(e.lines)}`, color: amber }));}-__name(editedSegs, "editedSegs");function storyView(story, reach, style, columns) {const pal = MAP_PALETTES[style.theme];const rows = [@@ -2900,30 +2579,28 @@ 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 keyCells = (label) => label.length + 3;var MORE = "…";function keyRow(keys, style, columns) {- const on = [+ const offered = [["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 all = [...offered.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");+ const cells = (n) => 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);}-__name(keyRow, "keyRow");-var dimLine = /* @__PURE__ */ __name((line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" }), "dimLine");+var dimLine = (line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" });function legendView(parts, style, columns) {const story = storyView(parts.story, parts.reach, style, columns);const quiet = story.length === 0 ? [dimLine(MAP_COPY.quiet, columns)] : story;@@ -2936,11 +2613,9 @@ function legendView(parts, style, 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),@@ -2948,11 +2623,9 @@ function mapPaneView(layout, cells, parts) {...legendView(parts, layout.style, layout.columns)]);}-__name(mapPaneView, "mapPaneView");function noticeView(line2, columns) {return box({ key: "lens-map-pane", flexDirection: "column" }, [text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" })]);}-__name(noticeView, "noticeView");// src/views/owl.tsvar EYES = { open: "◉", shut: "─", side: "◐", happy: "^", still: "•" };@@ -2968,14 +2641,12 @@ function owlEyes(state2, now, still) {if (state2 !== "watching") return EYES_OF[state2];return still ? EYES.open : BLINK[Math.floor(now / BLINK_MS) % BLINK.length];}-__name(owlEyes, "owlEyes");var OWL_WIDTH = 5;function owl(state2, eyes, amber) {if (state2 === "asleep") return [text(`{${eyes},${eyes}}`, { dimColor: true })];- const eye = /* @__PURE__ */ __name(() => eyes === EYES.shut || eyes === EYES.still ? text(eyes) : text(eyes, { color: amber }), "eye");+ const eye = () => eyes === EYES.shut || eyes === EYES.still ? text(eyes) : text(eyes, { color: amber });return [text("{"), eye(), text(","), eye(), text("}")];}-__name(owl, "owl");// src/views/theme.tsvar DARK_THEME = { plum: DARK.accentSecondary, amber: BRAND.accent };@@ -2983,29 +2654,24 @@ var LIGHT_THEME = { plum: LIGHT.accentSecondary, amber: BRAND.accentTextLight };function flowTheme(light) {return light ? LIGHT_THEME : DARK_THEME;}-__name(flowTheme, "flowTheme");function themeOf(value) {return typeof value === "string" && value.startsWith("light") ? "light" : "dark";}-__name(themeOf, "themeOf");var HILLS = "▁▂▃▅▃▂▁▁▂▃▂▁▁▁▂▃▄▃▂▁";var MIRROR = { "▁": " ", "▂": "▔", "▃": "▔", "▄": "▀", "▅": "▀" };var THISTLE = "⚘";function repeat(pattern, columns) {return pattern.repeat(Math.ceil(Math.max(0, columns) / pattern.length)).slice(0, Math.max(0, columns));}-__name(repeat, "repeat");function hills(columns) {return repeat(HILLS, columns);}-__name(hills, "hills");function loch(columns) {return [...hills(columns)].map((c) => MIRROR[c] ?? " ").join("");}-__name(loch, "loch");// src/views/flow.ts-var FLOW_KEY = "lens-flow";+var FLOW_BOX_ID = "lens-flow";var FLOW_NEXT = "lens-flow-next";var FLOW_PREV = "lens-flow-prev";var HAPPY_MS = 3e3;@@ -3026,12 +2692,11 @@ var BUILT_FROM = 2;var TARGET_MIN = 28;var SEP2 = " · ";var EXCERPT_LINE = 160;-var rowKey = /* @__PURE__ */ __name((id) => `${FLOW_KEY}-${id}`, "rowKey");+var rowKey = (id) => `${FLOW_BOX_ID}-${id}`;function flowPresses(state2) {return [[FLOW_NEXT, null], [FLOW_PREV, null], ...openable(state2).map((id) => [rowKey(id), id])];}-__name(flowPresses, "flowPresses");-var width = /* @__PURE__ */ __name((segs) => segs.reduce((n, s) => n + s.t.length, 0), "width");+var width = (segs) => segs.reduce((n, s) => n + s.t.length, 0);function segNode(s) {if (s.press !== void 0) return { type: "Button", props: { key: s.press, label: s.t, plain: true } };const props = {};@@ -3039,7 +2704,6 @@ function segNode(s) {if (s.dim === true) props.dimColor = true;return text(s.t, props);}-__name(segNode, "segNode");function row(segs, columns, right = []) {const fixed = width(segs.filter((s) => s.flex !== true)) + width(right) + (right.length > 0 ? 2 : 0);const fitted = segs.map((s) => s.flex === true ? { ...s, t: fit(s.t, Math.max(1, columns - fixed)) } : s);@@ -3047,17 +2711,14 @@ function row(segs, columns, right = []) {const all = gap > 0 ? [...fitted, { t: " ".repeat(gap) }, ...right] : fitted;return box({ flexDirection: "row" }, all.filter((s) => s.t !== "").map(segNode));}-__name(row, "row");-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");+var dimLine2 = (t, columns) => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" });+var pad = (n) => ({ t: " ".repeat(n) });function wrapWords(words, columns) {return packRows(words.split(" "), (w) => w.length, Math.max(1, columns), 1).map((r) => r.join(" "));}-__name(wrapWords, "wrapWords");function section(caption, lines) {return lines.length === 0 ? [] : [text(caption, { dimColor: true }), ...lines];}-__name(section, "section");function owlState(state2, now) {const last = state2.turns.at(-1);if (last === void 0) return "asleep";@@ -3065,7 +2726,6 @@ function owlState(state2, now) {if (last.end === "stopped" || last.end === "failed") return "stopped";return last.endedAt !== null && now - last.endedAt < HAPPY_MS ? "happy" : "asleep";}-__name(owlState, "owlState");function statusSegs(turn, now, theme2) {const edited = turnTotals(turn).edits;if (turn.endedAt === null) return [{ t: statusLine(null, now - turn.startedAt, edited) }];@@ -3073,11 +2733,9 @@ function statusSegs(turn, now, theme2) {const line2 = { t: statusLine(end, turn.durationMs ?? 0, edited) };return end === "answer" ? [line2, { t: ` ${THISTLE}`, color: theme2.plum }] : [line2];}-__name(statusSegs, "statusSegs");function notice(mode) {return mode === "no-index" || mode === "no-cli" ? FLOW_COPY.notConnected : null;}-__name(notice, "notice");function header(state2, v, theme2) {const turn = state2.turns.at(-1);const st = owlState(state2, v.now);@@ -3097,8 +2755,7 @@ function header(state2, v, theme2) {...tail];}-__name(header, "header");-var fileName = /* @__PURE__ */ __name((path) => path.split("/").at(-1) ?? path, "fileName");+var fileName = (path) => path.split("/").at(-1) ?? path;function gapLines(g) {const out = [];if (g.importers !== null) out.push(importersLine(g.importers.total, g.importers.opened));@@ -3106,14 +2763,12 @@ function gapLines(g) {if (g.tests !== null) out.push(testsReachLine(g.tests.total, g.tests.basis, g.tests.run, fileName(g.path)));return out;}-__name(gapLines, "gapLines");function healthLines(risk) {const hd = risk?.health_delta;if (hd === void 0) return [];if (hd.introduced > 0) return [introducedLine(hd.introduced, hd.top_findings.find((f) => f.change === "introduced") ?? null)];return hd.status === "partial" ? [HEALTH_PARTLY] : [];}-__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),@@ -3122,19 +2777,16 @@ function beforeAcceptLines(state2, turn, v) {const health2 = healthLines(v.review).map((l) => text(fit(` ${l}`, v.columns)));return section(FLOW_COPY.beforeAccept, [...files, ...health2]);}-__name(beforeAcceptLines, "beforeAcceptLines");function viaSeg(via, theme2) {if (via.kind === "repowise") return { t: via.tool.padEnd(VIA_W), color: theme2.plum };return { t: (via.kind === "search" ? FLOW_COPY.search : FLOW_COPY.direct).padEnd(VIA_W), dim: true };}-__name(viaSeg, "viaSeg");function workingRow(f, t) {const card = t.cards.get(pathKey(f.path));const knows = t.columns < NARROW || card === void 0 ? "" : knowsParts(card).join(SEP2);const kind = { t: (f.kind === "edited" ? FLOW_COPY.edited : FLOW_COPY.read).padEnd(KIND_W), dim: f.kind === "read" };return row([pad(2), { t: fit(f.path, t.fileW).padEnd(t.fileW + 2) }, kind, viaSeg(f.via, t.theme), { t: knows, dim: true, flex: true }], t.columns);}-__name(workingRow, "workingRow");function workingLines(state2, turn, v, theme2) {const files = workingSet(state2, turn);const longest = Math.max(0, ...files.map((f) => f.path.length));@@ -3148,17 +2800,14 @@ function workingLines(state2, turn, v, theme2) {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");var SHADE = { repowise: "█", read: "▓", search: "▒", shell: "░", other: "·" };function cellsOf(bytes, total2, cells) {return CONTEXT_KINDS.filter((k) => bytes[k] > 0).map((k) => [k, Math.max(1, Math.round(bytes[k] / total2 * cells))]);}-__name(cellsOf, "cellsOf");function shadeSeg(kind, n, theme2) {const t = SHADE[kind].repeat(n);return kind === "repowise" ? { t, color: theme2.plum } : { t };}-__name(shadeSeg, "shadeSeg");function contextLines(turn, columns, theme2) {const bytes = contextBytes(turn);const total2 = CONTEXT_KINDS.reduce((n, k) => n + bytes[k], 0);@@ -3171,25 +2820,21 @@ function contextLines(turn, columns, theme2) {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");function lead(a, ctx) {const mark = a.id === ctx.active ? { t: `${ACTIVE_MARK} `, color: ctx.theme.amber } : pad(GUTTER);return [mark, { t: clockText(a.startedAt - ctx.turn.startedAt).padEnd(CLOCK_W), dim: true }];}-__name(lead, "lead");function builtFrom(a, ctx) {const reply = a.reply;const facts = reply === null ? [] : reply.inside.slice(0, BUILT_FROM).map(insideFact);const fresh = reply === null ? null : freshnessText(reply.behind);return [...ctx.beforeEdit.has(a.id) ? [FLOW_COPY.beforeEdit] : [], ...facts, ...fresh === null ? [] : [fresh]];}-__name(builtFrom, "builtFrom");function rightOf(a, ctx) {if (a.isError) return FLOW_COPY.error;if (a.endedAt === null) return FLOW_COPY.asking;return [durationText(a.endedAt - a.startedAt), ...builtFrom(a, ctx)].join(SEP2);}-__name(rightOf, "rightOf");function callLine(a, ctx) {const what = a.args[0]?.[1] ?? "";const sub = a.agentId === null ? [] : [{ t: ` ${FLOW_COPY.subagent}`, dim: true }];@@ -3197,16 +2842,13 @@ function callLine(a, ctx) {const room = ctx.columns - width(segs.filter((s) => s.flex !== true)) - Math.min(what.length, TARGET_MIN) - 2;return { node: row(segs, ctx.columns, [{ t: fit(rightOf(a, ctx), Math.max(1, room)), dim: true }]), id: a.id };}-__name(callLine, "callLine");function labeled(label, body, ctx, id) {return { node: row([pad(DETAIL_INDENT), { t: label.padEnd(DETAIL_W), dim: true }, { t: body, flex: true }], ctx.columns), id };}-__name(labeled, "labeled");function wrapped(label, parts, ctx, id) {const room = Math.max(10, ctx.columns - DETAIL_INDENT - DETAIL_W);return packRows(parts, (p) => p.length, room, SEP2.length).map((r, i) => labeled(i === 0 ? label : "", r.join(SEP2), ctx, id));}-__name(wrapped, "wrapped");function replyDetail(a, ctx) {const reply = a.reply;if (reply === null) return [];@@ -3214,13 +2856,11 @@ function replyDetail(a, ctx) {const note = ctx.beforeEdit.has(a.id) ? [FLOW_COPY.beforeEdit] : [];return [...wrapped(FLOW_COPY.howAnswered, [...note, ...behindParts(reply.behind, reply.bytes)], ctx, a.id), ...excerpt];}-__name(replyDetail, "replyDetail");function detailLines(a, ctx) {if (a.id !== ctx.open) return [];const opened = ctx.opened.get(a.id) ?? [];return [...replyDetail(a, ctx), labeled(FLOW_COPY.thenOpened, opened.length === 0 ? FLOW_COPY.nothingOpened : opened.join(", "), ctx, a.id)];}-__name(detailLines, "detailLines");function openedAfter(state2) {const out = /* @__PURE__ */ new Map();for (const a of state2.turns.flatMap((t) => t.activities)) {@@ -3233,8 +2873,7 @@ function openedAfter(state2) {}return out;}-__name(openedAfter, "openedAfter");-var isCall = /* @__PURE__ */ __name((a) => a.kind === "repowise", "isCall");+var isCall = (a) => a.kind === "repowise";function callLines(state2, turn, v, theme2) {const ctx = {turn,@@ -3249,9 +2888,8 @@ function callLines(state2, turn, v, theme2) {const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine2(` ${droppedSteps(turn.dropped)}`, v.columns) }] : [];return [...dropped, ...calls];}-__name(callLines, "callLines");-var heightOf = /* @__PURE__ */ __name((l) => l.height ?? 1, "heightOf");-var total = /* @__PURE__ */ __name((lines) => lines.reduce((n, l) => n + heightOf(l), 0), "total");+var heightOf = (l) => l.height ?? 1;+var total = (lines) => lines.reduce((n, l) => n + heightOf(l), 0);function windowStart(lines, room, open) {const at = open === null ? -1 : lines.findIndex((l) => l.id === open);const floor = at < 0 ? lines.length - 1 : Math.max(0, at - 1);@@ -3259,11 +2897,9 @@ function windowStart(lines, room, open) {while (start < floor && total(lines.slice(start)) > room) start++;return start;}-__name(windowStart, "windowStart");function stepsOutside(lines, shown) {return new Set(lines.map((l) => l.id).filter((id) => !shown.has(id))).size;}-__name(stepsOutside, "stepsOutside");function windowed(lines, room, open) {if (total(lines) <= room) return lines;const start = windowStart(lines, room - 2, open);@@ -3272,29 +2908,24 @@ 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: dimLine2(say(n), Number.POSITIVE_INFINITY) }], "note");+ const note = (n, say) => n === 0 ? [] : [{ node: dimLine2(say(n), Number.POSITIVE_INFINITY) }];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) => 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");function navRow(state2) {if (openable(state2).length === 0) return [];return [box({ flexDirection: "row", columnGap: 2 }, [button(FLOW_NEXT, "j", FLOW_COPY.next, true), button(FLOW_PREV, "k", FLOW_COPY.previous, true)])];}-__name(navRow, "navRow");function dashboard(state2, turn, v, theme2) {return [...beforeAcceptLines(state2, turn, v), ...workingLines(state2, turn, v, theme2), ...contextLines(turn, v.columns, theme2)];}-__name(dashboard, "dashboard");function closing(turn, columns) {return turn !== void 0 && turn.end === "answer" ? [text(loch(columns), { dimColor: true })] : [];}-__name(closing, "closing");function flowView(state2, v) {const theme2 = flowTheme(v.light === true);const head = [text(hills(v.columns), { color: theme2.plum }), ...header(state2, v, theme2)];@@ -3304,18 +2935,14 @@ function flowView(state2, v) {const room = Math.max(MIN_BODY, v.rows - head.length - fixed.length - after.length - 1);const calls = turn === void 0 ? [] : windowed(callLines(state2, turn, v, theme2), room, state2.open);const callNodes = section(FLOW_COPY.calls, calls.map((l) => l.node));- return box({ key: FLOW_KEY, flexDirection: "column" }, [...head, ...fixed, ...callNodes, ...after]);+ return box({ key: FLOW_BOX_ID, flexDirection: "column" }, [...head, ...fixed, ...callNodes, ...after]);}-__name(flowView, "flowView");// src/flow-controller.tsvar REDRAW_MS = 125;var STILL_TICK_MS = 1e3;var GONE_MS = 1e3;var LensFlow = class {- static {- __name(this, "LensFlow");- }state = initialFlow;/** Flow is on screen: set by its render; cleared by another tab, or by a redraw no render answered. */shown = false;@@ -3327,8 +2954,8 @@ var LensFlow = class {pending;ticker;happy;- setReducedMotion(on) {- this.still = on;+ setReducedMotion(reduced) {+ this.still = reduced;}/** Another tab is shown, or the pane is gone: nothing of Flow is on screen. */hide() {@@ -3409,14 +3036,12 @@ var LensFlow = class {function fromTurnComplete(e) {return e.agentId === void 0 ? { type: "turnCompleted" } : null;}-__name(fromTurnComplete, "fromTurnComplete");var FILE_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write"]);function fileTarget(e, repoRoot) {if (!FILE_TOOLS.has(e.tool) || repoRoot === null || typeof e.file_path !== "string") return null;const windows = /^[A-Za-z]:[\\/]|^[\\/]{2}/.test(repoRoot);return relativeTo(e.file_path, repoRoot, windows);}-__name(fileTarget, "fileTarget");var EDIT_TOOLS = /* @__PURE__ */ new Set(["Edit", "Write"]);var STANDING = /^\[repowise\] .+? is governed by a standing decision: (.+?)(?: because .*)?\.$/;var MINED = /^\[repowise\] .+? has a decision recorded in it, mined but not reviewed: (.+?)(?: because .*)?\.$/;@@ -3424,7 +3049,6 @@ var FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, lfunction stripConfirmed(line2) {return line2.replace(/ \(confirmed across \d+ sessions\)\.$/, ".");}-__name(stripConfirmed, "stripConfirmed");function notesFromAugment(additionalContext) {if (!Array.isArray(additionalContext)) return [];const notes = [];@@ -3442,7 +3066,6 @@ function notesFromAugment(additionalContext) {}return notes;}-__name(notesFromAugment, "notesFromAugment");function savingsTotals(s) {return {tokens: s.saved_input_tokens,@@ -3450,7 +3073,6 @@ function savingsTotals(s) {usd: s.priced_input_savings_usd};}-__name(savingsTotals, "savingsTotals");function savingsSince(now, base) {const tokens = now.tokens - base.tokens;const inferredTokens = now.inferredTokens - base.inferredTokens;@@ -3458,7 +3080,6 @@ function savingsSince(now, base) {if (tokens < 0 || inferredTokens < 0 || usd < 0) return null;return { tokens, inferredTokens: Math.min(inferredTokens, tokens), usd };}-__name(savingsSince, "savingsSince");var OBSERVED_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write", "Grep", "Glob"]);var OWN_CALL_PREFIX2 = "toolu_plugin_";function absolutePath(raw, ctx) {@@ -3466,45 +3087,37 @@ function absolutePath(raw, ctx) {const joined = absolute ? raw : `${ctx.cwd.replace(/[\\/]+$/, "")}/${raw.replace(/^\.[\\/]/, "")}`;return ctx.isWindows ? joined.replace(/\\/g, "/") : joined;}-__name(absolutePath, "absolutePath");function absoluteKey(raw, ctx) {return normalizeRepoPath(absolutePath(raw, ctx), ctx.isWindows);}-__name(absoluteKey, "absoluteKey");function relativeTo(absolute, root, isWindows) {const rootKey = normalizeRepoPath(root, isWindows);const slashed = isWindows ? absolute.replace(/\\/g, "/") : absolute;if (!normalizeRepoPath(slashed, isWindows).startsWith(`${rootKey}/`)) return null;return slashed.slice(rootKey.length + 1);}-__name(relativeTo, "relativeTo");function filenamesOf(out) {const names2 = typeof out.result === "object" ? out.result.filenames : void 0;return Array.isArray(names2) ? names2.filter((v) => typeof v === "string") : [];}-__name(filenamesOf, "filenamesOf");function isContentGrep(tool, out) {return tool === "Grep" && typeof out.result === "object" && out.result.mode === "content";}-__name(isContentGrep, "isContentGrep");function searchAction(out, ctx) {return { type: "search", paths: filenamesOf(out).map((f) => absoluteKey(f, ctx)) };}-__name(searchAction, "searchAction");function fileAction(e, ctx) {const raw = e["file_path"];if (typeof raw !== "string") return null;const path = absoluteKey(raw, ctx);return e.tool === "Read" ? { type: "read", path } : { type: "edit", path };}-__name(fileAction, "fileAction");function fromToolCall(e, outcome, ctx) {if (!OBSERVED_TOOLS.has(e.tool) || e.tool_use_id?.startsWith(OWN_CALL_PREFIX2)) return null;const out = outcome ?? {};if (out.isError === true || isContentGrep(e.tool, out)) return null;return e.tool === "Grep" || e.tool === "Glob" ? searchAction(out, ctx) : fileAction(e, ctx);}-__name(fromToolCall, "fromToolCall");function touchedPath(e, cwd2, repoRoot) {const raw = typeof e.file_path === "string" ? e.file_path : e["notebook_path"];if (typeof raw !== "string") return null;@@ -3514,14 +3127,13 @@ function touchedPath(e, cwd2, repoRoot) {const abs = absolutePath(raw, { cwd: base, isWindows });return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;}-__name(touchedPath, "touchedPath");// src/model/story.tsvar NO_STORY = { searched: [], opened: [], edited: [] };-var nameOf = /* @__PURE__ */ __name((path) => path.slice(path.lastIndexOf("/") + 1), "nameOf");+var nameOf = (path) => path.slice(path.lastIndexOf("/") + 1);var FILE_KINDS = /* @__PURE__ */ new Set(["read", "edit", "search"]);-var isFileStep = /* @__PURE__ */ __name((a) => !a.isError && FILE_KINDS.has(a.kind), "isFileStep");-var isOpen = /* @__PURE__ */ __name((a) => a.kind === "read" || a.kind === "edit", "isOpen");+var isFileStep = (a) => !a.isError && FILE_KINDS.has(a.kind);+var isOpen = (a) => a.kind === "read" || a.kind === "edit";function storyTurn(state2) {for (let i = state2.turns.length - 1; i >= 0; i--) {const t = state2.turns[i];@@ -3529,11 +3141,9 @@ function storyTurn(state2) {}return null;}-__name(storyTurn, "storyTurn");function argOf(a, keys) {return a.args.find(([k]) => keys.includes(k))?.[1] ?? "";}-__name(argOf, "argOf");function openedOf(steps) {const seen = /* @__PURE__ */ new Map();for (const a of steps) {@@ -3543,7 +3153,6 @@ function openedOf(steps) {}return [...seen.values()];}-__name(openedOf, "openedOf");function storyFromFlow(state2) {const turn = storyTurn(state2);if (turn === null) return NO_STORY;@@ -3554,7 +3163,6 @@ function storyFromFlow(state2) {edited: steps.filter((a) => a.kind === "edit" && a.paths[0] !== void 0).map((a) => ({ name: nameOf(a.paths[0]), lines: a.lines }))};}-__name(storyFromFlow, "storyFromFlow");function litFromFlow(state2) {const turn = storyTurn(state2);if (turn === null) return NO_LIT;@@ -3571,15 +3179,13 @@ function litFromFlow(state2) {current: opened.at(-1)?.path ?? null};}-__name(litFromFlow, "litFromFlow");-var rel = /* @__PURE__ */ __name((abs, root, ci) => relativeTo(abs, root, ci), "rel");+var rel = (abs, root, ci) => relativeTo(abs, root, ci);function litFromTrail(trail, root, caseInsensitive) {- const all = /* @__PURE__ */ __name((paths) => paths.map((p) => rel(p, root, caseInsensitive)).filter((p) => p !== null), "all");+ const all = (paths) => paths.map((p) => rel(p, root, caseInsensitive)).filter((p) => p !== null);const reads = all(trail.reads);const edit = trail.edit === null ? null : rel(trail.edit, root, caseInsensitive);return { hits: all(trail.hits), reads, named: [], importers: [], edits: edit === null ? [] : [edit], edit, current: reads.at(-1) ?? null };}-__name(litFromTrail, "litFromTrail");function storyFromTrail(trail) {return {searched: trail.searches === 0 ? [] : [{ pattern: "", hits: trail.hits.length }],@@ -3587,14 +3193,12 @@ function storyFromTrail(trail) {edited: trail.edit === null ? [] : [{ name: nameOf(trail.edit), lines: null }]};}-__name(storyFromTrail, "storyFromTrail");function combineCallers(answers, edited) {const ready = answers.filter((c) => c.status === "ready");if (ready.length > 0) return { status: "ready", paths: [...new Set(ready.flatMap((c) => c.paths))].filter((p) => !edited.has(p.toLowerCase())) };if (answers.some((c) => c.status === "loading")) return { status: "loading" };return answers.length > 0 ? { status: "failed" } : null;}-__name(combineCallers, "combineCallers");function withImporters(lit, importersOf) {if (lit.edit === null) return { lit, reach: null };const answers = lit.edits.map(importersOf).filter((c) => c !== null);@@ -3603,11 +3207,10 @@ function withImporters(lit, importersOf) {const importers = callers.status === "ready" ? callers.paths : [];return { lit: { ...lit, importers }, reach: { edit: lit.edit, callers, opened: new Set(lit.reads.map((p) => p.toLowerCase())) } };}-__name(withImporters, "withImporters");// src/model/inspect.tsvar KNOWS_NOTHING = { context: null, tests: null, namedBy: null };-var key = /* @__PURE__ */ __name((p) => p.toLowerCase(), "key");+var key = (p) => p.toLowerCase();function litPaths(lit) {const edits = [...lit.edits].reverse();const order = [...edits, ...lit.reads, ...lit.importers, ...lit.named];@@ -3618,16 +3221,14 @@ function litPaths(lit) {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");+var nameOf2 = (p) => p.slice(p.lastIndexOf("/") + 1);+var has = (paths, p) => paths.some((x) => key(x) === key(p));function whyLit(path, lit, story, knows) {const edit = has(lit.edits, path) ? story.edited.find((e) => e.name === nameOf2(path)) ?? { lines: null } : null;return {@@ -3637,7 +3238,6 @@ function whyLit(path, lit, story, knows) {namedBy: knows.namedBy};}-__name(whyLit, "whyLit");function contextOf(contexts, path) {const exact = contexts[path];if (exact !== void 0) return exact;@@ -3645,7 +3245,6 @@ function contextOf(contexts, 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;@@ -3655,7 +3254,6 @@ function knowsOf(path, contexts, flow2) {namedBy: flow2 === null ? null : flow2.named[pathKey(path)]?.tool ?? null};}-__name(knowsOf, "knowsOf");// ../api-client/src/blast-radius.tsasync function analyzeBlastRadius(repoId, body) {@@ -3664,7 +3262,6 @@ async function analyzeBlastRadius(repoId, body) {body);}-__name(analyzeBlastRadius, "analyzeBlastRadius");// ../api-client/src/code-health.tsasync function getHealthMap(repoId, opts = {}) {@@ -3675,7 +3272,6 @@ async function getHealthMap(repoId, opts = {}) {counts: opts.counts});}-__name(getHealthMap, "getHealthMap");// src/model/trail.tsvar MAX_READS = 200;@@ -3694,7 +3290,6 @@ function withRead(state2, path) {if (reads.length <= MAX_READS) return { ...state2, reads };return { ...state2, reads: reads.slice(reads.length - MAX_READS), readsCapped: true };}-__name(withRead, "withRead");function reduceTrail(state2, action) {switch (action.type) {case "read":@@ -3712,26 +3307,23 @@ function reduceTrail(state2, action) {return action.edits === state2.edits ? { ...state2, callers: action.callers } : state2;}}-__name(reduceTrail, "reduceTrail");// src/views/mapSvg.tsvar SVG_CHARS = 131072;var DESKTOP_MAX_COLUMNS = 160;var DESKTOP_MAX_ROWS = 45;-var color = /* @__PURE__ */ __name((c) => `#${c.toString(16).padStart(6, "0")}`, "color");-var escape = /* @__PURE__ */ __name((s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">"), "escape");+var color = (c) => `#${c.toString(16).padStart(6, "0")}`;+var escape = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");function desktopSize(size) {return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };}-__name(desktopSize, "desktopSize");-var textAt = /* @__PURE__ */ __name((l, fill) => `<text x="${l.col}" y="${2 * l.row + 1.6}" fill="${color(fill)}">${escape(l.text)}</text>`, "textAt");+var textAt = (l, fill) => `<text x="${l.col}" y="${2 * l.row + 1.6}" fill="${color(fill)}">${escape(l.text)}</text>`;function svgLabels(layout, overlay) {const pal = MAP_PALETTES[layout.style.theme];const folder = layout.style.health ? LABEL_FG : pal.folder;const names2 = overlay.names.map((n) => textAt(n, n.color === TERMINAL_DEFAULT ? pal.read : n.color));return [...layout.labels.map((l) => textAt(l, folder)), ...names2].join("");}-__name(svgLabels, "svgLabels");function mapSvg(layout, overlay) {const { width: width2, height } = layout;const { pixels } = framePixels(layout, overlay);@@ -3752,20 +3344,18 @@ function mapSvg(layout, overlay) {const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width2} ${height}" shape-rendering="crispEdges"><g stroke-width="1" fill="none">${paths}</g><g font-family="monospace" font-size="1.7">${svgLabels(layout, overlay)}</g></svg>`;}-__name(mapSvg, "mapSvg");function svgPaneView(layout, overlay, parts) {const source = mapSvg(layout, overlay);const picture = source.length <= SVG_CHARS ? svg(source, mapAlt(layout.drawn.length)) : text(fit(MAP_COPY.tooLarge, layout.columns), { dimColor: true, wrap: "truncate-end" });return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(parts, layout.style, layout.columns)]);}-__name(svgPaneView, "svgPaneView");// src/map-controller.tsvar MAP_CAP = 4e3;var MAP_TIMEOUT_MS = 15e3;var CALLERS_TIMEOUT_MS = 2e4;var CALLERS_DEPTH = 1;-var NO_TURN = /* @__PURE__ */ __name(() => ({ lit: NO_LIT, story: NO_STORY }), "NO_TURN");+var NO_TURN = () => ({ lit: NO_LIT, story: NO_STORY });function scopeFacts(layout, data, repo, offMap) {const whole = layout.root === null;return {@@ -3779,14 +3369,12 @@ function scopeFacts(layout, data, repo, offMap) {zoom: layout.root};}-__name(scopeFacts, "scopeFacts");-var cacheKey = /* @__PURE__ */ __name((k) => `${k.root ?? ""}|${k.columns}|${k.rows}|${k.style.theme}|${k.style.health}`, "cacheKey");+var cacheKey = (k) => `${k.root ?? ""}|${k.columns}|${k.rows}|${k.style.theme}|${k.style.health}`;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;@@ -3794,11 +3382,7 @@ function folderOf(layout, path) {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");- }trail = initialTrail;disposed = false;/** One band row the map asks for (the pane could not open), until the turn ends. */@@ -3911,8 +3495,8 @@ var LensMap = class {return this.band;}/** The person's `prefersReducedMotion` setting: resting frames only. */- setReducedMotion(on) {- this.reducedMotion = on;+ setReducedMotion(reduced) {+ this.reducedMotion = reduced;}dispose() {this.disposed = true;@@ -4077,9 +3661,9 @@ var LensMap = class {}/** Whether an animation would show anything: a map on screen, motion allowed, a ripple with somewhere to go. */canAnimate(kind) {- const on = this.drawn;- if (this.reducedMotion || on === null) return false;- return kind === "flash" || rippleRadius(on.layout, resolveLit(on.layout, this.lighting().lit)) > 0;+ const drawn = this.drawn;+ if (this.reducedMotion || drawn === null) return false;+ return kind === "flash" || rippleRadius(drawn.layout, resolveLit(drawn.layout, this.lighting().lit)) > 0;}/*** A flash or a ripple when it would show; otherwise (reduced motion, nothing@@ -4091,33 +3675,29 @@ var LensMap = class {}/** The current trail on the drawn map at one step, or null once the map is off screen. */frame(step2) {- const on = this.drawn;+ const drawn = this.drawn;const anim = mapStep(step2);- if (on === null || anim === void 0) return null;- 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 };+ if (drawn === null || anim === void 0) return null;+ const cells = frameCells(drawn.layout, resolveLit(drawn.layout, this.lighting().lit, this.selected), anim);+ return { key: MAP_KEY, cells, columns: drawn.layout.columns, rows: drawn.layout.rows };}};function mapStep(step2) {return step2 !== void 0 && (step2.kind === "flash" || step2.kind === "ripple") ? step2 : void 0;}-__name(mapStep, "mapStep");// src/model/ask.tsvar TAB_BAR = ["flow", "map", "ask", "recap"];function askRoute(question) {return /^\s*why\b/i.test(question) ? { tool: "get_why", args: { query: question } } : { tool: "get_answer", args: { question } };}-__name(askRoute, "askRoute");function askReply(tool, reply) {const body = typeof reply === "object" && reply !== null ? reply : {};return tool === "get_why" ? { tool, reply: body } : { tool, reply: body };}-__name(askReply, "askReply");function mayHaveUsedModel(a) {return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";}-__name(mayHaveUsedModel, "mayHaveUsedModel");function lensCommand(args, tabs = TAB_BAR) {const [word = "", ...rest] = args.trim().split(/\s+/);const question = rest.join(" ");@@ -4126,11 +3706,9 @@ function lensCommand(args, tabs = TAB_BAR) {const tab = tabs.find((t) => t === named2);return { tab: tab ?? null, question: null };}-__name(lensCommand, "lensCommand");function whyDraft(decision) {return `why ${decision}`;}-__name(whyDraft, "whyDraft");// src/model/review.tsvar initialReview = { edited: false, outcome: { phase: "none" }, decision: null };@@ -4150,15 +3728,12 @@ function reduceReview(state2, action) {return state2.decision === action.title ? state2 : { ...state2, decision: action.title };}}-__name(reduceReview, "reduceReview");function emptyDiff(risk) {return risk.status === "nothing_to_score" || risk.health_delta?.scope?.changed === 0;}-__name(emptyDiff, "emptyDiff");function reviewable(risk) {return risk.error === void 0 && !emptyDiff(risk);}-__name(reviewable, "reviewable");var WRITE_TOOLS = /* @__PURE__ */ new Set(["Edit", "MultiEdit", "Write", "NotebookEdit"]);function isFileEdit(e, result) {if (typeof e.tool !== "string" || !WRITE_TOOLS.has(e.tool)) return false;@@ -4167,16 +3742,13 @@ function isFileEdit(e, result) {const r = result;return r.deny === void 0 && r.isError !== true;}-__name(isFileEdit, "isFileEdit");function shouldReview(e, edits) {if (e.agentId !== void 0 || edits === 0) return false;return e.isAborted !== true && e.reason !== "aborted" && e.reason !== "error";}-__name(shouldReview, "shouldReview");function isRetryable(action) {return action.type === "reviewFailed" && action.reason !== "timeout";}-__name(isRetryable, "isRetryable");function testsToRun(risk) {const block = risk.impacted_tests;const tests = block?.tests_to_run ?? [];@@ -4189,7 +3761,6 @@ function testsToRun(risk) {measured: block.basis === "measured"};}-__name(testsToRun, "testsToRun");// src/model/session.tsvar initialSession = {@@ -4215,12 +3786,10 @@ function hintFor(mode, liteReason) {if (mode === "lite") return liteReason ?? "no-server";return mode;}-__name(hintFor, "hintFor");function clearedConversation(state2) {const { mode, freshness, hint, hintsShown, repoRoot, contexts } = state2;return { ...initialSession, mode, freshness, hint, hintsShown, repoRoot, contexts, pane: { tab: state2.pane.tab, draft: "" } };}-__name(clearedConversation, "clearedConversation");function reduce(state2, action) {switch (action.type) {case "discovered": {@@ -4278,7 +3847,6 @@ function reduce(state2, action) {return reduceTurn(state2, action);}}-__name(reduce, "reduce");function reduceTurn(state2, action) {const review = reduceReview(state2.review, action);const compacted = action.type === "turnStarted" ? false : state2.compacted;@@ -4286,7 +3854,6 @@ function reduceTurn(state2, action) {if (review === state2.review && compacted === state2.compacted && lastReview === state2.lastReview) return state2;return { ...state2, review, compacted, lastReview };}-__name(reduceTurn, "reduceTurn");function surfacedDecisions(state2) {const seen = /* @__PURE__ */ new Map();for (const notes of Object.values(state2.notes)) {@@ -4294,7 +3861,6 @@ function surfacedDecisions(state2) {}return [...seen].map(([title, reviewed]) => ({ title, reviewed }));}-__name(surfacedDecisions, "surfacedDecisions");// src/views/review.tsvar PRESS = { tests: "lens-review-tests", why: "lens-review-why", details: "lens-review-details" };@@ -4303,12 +3869,10 @@ var NOT_REPORTED = { words: HEALTH_NOT_REPORTED, short: HEALTH_NOT_REPORTED };function notComparedWords(hd) {return { words: notCompared(hd.explanation.replace(/\.$/, "")), short: notCompared("") };}-__name(notComparedWords, "notComparedWords");function clearWords(hd) {if (hd.resolved === 0) return { words: noNewFindings(hd.scope?.analyzed ?? 0), short: NO_NEW_FINDINGS };return { words: healthImproved(hd.resolved), short: improvedShort(hd.resolved), color: DARK.success };}-__name(clearWords, "clearWords");var FINDINGS_TONE = {review_required: { required: true, color: DARK.error },review_recommended: { required: false, color: DARK.warning }@@ -4320,7 +3884,6 @@ function findingsWords(d, hd) {if (tone === void 0) return { words, short: PARTLY_COMPARED };return { words, short: newFindings(hd.findings_total, tone.required), color: tone.color };}-__name(findingsWords, "findingsWords");function health(risk) {const d = risk.directive;const hd = risk.health_delta;@@ -4329,7 +3892,6 @@ function health(risk) {if (d.status === "clear_in_analyzed_scope") return clearWords(hd);return findingsWords(d, hd);}-__name(health, "health");function overlap(risk) {const block = risk.branch_overlap;const branches = block?.branches ?? [];@@ -4337,15 +3899,12 @@ function overlap(risk) {const files = [...new Set(branches.flatMap((b) => (b.files ?? []).map((f) => f.file)))];return { branches: branches.map((b) => b.branch), files, more: block?.truncated === true };}-__name(overlap, "overlap");function isClear(risk) {return risk.directive?.status === "clear_in_analyzed_scope";}-__name(isClear, "isClear");function header2(risk, changed) {return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;}-__name(header2, "header");function findingSegments(hd) {const rows = hd?.top_findings ?? [];const segments = rows.map(findingLine);@@ -4353,22 +3912,18 @@ function findingSegments(hd) {if (more > 0) segments.push(moreFindings(more));return segments;}-__name(findingSegments, "findingSegments");function scopeSegments(hd) {if (hd?.status !== "partial" || hd.scope === void 0) return [];return [partialScope(hd.scope.analyzed, hd.scope.changed, hd.skipped?.by_reason ?? {})];}-__name(scopeSegments, "scopeSegments");function testSegments(risk) {const tests = testsToRun(risk);return tests === null ? [] : [testsLine(tests)];}-__name(testSegments, "testSegments");function overlapSegments(risk) {const shared = overlap(risk);return shared === null ? [] : [`Branches: ${overlapLine(shared.branches, shared.files, shared.more)}`];}-__name(overlapSegments, "overlapSegments");function cardSegments(risk) {if (isClear(risk) && overlap(risk) === null) return [header2(risk, null), `health: ${health(risk).words}`];const hd = risk.health_delta;@@ -4382,13 +3937,11 @@ function cardSegments(risk) {...overlapSegments(risk)];}-__name(cardSegments, "cardSegments");function doneText(risk) {if (risk.error !== void 0) return reviewFailed(risk.error);if (emptyDiff(risk)) return null;return cardSegments(risk).join(" · ");}-__name(doneText, "doneText");function reviewText(outcome) {switch (outcome.phase) {case "none":@@ -4400,7 +3953,6 @@ function reviewText(outcome) {return doneText(outcome.risk);}}-__name(reviewText, "reviewText");function buttons(risk, decision) {const out = [];if (testsToRun(risk) !== null) out.push(button(PRESS.tests, "1", RUN_TESTS));@@ -4408,16 +3960,13 @@ function buttons(risk, decision) {if (risk.directive !== void 0) out.push(button(PRESS.details, "3", DETAILS));return out;}-__name(buttons, "buttons");var GAP2 = 2;function buttonCells(pressable) {return pressable.reduce((n, b) => n + (b.type === "Button" ? b.props.label.length + 3 : 0) + GAP2, 0);}-__name(buttonCells, "buttonCells");function quietInBand(risk, decision) {return isClear(risk) && testsToRun(risk) === null && overlap(risk) === null && decision === null;}-__name(quietInBand, "quietInBand");function summaryParts(risk, room) {const h = health(risk);const words = fit(`review · health: ${h.short}`, room);@@ -4427,7 +3976,6 @@ function summaryParts(risk, room) {if (tail !== "" && room - words.length >= tail.length) parts.push(text(tail, { dimColor: true }));return parts;}-__name(summaryParts, "summaryParts");function resultRow(risk, columns, decision) {if (!reviewable(risk) || quietInBand(risk, decision)) return null;const pressable = buttons(risk, decision);@@ -4437,30 +3985,25 @@ function resultRow(risk, columns, decision) {...pressable]);}-__name(resultRow, "resultRow");function reviewBandRow(outcome, columns, decision = null) {if (outcome.phase === "reviewing") return text(fit(REVIEWING, columns), { dimColor: true, wrap: "truncate-end" });return outcome.phase === "done" ? resultRow(outcome.risk, columns, decision) : null;}-__name(reviewBandRow, "reviewBandRow");function directiveRows(outcome) {if (outcome.phase !== "done" || outcome.risk.directive === void 0) return null;return directiveLines(outcome.risk.directive);}-__name(directiveRows, "directiveRows");function runTestsText(outcome) {if (outcome.phase !== "done") return null;const tests = testsToRun(outcome.risk);return tests === null ? null : runTestsPrompt(tests);}-__name(runTestsText, "runTestsText");function withCard(result, answer, card) {if (typeof result !== "object" || result === null) return result;const r = result;if (typeof r.text !== "string") return result;return { ...r, text: r.text === answer ? card : `${r.text} · ${card}` };}-__name(withCard, "withCard");// src/views/brief.tsvar BRIEF_PRESS = "lens-brief";@@ -4476,7 +4019,6 @@ function listWithin(head, items, room) {}return fit(`${head} and ${cut.length} more`, room);}-__name(listWithin, "listWithin");function reviewItems(state2) {const risk = state2.lastReview;if (risk === null) return [];@@ -4489,7 +4031,6 @@ function reviewItems(state2) {...shared === null ? [] : [overlapLine(shared.branches, shared.files, shared.more)]];}-__name(reviewItems, "reviewItems");function briefText(state2) {const sections = [[BRIEF_COPY.files, [...state2.touched]],@@ -4506,7 +4047,6 @@ ${listWithin(head, items, Math.max(0, room))}`;});return brief;}-__name(briefText, "briefText");function briefBandRow(state2, columns, besideReview = false) {if (!state2.compacted || briefText(state2) === null) return null;return box({ key: "lens-brief", flexDirection: "row", columnGap: 2 }, [@@ -4514,7 +4054,6 @@ function briefBandRow(state2, columns, besideReview = false) {button(BRIEF_PRESS, besideReview ? "4" : "1", BRIEF_COPY.button)]);}-__name(briefBandRow, "briefBandRow");// src/views/band.tsvar MAX_BAND_ROWS = 2;@@ -4525,7 +4064,6 @@ function bandRows(state2, columns = Number.POSITIVE_INFINITY) {if (state2.savings !== null) rows.push(savingsLine(state2.savings, columns));return rows.slice(0, MAX_BAND_ROWS);}-__name(bandRows, "bandRows");function bandView(state2, viewport, extra = []) {if (viewport.hasSurvey) return null;const review = reviewBandRow(state2.review.outcome, viewport.columns, state2.review.decision);@@ -4535,7 +4073,6 @@ function bandView(state2, viewport, extra = []) {const nodes = own.map((row2) => text(fit(row2, viewport.columns), { dimColor: true, wrap: "truncate-end" }));return box({ key: "lens-band", flexDirection: "column" }, [...nodes, ...actions]);}-__name(bandView, "bandView");// src/views/margin.tsvar MAX_MARGIN_LINES = 2;@@ -4546,46 +4083,41 @@ function marginView(notes) {notes.slice(0, MAX_MARGIN_LINES).map((n) => text(` ${marginLine(n)}`, { dimColor: true, wrap: "truncate-end" })));}-__name(marginView, "marginView");// src/views/answer.tsvar LIST_ROWS = 5;var ROW_CHARS = 300;-var code = /* @__PURE__ */ __name((s) => `\`${s.replace(/`/g, "'")}\``, "code");-var line = /* @__PURE__ */ __name((s, chars = ROW_CHARS) => fit(s.replace(/\s+/g, " ").trim(), chars), "line");+var code = (s) => `\`${s.replace(/`/g, "'")}\``;+var line = (s, chars = ROW_CHARS) => fit(s.replace(/\s+/g, " ").trim(), chars);function ids(refs) {const found = (refs ?? []).map((r) => r.id).filter((id) => typeof id === "string");return found.length === 0 ? "" : ` · ${found.map(code).join(" ")}`;}-__name(ids, "ids");function list(head, rows, row2, total2) {if (rows === void 0 || rows.length === 0) return [];const shown = rows.slice(0, LIST_ROWS);const more = Math.max(total2 ?? 0, rows.length) - shown.length;return [`**${head}**`, ...shown.map((r) => `- ${row2(r)}`), ...more > 0 ? [`- ${moreRows(more)}`] : []];}-__name(list, "list");function answerHead(a) {const parts = [`**${a.degraded === void 0 ? PANE_COPY.fromModel : PANE_COPY.fromIndex}**`];if (a.confidence !== void 0) parts.push(`confidence ${a.confidence}`);if (a.retrieval_quality !== void 0) parts.push(`retrieval ${a.retrieval_quality}`);return parts.join(" · ");}-__name(answerHead, "answerHead");function answerMarkdown(a) {const cited = a.citations ?? [];const evidence = cited.length === 0 ? PANE_COPY.noEvidence : `evidence: ${cited.map(code).join(", ")}`;return [answerHead(a), a.answer ?? "", evidence];}-__name(answerMarkdown, "answerMarkdown");-var decisionRow = /* @__PURE__ */ __name((d) => {+var decisionRow = (d) => {const facts = [d.status, d.authority, d.confidence === null || d.confidence === void 0 ? void 0 : `confidence ${d.confidence}`].filter((f) => f !== void 0).join(" · ");const id = d.id === void 0 ? "" : ` · ${code(d.id)}`;const body = d.decision === void 0 ? "" : `: ${line(d.decision)}`;return `**${line(d.title, 120)}**${facts === "" ? "" : ` (${facts})`}${id}${body}`;-}, "decisionRow");-var commitRow = /* @__PURE__ */ __name((c) => `${code(c.sha ?? "?")} ${line(c.message ?? "", 160)}${c.date === void 0 ? "" : ` (${c.date.slice(0, 10)})`}${ids(c.evidence_refs)}`, "commitRow");-var rationaleRow = /* @__PURE__ */ __name((r) => `${code(r.lines === void 0 ? r.path : `${r.path}:${r.lines[0]}`)} ${line(r.comment)}${ids(r.evidence_refs)}`, "rationaleRow");+};+var commitRow = (c) => `${code(c.sha ?? "?")} ${line(c.message ?? "", 160)}${c.date === void 0 ? "" : ` (${c.date.slice(0, 10)})`}${ids(c.evidence_refs)}`;+var rationaleRow = (r) => `${code(r.lines === void 0 ? r.path : `${r.path}:${r.lines[0]}`)} ${line(r.comment)}${ids(r.evidence_refs)}`;function whyMarkdown(w) {const from = `**${PANE_COPY.fromIndex}**`;const head = w.answer_basis === void 0 ? from : `${from} · basis ${w.answer_basis}`;@@ -4598,7 +4130,6 @@ function whyMarkdown(w) {...list("Rationale in the code", w.code_rationale, rationaleRow, w.code_rationale_total)];}-__name(whyMarkdown, "whyMarkdown");function replyMarkdown(question, a) {const body = a.tool === "get_answer" ? answerMarkdown(a.reply) : whyMarkdown(a.reply);const text2 = [`> ${line(question, 200)}`, ...body].join("\n\n");@@ -4608,14 +4139,12 @@ function replyMarkdown(question, a) {_${askCut(ASK_CHARS)}_`;return `${text2.slice(0, ASK_CHARS - note.length).trimEnd()}${note}`;}-__name(replyMarkdown, "replyMarkdown");// src/views/pane.tsfunction tabBar(flowOn2) {return flowOn2 ? TAB_BAR : TAB_BAR.filter((t) => t !== "flow");}-__name(tabBar, "tabBar");-var tabPress = /* @__PURE__ */ __name((tab) => `lens-tab-${tab}`, "tabPress");+var tabPress = (tab) => `lens-tab-${tab}`;var ASK_KEY = "lens-ask";var TAB_ROWS = 1;function tabsView(current, tabs = TAB_BAR) {@@ -4624,8 +4153,7 @@ function tabsView(current, tabs = TAB_BAR) {tabs.map((tab, i) => button(tabPress(tab), String(i + 1), PANE_COPY.tabs[tab], tab !== current)));}-__name(tabsView, "tabsView");-var dim = /* @__PURE__ */ __name((line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" }), "dim");+var dim = (line2, columns) => text(fit(line2, columns), { dimColor: true, wrap: "truncate-end" });function askStatus(state2, columns) {const ask = state2.ask;switch (ask.phase) {@@ -4643,7 +4171,6 @@ function askStatus(state2, columns) {return [markdown(replyMarkdown(ask.question, ask.answer))];}}-__name(askStatus, "askStatus");function askView(state2, columns) {const field = input({key: ASK_KEY,@@ -4655,13 +4182,11 @@ function askView(state2, columns) {});return box({ key: "lens-ask-tab", flexDirection: "column" }, [field, ...askStatus(state2, columns)]);}-__name(askView, "askView");function overlapWords(risk) {const shared = overlap(risk);if (shared !== null) return overlapLine(shared.branches, shared.files, shared.more);return risk.branch_overlap === void 0 ? RECAP_COPY.notReported : RECAP_COPY.noOverlap;}-__name(overlapWords, "overlapWords");function reviewRows(state2) {const risk = state2.lastReview;if (risk === null) return [[RECAP_COPY.review, RECAP_COPY.noReview]];@@ -4676,12 +4201,10 @@ function reviewRows(state2) {[RECAP_COPY.overlap, overlapWords(risk)]];}-__name(reviewRows, "reviewRows");function savedRow(state2) {if (state2.savings !== null) return savingsLine(state2.savings, Number.POSITIVE_INFINITY);return state2.mode === "full" ? RECAP_COPY.noSavings : RECAP_COPY.savingsNeedServer;}-__name(savedRow, "savedRow");function recapRows(state2, touched) {const decisions = surfacedDecisions(state2).map((d) => d.title);return [@@ -4691,7 +4214,6 @@ function recapRows(state2, touched) {[RECAP_COPY.decisions, decisions.length === 0 ? RECAP_COPY.noDecisions : decisionsSurfaced(decisions)]];}-__name(recapRows, "recapRows");function recapView(state2, touched, columns) {const rows = recapRows(state2, touched);const width2 = Math.max(...rows.map((r) => typeof r === "string" ? 0 : r[0].length)) + 2;@@ -4703,11 +4225,9 @@ function recapView(state2, touched, columns) {);return box({ key: "lens-recap", flexDirection: "column" }, [...drawn, dim(recapFooter(state2.modelAsks), columns)]);}-__name(recapView, "recapView");function paneView(tab, body, tabs = TAB_BAR) {return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab, tabs), body]);}-__name(paneView, "paneView");// src/views/spinner.tsfunction spinnerSuffix(state2) {@@ -4715,7 +4235,6 @@ function spinnerSuffix(state2) {const ctx = state2.contexts[state2.running.file];return ctx === void 0 ? null : spinnerLine(state2.running.file, ctx);}-__name(spinnerSuffix, "spinnerSuffix");// src/model/squeeze.tsvar MARKER = /^\[repowise#([0-9a-f]{12}): (\d+) lines omitted \(~(\d+) tokens\); restore: repowise expand \1\]$/;@@ -4723,8 +4242,7 @@ function markerOf(line2) {const m = MARKER.exec(line2.trim());return m === null ? null : { ref: m[1], lines: Number(m[2]), tokens: Number(m[3]) };}-__name(markerOf, "markerOf");-var isBlank = /* @__PURE__ */ __name((line2) => line2.trim() === "", "isBlank");+var isBlank = (line2) => line2.trim() === "";function trailingMarkers(lines) {let end = lines.length;const markers = [];@@ -4737,7 +4255,6 @@ function trailingMarkers(lines) {}return { kept: lines.slice(0, end), markers };}-__name(trailingMarkers, "trailingMarkers");var PYTEST_SUMMARY = /^=+ (.*\b(?:passed|failed|error|errors|skipped)\b.*) =+$/;var PYTEST_FAILED = /\b(\d+) failed\b/;var PYTEST_ERRORS = /\b(\d+) errors?\b/;@@ -4749,7 +4266,6 @@ function pytestCounts(line2) {if (m === null) return null;return { failed: Number(PYTEST_FAILED.exec(m[1])?.[1] ?? 0), errors: Number(PYTEST_ERRORS.exec(m[1])?.[1] ?? 0) };}-__name(pytestCounts, "pytestCounts");function runnerFailures(kept) {let cargo = 0;let go = 0;@@ -4763,7 +4279,6 @@ function runnerFailures(kept) {}return { failed: cargo + go, errors: 0 };}-__name(runnerFailures, "runnerFailures");function parseSqueeze(output) {const { kept, markers } = trailingMarkers(output.split(/\r?\n/));if (markers.length === 0) return null;@@ -4784,13 +4299,11 @@ function parseSqueeze(output) {refs: [...refs]};}-__name(parseSqueeze, "parseSqueeze");function bashText(output) {if (typeof output === "string") return output;const stdout = output?.stdout;return typeof stdout === "string" ? stdout : null;}-__name(bashText, "bashText");// src/views/squeeze.tsvar BAR_CELLS = 12;@@ -4798,11 +4311,9 @@ function squeezeBar(s, cells = BAR_CELLS) {const filled = Math.min(cells, Math.max(1, Math.round(cells * s.keptLines / Math.max(1, s.originalLines))));return `${"█".repeat(filled)}${"░".repeat(cells - filled)}`;}-__name(squeezeBar, "squeezeBar");function squeezeView(s) {return text(`${squeezeBar(s)} ${squeezeLine(s)}`, { dimColor: true, wrap: "truncate-end" });}-__name(squeezeView, "squeezeView");// src/register.tsvar PROCESS_TIMEOUT_MS = 5e3;@@ -4818,7 +4329,6 @@ var reducedMotion = false;function freshSession() {return flowOn ? initialSession : reduce(initialSession, { type: "tab", tab: "map" });}-__name(freshSession, "freshSession");var state = initialSession;var generation = 0;var running = false;@@ -4843,60 +4353,57 @@ var animator = new Animator();var ERROR_CELLS = 160;function bind($) {const host = {- session: { cwd: /* @__PURE__ */ __name(() => $.session.cwd(), "cwd") },+ session: { cwd: () => $.session.cwd() },fs: {- read: /* @__PURE__ */ __name((path) => $.fs.read(path), "read"),- exists: /* @__PURE__ */ __name((path) => $.fs.exists(path), "exists")+ read: (path) => $.fs.read(path),+ exists: (path) => $.fs.exists(path)},process: {- run: /* @__PURE__ */ __name((argv, cwd2) => $.process.run(argv, { cwd: cwd2, timeoutMs: PROCESS_TIMEOUT_MS }), "run")+ run: (argv, cwd2) => $.process.run(argv, { cwd: cwd2, timeoutMs: PROCESS_TIMEOUT_MS })},- http: /* @__PURE__ */ __name((url, init) => {+ http: (url, init) => {const request = {};if (init.method !== void 0) request.method = init.method;if (init.headers !== void 0) request.headers = init.headers;if (init.body !== void 0) request.body = init.body;return $.http.fetch(url, request);- }, "http"),+ },mcp: {- connect: /* @__PURE__ */ __name(async () => mcpConnected ||= (await $.mcp.connect(MCP_SERVER_KEY)).isConnected, "connect"),- server: /* @__PURE__ */ __name(async () => {+ connect: async () => mcpConnected ||= (await $.mcp.connect(MCP_SERVER_KEY)).isConnected,+ server: async () => {const r = await $.mcp.connect(MCP_SERVER_KEY);return r.isConnected && typeof r.server === "string" ? r.server : null;- }, "server"),- call: /* @__PURE__ */ __name((server, tool, args) => $.mcp.call(server, tool, args), "call")+ },+ call: (server, tool, args) => $.mcp.call(server, tool, args)}};const bound = {host,- 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((key2, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: key2, cells, columns, rows }), "blit"),+ blastLanded: (path, r) => flowBlast(bound, path, r),+ redraw: () => $.ui.invalidate("ui.render"),+ debug: (message) => $.ui.log(`lens: ${message}`, { to: "debug" }),+ blit: (key2, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: key2, cells, columns, rows }),// 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.- openPane: /* @__PURE__ */ __name((focus) => (focus ? null : state = reduce(state, { type: "tab", tab: "map" }), $.ui.open(+ openPane: (focus) => (focus ? null : state = reduce(state, { type: "tab", tab: "map" }), $.ui.open(focus ? { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS, focus: true } : { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS }- )), "openPane"),- closePane: /* @__PURE__ */ __name(() => $.ui.close({ id: PANE_ID }), "closePane")+ )),+ closePane: () => $.ui.close({ id: PANE_ID })};animator.use(bound);return bound;}-__name(bind, "bind");function mapRepo(d) {if (d.mode !== "full" || d.repo === void 0 || d.repoRoot === null) return null;return { id: d.repo.id, root: d.repoRoot, updatedAt: d.repo.updatedAt, caseInsensitive: isWindowsPath(d.repoRoot) };}-__name(mapRepo, "mapRepo");function dispatch(b, action) {const next = reduce(state, action);if (next === state) return;state = next;b.redraw();}-__name(dispatch, "dispatch");async function refreshOnce(b, gen) {const h = b.host;const found = await discover(h);@@ -4911,7 +4418,6 @@ async function refreshOnce(b, gen) {if (found.repo !== void 0) refreshSavings(b, found.repo.id, gen);map.setRepo(b, mapRepo(found));}-__name(refreshOnce, "refreshOnce");function refreshSavings(b, repoId, gen) {const now = Date.now();if (savingsBusy || now - savingsAskedAt < SAVINGS_COOLDOWN_MS) return;@@ -4929,7 +4435,6 @@ function refreshSavings(b, repoId, gen) {savingsBase = { repoId, totals };}).catch((err) => b.debug(`savings failed: ${String(err)}`)).finally(() => savingsBusy = false);}-__name(refreshSavings, "refreshSavings");function refresh(b) {latest = b;if (running) {@@ -4943,7 +4448,6 @@ function refresh(b) {if (dirty && latest !== null) refresh(latest);});}-__name(refresh, "refresh");async function onSessionStart($, e, next) {const b = bind($);try {@@ -4976,14 +4480,12 @@ async function onSessionStart($, e, next) {}return next(e);}-__name(onSessionStart, "onSessionStart");async function onTurnComplete($, e, next) {const b = bind($);noteTurnEnd(b, e);const result = await next(e);return reviewOn && shouldReview(e, editsThisTurn) ? withReview(b, e, result) : result;}-__name(onTurnComplete, "onTurnComplete");function noteTurnEnd(b, e) {try {const action = fromTurnComplete(e);@@ -4996,7 +4498,6 @@ function noteTurnEnd(b, e) {b.debug(`turn.complete failed: ${String(err)}`);}}-__name(noteTurnEnd, "noteTurnEnd");async function withReview(b, e, result) {try {const card = await finishReview(b);@@ -5006,7 +4507,6 @@ async function withReview(b, e, result) {return result;}}-__name(withReview, "withReview");async function fetchReview(b) {try {const risk = await callTool(b.host, "get_change_risk", {}, { timeoutMs: REVIEW_TIMEOUT_S * 1e3 });@@ -5017,7 +4517,6 @@ async function fetchReview(b) {return { type: "reviewFailed", reason: err instanceof Error && err.name === "TimeoutError" ? "timeout" : "error", message };}}-__name(fetchReview, "fetchReview");function startReview(b) {const review = { gen: reviewGeneration, covers: editsThisTurn, settled: false, outcome: fetchReview(b) };void review.outcome.then(() => {@@ -5026,24 +4525,20 @@ function startReview(b) {started2 = review;return review;}-__name(startReview, "startReview");function reviewAfterEdit(b) {editsThisTurn++;dispatch(b, { type: "fileEdited" });if (started2 !== null && started2.gen === reviewGeneration && !started2.settled) return;startReview(b);}-__name(reviewAfterEdit, "reviewAfterEdit");function coveringReview() {const s = started2;return s !== null && s.gen === reviewGeneration && s.covers === editsThisTurn ? s : null;}-__name(coveringReview, "coveringReview");async function outcomeOf(b, review, reused) {const action = await review.outcome;return reused && isRetryable(action) ? startReview(b).outcome : action;}-__name(outcomeOf, "outcomeOf");async function finishReview(b) {const gen = reviewGeneration;const reused = coveringReview();@@ -5054,7 +4549,6 @@ async function finishReview(b) {dispatch(b, action);return reviewText(state.review.outcome);}-__name(finishReview, "finishReview");async function onTurnStart($, e, next) {noteFlow(bind($), () => ({ type: "turnStarted", turnId: e.turnId ?? null, prompt: e.text ?? "", at: Date.now() }));try {@@ -5070,7 +4564,6 @@ async function onTurnStart($, e, next) {}return next(e);}-__name(onTurnStart, "onTurnStart");function pressRunTests($) {try {const prompt = runTestsText(state.review.outcome);@@ -5080,7 +4573,6 @@ function pressRunTests($) {bind($).debug(`run tests failed: ${String(err)}`);}}-__name(pressRunTests, "pressRunTests");function pressWhy($) {const b = bind($);try {@@ -5092,7 +4584,6 @@ function pressWhy($) {b.debug(`why failed: ${String(err)}`);}}-__name(pressWhy, "pressWhy");function pressBrief($) {const b = bind($);try {@@ -5104,7 +4595,6 @@ function pressBrief($) {b.debug(`brief failed: ${String(err)}`);}}-__name(pressBrief, "pressBrief");async function onSessionEnd($, e, next) {if (e.reason !== "clear") return next(e);const b = bind($);@@ -5127,7 +4617,6 @@ async function onSessionEnd($, e, next) {}return next(e);}-__name(onSessionEnd, "onSessionEnd");async function onPostCompact($, e, next) {try {dispatch(bind($), { type: "compacted" });@@ -5136,7 +4625,6 @@ async function onPostCompact($, e, next) {}return next(e);}-__name(onPostCompact, "onPostCompact");function startAsk(b, question) {const q = question.trim();if (q === "") return;@@ -5155,7 +4643,6 @@ function startAsk(b, question) {dispatch(b, { type: "askFailed", question: q, tool, message });});}-__name(startAsk, "startAsk");async function onAskInput($, e, next) {try {if (e.kind === "submit" && e.element === ASK_KEY) startAsk(bind($), e.value);@@ -5164,7 +4651,6 @@ async function onAskInput($, e, next) {}return next(e);}-__name(onAskInput, "onAskInput");function pressDetails($) {try {for (const row2 of directiveRows(state.review.outcome) ?? []) $.ui.log(row2, { to: "transcript" });@@ -5172,7 +4658,6 @@ function pressDetails($) {bind($).debug(`details failed: ${String(err)}`);}}-__name(pressDetails, "pressDetails");async function onBand($, e, next) {const theirs = await next(e);try {@@ -5195,7 +4680,6 @@ async function onBand($, e, next) {return theirs;}}-__name(onBand, "onBand");function fetchContext(b, file) {if (contextAsked.has(file)) return;contextAsked.add(file);@@ -5208,7 +4692,6 @@ function fetchContext(b, file) {b.debug(`context for ${file} failed: ${String(err)}`);});}-__name(fetchContext, "fetchContext");async function onToolCall($, e, next) {const b = bind($);const file = fileToolStarted(b, e);@@ -5227,20 +4710,16 @@ async function onToolCall($, e, next) {observeTrail($, b, e, result);return result;}-__name(onToolCall, "onToolCall");function flowPane(columns, rows) {const outcome = state.review.outcome;return { columns, rows, mode: state.mode, contexts: state.contexts, review: outcome.phase === "done" ? outcome.risk : null, light: theme === "light" };}-__name(flowPane, "flowPane");function flowBlast(b, path, r) {noteFlow(b, () => ({ type: "blastLanded", path, facts: blastFacts(path, r) }));}-__name(flowBlast, "flowBlast");function flowRoot() {return state.repoRoot ?? cwd;}-__name(flowRoot, "flowRoot");function noteFlow(b, action) {if (!flowOn) return;try {@@ -5250,7 +4729,6 @@ function noteFlow(b, action) {flowFailed(b, err);}}-__name(noteFlow, "noteFlow");function flowFailed(b, err) {try {b.debug(`flow failed: ${String(err)}`);@@ -5258,7 +4736,6 @@ function flowFailed(b, err) {flowOn = false;}}-__name(flowFailed, "flowFailed");function observeTrail($, b, e, result) {if (!OBSERVED_TOOLS.has(e.tool)) return;try {@@ -5278,7 +4755,6 @@ function observeTrail($, b, e, result) {b.debug(`tool.call observe failed: ${String(err)}`);}}-__name(observeTrail, "observeTrail");function fileToolStarted(b, e) {try {const file = fileTarget(e, state.repoRoot);@@ -5291,7 +4767,6 @@ function fileToolStarted(b, e) {return null;}}-__name(fileToolStarted, "fileToolStarted");function editLanded(b, e, result) {try {if (!isFileEdit(e, result)) return;@@ -5302,18 +4777,6 @@ function editLanded(b, e, result) {b.debug(`tool.call failed: ${String(err)}`);}}-__name(editLanded, "editLanded");-async function onToolCheck($, e, next) {- try {- if (isOwnLensCall(e, next.origin?.plugin)) {- return { decision: "allow", reason: "Repowise Lens: its own read-only index lookup" };- }- } catch (err) {- bind($).debug(`tool.check failed: ${String(err)}`);- }- return next(e);-}-__name(onToolCheck, "onToolCheck");async function onSpinner($, e, next) {let line2 = null;try {@@ -5325,14 +4788,12 @@ async function onSpinner($, e, next) {const theirs = typeof e.props.suffix === "string" ? e.props.suffix : "";return next({ ...e, props: { ...e.props, suffix: `${theirs} ${line2}` } });}-__name(onSpinner, "onSpinner");function below(elements, theirs, tree) {const ours = materialize(tree, elements);const box2 = elements["Box"];if (theirs === null || theirs === void 0 || box2 === void 0) return ours;return box2({ flexDirection: "column", children: [theirs, ours] });}-__name(below, "below");function squeezeOf(e) {const id = e.props.tool_use_id;const known = squeezes.get(id);@@ -5342,7 +4803,6 @@ function squeezeOf(e) {if (found !== null) squeezes.set(id, found);return found;}-__name(squeezeOf, "squeezeOf");async function onToolResult($, e, next) {const theirs = await next(e);try {@@ -5353,7 +4813,6 @@ async function onToolResult($, e, next) {return theirs;}}-__name(onToolResult, "onToolResult");async function onPostToolUse($, e, next) {const result = await next(e);try {@@ -5366,7 +4825,6 @@ async function onPostToolUse($, e, next) {}return result;}-__name(onPostToolUse, "onPostToolUse");async function onToolUse($, e, next) {const theirs = await next(e);try {@@ -5377,7 +4835,6 @@ async function onToolUse($, e, next) {return theirs;}}-__name(onToolUse, "onToolUse");async function onLensCommand($, e) {const b = bind($);try {@@ -5395,19 +4852,15 @@ async function onLensCommand($, e) {}return {};}-__name(onLensCommand, "onLensCommand");function tabPresses($, bar) {return Object.fromEntries(bar.map((tab) => [tabPress(tab), () => selectTab($, tab)]));}-__name(tabPresses, "tabPresses");function flowRowPresses($) {return Object.fromEntries(flowPresses(flow.state).map(([key2, id]) => [key2, () => pressFlow($, key2, id)]));}-__name(flowRowPresses, "flowRowPresses");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) {try {dispatch(bind($), { type: "tab", tab });@@ -5415,35 +4868,31 @@ function selectTab($, tab) {bind($).debug(`tab failed: ${String(err)}`);}}-__name(selectTab, "selectTab");var theme = "dark";function readTheme($) {$.config.list().then((rows) => {theme = themeOf(rows.find((r) => r.key === "theme")?.value);}).catch((err) => bind($).debug(`theme failed: ${String(err)}`));}-__name(readTheme, "readTheme");var TAB_BODIES = {- flow: /* @__PURE__ */ __name((b, e, rows) => flow.paneTree(b, flowPane(e.props.bodyColumns, rows), Date.now()), "flow"),- ask: /* @__PURE__ */ __name((_b, e) => askView(state, e.props.bodyColumns), "ask"),- recap: /* @__PURE__ */ __name((_b, e) => recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, e.props.bodyColumns), "recap"),- map: /* @__PURE__ */ __name((b, e) => mapBody(b, e), "map")+ flow: (b, e, rows) => flow.paneTree(b, flowPane(e.props.bodyColumns, rows), Date.now()),+ ask: (_b, e) => askView(state, e.props.bodyColumns),+ recap: (_b, e) => recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, e.props.bodyColumns),+ map: (b, e) => mapBody(b, e)};function mapTurn() {- const knows = /* @__PURE__ */ __name((path) => knowsOf(path, state.contexts, flowOn ? flow.state : null), "knows");+ const knows = (path) => 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), knows };}-__name(mapTurn, "mapTurn");function mapBody(b, e) {const { bodyColumns, placement, scroll } = e.props;const d = discovery;const notice2 = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];return map.paneTree(b, { surface: e.surface, notice: notice2, bodyColumns, placement, bodyRows: scroll.bodyRows - TAB_ROWS, theme });}-__name(mapBody, "mapBody");function pressMap($, key2) {try {map.press(bind($), key2);@@ -5451,11 +4900,9 @@ function pressMap($, key2) {bind($).debug(`map key failed: ${String(err)}`);}}-__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();@@ -5468,7 +4915,6 @@ function tabBody(b, e) {return text(fit(PANE_COPY.bodyFailed, e.props.bodyColumns), { dimColor: true, wrap: "truncate-end" });}}-__name(tabBody, "tabBody");async function onPane($, e, next) {if (e.requestId !== PANE_ID) return next(e);const b = bind($);@@ -5481,7 +4927,6 @@ async function onPane($, e, next) {return next(e);}}-__name(onPane, "onPane");function register(on, options = {}) {reviewOn = options["lens_review"] !== false;autoOpenOn = options["lens_pane_autoopen"] === true;@@ -5498,15 +4943,15 @@ function register(on, options = {}) {on("ui.input", { plugin: "repowise", element: "lens-ask" }, onAskInput);on("classic.PostCompact", onPostCompact);on("tool.call", onToolCall);- on("tool.check", onToolCheck);on("ui.render", { component: "Spinner" }, onSpinner);- if (options["lens_squeeze"] !== false) on("ui.render", { component: "ToolResult" }, onToolResult);+ if (options["lens_squeeze"] !== false) {+ on("ui.render", { component: "ToolResult" }, onToolResult);+ }if (options["lens_margin"] !== false) {on("classic.PostToolUse", onPostToolUse);on("ui.render", { component: "ToolUse" }, onToolUse);}}-__name(register, "register");export {register};diff --git a/plugins/shared/commands/ask.md b/plugins/shared/commands/ask.mdindex 0d1acdceb..9427e942b 100644--- a/plugins/shared/commands/ask.md+++ b/plugins/shared/commands/ask.md@@ -1,7 +1,7 @@---frontmatter: |description: Ask a codebase question and get a cited, synthesised answer with a confidence rating (costs an LLM call).- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise ask:*), Read---# Repowise Askdiff --git a/plugins/shared/commands/context.md b/plugins/shared/commands/context.mdindex 642264288..f78b8f5ba 100644--- a/plugins/shared/commands/context.md+++ b/plugins/shared/commands/context.md@@ -1,7 +1,7 @@---frontmatter: |description: Triage card for files, modules, or symbols — layer, hotspot, fix history, freshness (relationships, not source bytes).- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise context:*), Read---# Repowise Contextdiff --git a/plugins/shared/commands/coverage.md b/plugins/shared/commands/coverage.mdindex 21add2029..d4994326b 100644--- a/plugins/shared/commands/coverage.md+++ b/plugins/shared/commands/coverage.md@@ -1,7 +1,7 @@---frontmatter: |description: Ingest or inspect test-coverage reports (LCOV, Cobertura, Clover, Go cover profiles, JaCoCo, repowise JSON, or coverage.py .coverage; builds the per-test map when contexts are present), or gate a change on its patch coverage in CI.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise coverage:*), Read---# Repowise Coveragediff --git a/plugins/shared/commands/dead-code.md b/plugins/shared/commands/dead-code.mdindex 8ff42c9ab..8b1e56bd5 100644--- a/plugins/shared/commands/dead-code.md+++ b/plugins/shared/commands/dead-code.md@@ -1,7 +1,7 @@---frontmatter: |description: Report unreachable files, unused exports, and zombie packages, tiered by confidence.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise dead-code:*), Read---# Repowise Dead Codediff --git a/plugins/shared/commands/decision.md b/plugins/shared/commands/decision.mdindex 8eb668aa4..46e1052b9 100644--- a/plugins/shared/commands/decision.md+++ b/plugins/shared/commands/decision.md@@ -1,7 +1,7 @@---frontmatter: |description: Work with architectural decisions — list, inspect health, add, or confirm auto-proposed decisions.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise decision:*), Read---# Repowise Decisionsdiff --git a/plugins/shared/commands/doctor.md b/plugins/shared/commands/doctor.mdindex 3f880ea68..7040bc171 100644--- a/plugins/shared/commands/doctor.md+++ b/plugins/shared/commands/doctor.md@@ -1,7 +1,7 @@---frontmatter: |description: Diagnose the Repowise setup — install, API keys, index/store drift — and optionally repair it.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise doctor:*), Read---# Repowise Doctordiff --git a/plugins/shared/commands/export.md b/plugins/shared/commands/export.mdindex cad70d544..c1cc9523b 100644--- a/plugins/shared/commands/export.md+++ b/plugins/shared/commands/export.md@@ -1,7 +1,7 @@---frontmatter: |description: Export the wiki (or architecture model) to markdown, HTML, JSON, or Structurizr DSL.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise export:*), Read---# Repowise Exportdiff --git a/plugins/shared/commands/health.md b/plugins/shared/commands/health.mdindex 45be7e9e6..f61421dbc 100644--- a/plugins/shared/commands/health.md+++ b/plugins/shared/commands/health.md@@ -1,7 +1,7 @@---frontmatter: |description: Show Repowise code-health — KPIs, lowest-scoring files, refactoring targets, trends, or per-file markers.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise health:*), Read---# Repowise Healthdiff --git a/plugins/shared/commands/impacted-tests.md b/plugins/shared/commands/impacted-tests.mdindex 27d2bdf2a..9ee3fa128 100644--- a/plugins/shared/commands/impacted-tests.md+++ b/plugins/shared/commands/impacted-tests.md@@ -1,7 +1,7 @@---frontmatter: |description: Print the tests whose coverage intersects a change's changed lines — for a commit, base..head range, or staged diff.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise impacted-tests:*), Read---# Repowise Impacted Testsdiff --git a/plugins/shared/commands/init.md b/plugins/shared/commands/init.mdindex 9d5df02bc..ff674335c 100644--- a/plugins/shared/commands/init.md+++ b/plugins/shared/commands/init.md@@ -1,7 +1,7 @@---frontmatter: |description: Set up Repowise for this codebase. Installs if needed, asks about your preferences, and runs the indexing.- allowed-tools: Bash, Read, Write, AskFollowupQuestion+ allowed-tools: Bash(repowise --version), Bash(repowise init:*), Bash(repowise status:*), Bash(git rev-parse --git-common-dir), Bash(pip install repowise), Bash(python -m pip install repowise), Read, AskUserQuestion---# Repowise Init@@ -177,22 +177,13 @@ Then continue to Step 4 for the model-written wiki, or Step 5 otherwise.**Skip this entire step unless the user chose the model-written wiki.** Amissing key is not a blocker: `init` renders the template wiki and exits 0-without one. If you cannot find a key, do not stop and do not ask again. Run+without one. If the user has no key, do not stop and do not ask again. Run`repowise init --yes` and tell the user their wiki is rendered from structureand can be upgraded per-page later with `repowise generate`.-Check which API keys are already set by running:-```bash-echo "ANTHROPIC=${ANTHROPIC_API_KEY:+set}" "OPENAI=${OPENAI_API_KEY:+set}" "GEMINI=${GEMINI_API_KEY:+set}${GOOGLE_API_KEY:+set}" "OLLAMA=${OLLAMA_BASE_URL:+set}"-```--If one or more keys are detected, suggest the detected provider:-- `ANTHROPIC_API_KEY` set → suggest `--provider anthropic`-- `OPENAI_API_KEY` set → suggest `--provider openai`-- `GEMINI_API_KEY` or `GOOGLE_API_KEY` set → suggest `--provider gemini`-- `OLLAMA_BASE_URL` set → suggest `--provider ollama`--If no key is detected, ask:+Do not read, test or print the user's environment variables or key values+yourself. `repowise init` picks up a provider key from the environment on its+own, so a user who already has one set needs no `--provider`. Ask:"Which LLM provider do you want to use?"- **Anthropic** (Claude) — needs `ANTHROPIC_API_KEY`@@ -201,7 +192,7 @@ If no key is detected, ask:- **Ollama** (fully local, no API key, slower) — needs Ollama running locally- **LiteLLM** (100+ providers) — needs LiteLLM config-Then ask them to set the required environment variable. Show the exact export command:+If they have not set that key yet, ask them to set it in their own shell. Show the exact export command:```bashexport ANTHROPIC_API_KEY="sk-ant-..."```diff --git a/plugins/shared/commands/reindex.md b/plugins/shared/commands/reindex.mdindex 71d246bbf..759593126 100644--- a/plugins/shared/commands/reindex.md+++ b/plugins/shared/commands/reindex.md@@ -1,7 +1,7 @@---frontmatter: |description: Rebuild the Repowise vector store by re-embedding all wiki pages. No LLM calls — only embedding API calls.- allowed-tools: Bash, Read, AskFollowupQuestion+ allowed-tools: Bash(repowise reindex:*), Read, AskUserQuestion---# Repowise Reindexdiff --git a/plugins/shared/commands/risk.md b/plugins/shared/commands/risk.mdindex 45d93b595..aa10aa8d4 100644--- a/plugins/shared/commands/risk.md+++ b/plugins/shared/commands/risk.md@@ -1,7 +1,7 @@---frontmatter: |description: Rank a live change for review using a repo-relative percentile and an auditable supporting diff-shape score.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise risk:*), Read---# Repowise Riskdiff --git a/plugins/shared/commands/search.md b/plugins/shared/commands/search.mdindex ac58dfb54..80c6ca2b4 100644--- a/plugins/shared/commands/search.md+++ b/plugins/shared/commands/search.md@@ -1,7 +1,7 @@---frontmatter: |description: Search the Repowise wiki using natural language, full-text, or symbol search.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise search:*), Read---# Repowise Searchdiff --git a/plugins/shared/commands/security.md b/plugins/shared/commands/security.mdindex ad501d1c6..63ed8dab3 100644--- a/plugins/shared/commands/security.md+++ b/plugins/shared/commands/security.md@@ -1,7 +1,7 @@---frontmatter: |description: Scan for security signals — working-tree scanning already runs during init/update; use --history to walk full git history for leaked secrets.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise security scan:*), Read---# Repowise Securitydiff --git a/plugins/shared/commands/status.md b/plugins/shared/commands/status.mdindex 0e063a292..cd7e41bee 100644--- a/plugins/shared/commands/status.md+++ b/plugins/shared/commands/status.md@@ -1,7 +1,7 @@---frontmatter: |description: Check the health of your Repowise index — sync state, page counts, provider, and token usage.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise status:*), Read---# Repowise Statusdiff --git a/plugins/shared/commands/symbol.md b/plugins/shared/commands/symbol.mdindex 9e51ca00f..640ce241c 100644--- a/plugins/shared/commands/symbol.md+++ b/plugins/shared/commands/symbol.md@@ -1,7 +1,7 @@---frontmatter: |description: Read one symbol's body with live-verified line bounds (path::Name, live range, or distill omission ref).- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise symbol:*), Read---# Repowise Symboldiff --git a/plugins/shared/commands/update.md b/plugins/shared/commands/update.mdindex f5eab4829..4181bedf8 100644--- a/plugins/shared/commands/update.md+++ b/plugins/shared/commands/update.md@@ -1,7 +1,7 @@---frontmatter: |description: Trigger an incremental Repowise update to sync documentation with recent code changes.- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise update:*), Read---# Repowise Updatediff --git a/plugins/shared/commands/why.md b/plugins/shared/commands/why.mdindex d7cf26588..6933affbc 100644--- a/plugins/shared/commands/why.md+++ b/plugins/shared/commands/why.md@@ -1,7 +1,7 @@---frontmatter: |description: Why the code is shaped this way — decisions, rationale, and git archaeology (question, path, or decision-health dashboard).- allowed-tools: Bash, Read+ allowed-tools: Bash(repowise why:*), Read---# Repowise Why