Skip to content

Codebase intelligence for AI and humans: code health scores, auto-generated docs, git analytics, dead code detection, and architectural decisions via MCP.

feat(lens): add the Flow dashboard and light the map with Claude's turn (#3023)

Raghav Chamadiya591e845fdd42
diff --git a/.github/assets/lens.gif b/.github/assets/lens.gif
new file mode 100644
index 000000000..75af8db0d
Binary files /dev/null and b/.github/assets/lens.gif differ
diff --git a/README.md b/README.md
index 00d123e88..a24232420 100644
--- a/README.md
+++ b/README.md
@@ -558,6 +558,17 @@ hover, and refactoring plans as CodeLens. One install also registers the MCP ser
so the same index serves you and your agent. Install from the Marketplace or Open VSX
and run **Repowise: Set Up This Repository**. [VS Code guide →](docs/agent/VSCODE.md)
+<img src=".github/assets/lens.gif" alt="Lens in Claude Code on Django: Claude edits query.py, which turns amber on the map while the 12 files that import it light up in plum; a second edit to django/conf/__init__.py lights its 248 importers, and Flow lists what to check before accepting" width="100%" />
+
+**In Claude Code**, Lens ships inside the Repowise plugin and shows you what the index
+knows while Claude works: the file it is on and how many files depend on it, a change
+review after a turn that edits files (code health, tests to run, other branches on the
+same files), and `/lens`, a pane with Flow (what to check before accepting each turn),
+a map of the repo lit by what Claude searched, opened and edited and what its edits
+reach, Ask, and a session recap. Nothing reaches Claude unless you press a button, and
+Lens makes no model calls of its own. It needs Claude Code 2.1.287 or later, and the
+map needs `repowise serve --no-ui` running. [Lens guide →](docs/agent/LENS.md)
+
---
## The ten MCP tools
diff --git a/docs/README.md b/docs/README.md
index 4bc931fa6..b8ffe4b45 100644
--- a/docs/README.md
+++ b/docs/README.md
@@ -32,6 +32,7 @@ For a map of every layer and how they feed each other, read
| [agent/MCP_TOOLS.md](agent/MCP_TOOLS.md) | The ten task-shaped tools, what each answers, and the opt-in extras |
| [agent/HOOKS.md](agent/HOOKS.md) | Context and warnings that reach the agent without it asking |
| [agent/DISTILL.md](agent/DISTILL.md) | Compress noisy command output before your agent reads it |
+| [agent/LENS.md](agent/LENS.md) | Lens in the Claude Code plugin: the spinner, change review, Flow and the `/lens` map shown while Claude works |
| [layers/GRAPH.md](layers/GRAPH.md) | The dependency graph, and how much to trust each edge |
| [layers/LANGUAGE_SUPPORT.md](layers/LANGUAGE_SUPPORT.md) | What works per language: 26 parsed to a full AST, 40 on the support ladder |
@@ -131,5 +132,6 @@ For a map of every layer and how they feed each other, read
Agent and editor pages: [Codex](agent/CODEX.md) ·
[opencode](agent/OPENCODE.md) · [Hermes](agent/HERMES.md) ·
[VS Code](agent/VSCODE.md) ·
+[Lens for Claude Code](agent/LENS.md) ·
[Claude Code as a provider](agent/CLAUDE_CODE_PROVIDER.md) ·
[all integrations](agent/INTEGRATIONS.md).
diff --git a/docs/agent/LENS.md b/docs/agent/LENS.md
new file mode 100644
index 000000000..81b97bfef
--- /dev/null
+++ b/docs/agent/LENS.md
@@ -0,0 +1,463 @@
+# Lens for Claude Code
+
+Lens is the part of the Repowise Claude Code plugin that you see. The plugin's
+hooks and MCP tools already feed the index to Claude. Lens draws what that index
+knows into the Claude Code interface itself: which file Claude is working on and
+how much depends on it, the decision or fix history behind a file it edits, how
+much a distilled command output was cut, what the change did to code health,
+a dashboard of each turn (what an edit reaches, where Claude's context came
+from, what Repowise answered), and a map of the repository
+with Claude's reads and edits marked on it.
+
+<img src="../../.github/assets/lens.gif" alt="Lens in Claude Code on Django: the map lights query.py in amber and its 12 importers in plum, then the 248 importers of django/conf/__init__.py, and Flow lists what to check before accepting" width="100%" />
+
+Lens ships inside the plugin as a Claude Code mod. There is nothing separate to
+install. It is quiet at rest: each surface draws only when it has something to
+say, and the map pane opens only when you ask for it.
+
+## What Lens shows
+
+On-screen wording below is quoted from the code. Values in angle brackets stand
+for figures your own index fills in.
+
+### The band above the prompt
+
+At most two rows above the prompt, counting the change review row and the
+compaction brief row, and empty when there is nothing to report. Those two rows
+keep their place, and the dim information rows above them fill what is left. The
+band gives way when Claude Code shows a survey there.
+
+- **A setup hint**, once per session, when something stops Lens from showing
+ everything. It stays for the first turn that ends while it shows, then
+ retires.
+
+ | Situation | Row |
+ |---|---|
+ | Indexed repo, no local server running | `Lens map needs the local server: repowise serve --no-ui` |
+ | The local server is running but does not list this repo | `Lens map needs a local server for this repo: repowise serve --no-ui` |
+ | The local server asks for an API key | `local server needs an API key; Lens does not read keys` |
+ | Git repo with no Repowise index | `index this repo for Lens: repowise init --no-prose --yes` |
+ | The `repowise` CLI is not installed | `Lens needs the Repowise CLI: pip install repowise` |
+
+ Lens shows these commands for you to run. It never runs them itself.
+- **Index freshness**, while the index is behind the checked-out commit:
+ `index behind HEAD (<N> files changed) · repowise update`. It stays quiet
+ while `repowise update` is already running.
+- **Savings**, once the local server reports tokens saved since the session
+ started: `<N> tokens (<M> inferred) · $<X> saved since this session started · all agents on this repo`.
+ The figure comes from the server's savings ledger, which counts every agent on
+ this repo, not only this Claude Code session. Dollars are the priced input
+ side only. In a narrow terminal the row shortens to
+ `<N> tokens (<M> inferred) · $<X> saved this session · all agents`.
+- **The change review row** and **the compaction brief offer**, described
+ below. These carry buttons.
+
+### Spinner text
+
+While Claude reads or edits a file inside the indexed repo, Lens appends the
+file's reach to Claude Code's spinner: `<file name> · <N> caller files · <N> contributors`,
+with the file's base name.
+Lens looks each file up once per session with `get_context`. The text appears
+from the next redraw after that lookup lands, never holding the spinner up.
+Counts the index does not know are left out.
+
+### Margin notes under edits
+
+Under an Edit or Write, at most two dim lines repeat what the Repowise
+`PostToolUse` hook flagged for that file. Lens adds no thresholds of its own:
+if the hook said nothing, there is no note.
+
+- `a standing decision covers this file: <title>`
+- `a decision found in this file, not yet reviewed: <title>`
+- `fixed <N> times in 6 months, most recently <age>, mostly in <symbol>`
+
+Margin notes need the `repowise-augment` hook on your PATH, which installing the
+`repowise` CLI provides.
+
+### Squeeze rows under distilled output
+
+When a Bash result was shortened by `repowise distill`, Lens draws one row under
+it: a 12-cell bar for the share of lines kept, then
+`<N> lines → <kept> · ~<N> tokens omitted · <N> failed · repowise expand <ref>`.
+Failure and error counts appear only when the test runner reported them. When a
+result carries several omission markers the row adds `(+<N> more)`. Everything
+on the row is read from the distill marker and the output itself. See
+[Distill](DISTILL.md) for how output gets shortened and how `repowise expand`
+restores it.
+
+### Change review card and buttons
+
+After a turn in which Claude edited files (Edit, MultiEdit, Write or
+NotebookEdit), Lens reviews the working tree with `get_change_risk`. The
+review starts in the background as soon as the first edit lands. Turns that
+were interrupted or failed, and subagent turns, are not reviewed.
+
+While it runs, the band shows only `Reviewing the change...`. The review
+gives up after 20 seconds. A timeout or a failure is reported in the row under
+Claude's answer, as `Change review timed out after 20 s` or
+`Change review could not run: <reason>`.
+
+The result appears as one row beneath Claude's answer, for example:
+
+```
+Change review (working tree, <N> changed files) · Health: <verdict> · <findings> · Diff shape: bigger than <N>% of this repo's recent commits; size, not danger · Tests to run: <N> tests, inferred from the dependency graph, not measured: <tests> · Branches: ◦ 1 other branch also edits <file> (<branch>)
+```
+
+- `Health:` says what the comparison found, for example
+ `no new findings in all <N> changed files`, `improved, <N> findings resolved, none new`,
+ or the review's own headline when it found new findings.
+- A partial comparison says so: `Scope: compared <N> of <M> changed files; <K> not analysed (<reasons>), so this is not a clean bill`.
+- Tests say whether they are `measured by stored coverage` or
+ `inferred from the dependency graph, not measured`.
+- Branch overlap uses a neutral `◦` mark. Green, amber and red are reserved for
+ health.
+- A clean change with no other branch in its files gets the short form:
+ `Change review (<scope>) · health: <verdict>`.
+
+The band then shows a summary such as `review · health: <N> new findings, review required`
+with up to three buttons, each pressed with the number shown beside it:
+
+| Button | When it shows | What a press does |
+|---|---|---|
+| `1: Run tests` | The review names tests to run | Submits a visible prompt to Claude: `Run the tests Repowise names for this change, <basis>: <tests>` |
+| `2: Why` | The Repowise hook flagged a decision on a file edited this turn | Opens the `/lens` pane on the Ask field with `why <decision>` in it. Nothing is asked until you press Enter |
+| `3: Details` | The review returned its full verdict | Prints the review's status, headline, reasons and next actions into the transcript for you to read |
+
+The band row stays quiet for a clean review with no tests, no overlapping
+branch and no decision. A new turn retires it.
+
+### The /lens pane
+
+`/lens` opens a pane with four tabs, `1: Flow 2: Map 3: Ask 4: Recap`. A session
+starts on Flow; after that `/lens` reopens the tab shown last.
+
+**Flow** is a dashboard of the turn, built from what only Lens sees: the chat
+already shows each step, so Flow shows what those steps add up to. Each
+section draws only when it has something to say.
+
+The header is the Repowise owl on one line, `{◉,◉}`, beside the status. The
+owl's eyes carry its state: `{─,─}` at rest, a slow blink while Claude works,
+eyes to the side `{◐,◐}` while a Repowise call is in flight, `{^,^}` for a
+moment after a turn that ended with an answer, and a neutral `{•,•}` after a
+turn that stopped. With `prefersReducedMotion` on it does not blink. The
+status is `Working · <m:ss>` while Claude works, then how the turn ended, kept
+until your next prompt: `Done · <time>` (with a thistle), `Stopped · <time>`
+when you interrupted it, or `Did not finish · <time>` after a refusal or an
+error, with `edited <N> files` when it edited. A prompt sent while a turn is
+still open marks that turn stopped. Under it, at full strength:
+`Repowise <N> calls · Claude opened <N> files, <N> named by Repowise first`,
+plus `edit landed in a file Repowise named` when one did (or
+`No Repowise calls`). A file counts as named by Repowise first when a Repowise
+reply earlier in the session named that exact repo-relative path. Then your
+own words, dim: text the session puts before a prompt (agent hand-backs,
+system reminders, task notifications, command wrappers) is left out, and when
+nothing you typed remains the line is not drawn.
+
+**BEFORE YOU ACCEPT** lists, per file this turn edited, only what the change
+reaches that Claude did not look at, from the index (the facts say
+`as of the last index`):
+
+- `<N> direct importers; Claude opened <N>`: files that import it directly
+ (the map's depth-1 blast radius, the same request, never a second one).
+- `not opened, usually changes with it (co-change score): <file> 0.80, ...`:
+ the two strongest co-change partners Claude did not open, with the server's
+ 0 to 1 score.
+- `<N> test files reach query.py (inferred); none run`: tests that reach the
+ file, measured or inferred as the server says, and how many a test command
+ this session named (by path, file name or folder, as a whole word).
+- The turn's health from the change review's own result, never a second call:
+ `this turn introduced 1 finding: complex method in query.py`, or
+ `health compared in part only; no new findings in the part compared`. A turn
+ that introduced nothing draws nothing.
+
+**WORKING SET** lists the files this turn edited, then the ones it read, at most
+six (`+<N> more`): the file, `edited` or `read`, how Claude came to it (the
+Repowise tool that named it first, `search` when a search returned it, or
+`direct`), and what the index knows of it: `hotspot`, `<N> files use it`
+(importers and callers together, not only direct importers), and
+`recent owner <name> <share> %`. These come from the file card Lens already
+fetches for the spinner. Below 80 columns the index facts are left out.
+
+**CONTEXT** is one bar of the bytes of tool results Claude received this turn,
+by kind, each kind its own shade so it reads without color:
+`█ Repowise <size> ▓ file reads <size> ▒ search <size> ░ shell <size> · other <size>`,
+then `first edit after <time>`. Lens counts each result's size; it keeps no
+content.
+
+**REPOWISE CALLS** has one line per call: the time since the turn started, the
+tool, what it asked about, how long it took, and what the reply was built
+from, for example `420 ms · 1 target · 1 documentation page · index current`.
+The call Claude is waiting on is marked `▸` and says `asking...`. A call about
+a file Claude had already edited this session says, dim,
+`from the index before this edit`. Questions you ask from Lens land in the
+Ask tab, not here. Press a call to open its detail; `j: Next call` and
+`k: Previous call` move between them. The detail shows `how it was answered`
+(only what the reply said about itself, such as `indexed at <commit>`,
+`index <N> days old`, `verified against the code`,
+`partial: the server capped it`, `confidence <level>`,
+`reply <size> (cap <N> characters)` and `<N> tokens left out, restorable`),
+`reply begins` with its first characters, and `Claude then opened`: the files
+Claude opened after this reply named them, or `nothing yet`. When the calls do not fit, a dim
+line says `<N> earlier calls hidden · j / k step through calls` (or
+`<N> later calls below · ...`).
+
+Earlier turns keep one line each,
+`Turn <N> · <time> · <N> Repowise calls · <N> files read · <N> edited`, with
+`stopped` or `did not finish` when they did not end with an answer; past six
+turns they fold into `Earlier: <N> turns · ...`.
+
+Flow's text keeps your terminal's own colors and never sets a background.
+Only marks take an accent: heather plum for the hills, the thistle,
+Repowise's tool names and its part of the bar; amber for the owl's eyes and
+the call in flight. Health colors never appear here. In a repo without an index
+Flow still counts Claude's own work and says
+`Repowise is not connected in this repo, so only Claude's own steps show here.`
+Before the first turn it says
+`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.`
+
+**Map** shows the whole repository as quiet tiles, one per file, sized by
+lines of code and grouped into folders, in two tones close to the terminal's
+own ground, so the current turn is the only colour on it. As Claude works,
+the files of its turn light up: search matches glow faintly, files Claude
+opened turn mist, the edit (and Claude's latest step) turns orange, files a
+Repowise reply named take a deep plum, and the files that import the edit
+ripple out in plum from it. Every mark fills a whole tile; a file too small
+for a tile of its own still lights one full cell where it sits. Opened and
+edited files keep their names beside their tiles, and large folders show their
+names faintly. The empty ground between tiles is the terminal's own
+background. In a very large repository, where most files would be smaller than
+a pixel, folders are drawn as tiles instead of files.
+
+Under the map, a story strip says what happened this turn, a row each once it
+has something to say:
+
+```
+SEARCHED class QuerySet: 4 files · django/db/models/sql/*.py: 7 files
+OPENED manager.py · query.py ◆ query.py named by get_context
+EDITED ◉ query.py +1 line
+REACHES 12 importers: manager.py (opened), fields.py, prefetch.py, +9
+```
+
+The strip is the map's legend. Before anything happens it says
+`Nothing lit yet this turn. Files Claude searches, opens and edits light up here.`
+The importers come from the import graph, so they are inferred from imports,
+not observed calls; while that lookup runs the row says
+`finding the files that import <file>`. A scope line says how much of the repo
+is drawn: `<N> files, all drawn`, `<N> of <M> files drawn at this size · rest too small to draw`,
+`<M> files, drawn as folders at this size`, or, when the server stopped at its
+cap, `4,000 largest of <M> files drawn`, then `indexed <age>` and
+`<N> touched files not on the map` when some were outside it.
+
+The `Health colours` button under the map (hotkey `h`) colours the tiles by
+health band instead, `Excellent`, `Good`, `Fair`, `Needs work`, `At risk` and
+`Not scored`, with that legend; the `lens_map_health` setting starts the map
+that way. The glow and ripple animations play briefly. With Claude Code's
+`prefersReducedMotion` setting on, the map shows still frames only. Colours
+follow Claude Code's `theme` setting: a light theme gets the light ramp.
+
+The map needs the local server (full mode). Without it the Map tab shows the
+setup hint instead.
+
+**Ask** asks the index about this repo. `/lens ask` and the review's `Why`
+open it, and `/lens ask <question>` asks at once, its reply landing in the
+Ask tab. Before the first question the field says
+`Ask about this repo. Answers cite the evidence they used.` A question that
+starts with "why" goes to `get_why`, which reads decision records, commits and
+rationale comments. Anything else goes to `get_answer`. Each reply is headed
+`Built from the index`, or `Written by this repo's configured model, from the index`
+when `get_answer` may have used the model your repo configures. The reply shows
+the tool's confidence or basis and the evidence it cites, or
+`no evidence cited`. Long replies are cut at 4,000 characters, with the cut
+stated. One question runs at a time: asking another meanwhile shows
+`still answering the last question; ask again when it lands`.
+
+**Recap** summarizes the session from what Lens already observed, with no new
+lookups:
+
+| Row | Example value |
+|---|---|
+| `Files` | `<N> edited of <M> files touched`, with `<M>` shown as `200+` once the count of touched files is capped |
+| `Change review` | `none this session`, shown in place of the four review rows when no review has run |
+| `from the last change review` | a dim sub-head over the next four rows |
+| `Code health` | the last review's health verdict |
+| `Findings` | `<N> resolved · <N> new findings`, or `not compared` |
+| `Tests to run` | `<N> tests, measured` or `<N> tests, inferred` (`<N> test files, ...` when the review names files), or `none named` |
+| `Branches overlapping` | the overlap line, `none found` or `not reported` |
+| `Saved` | the savings row, `nothing yet since this session started`, or `needs the local server: repowise serve --no-ui` |
+| `Decisions surfaced` | `<N>: <titles>` or `none` |
+
+The footer says `Lens made no model calls. Every figure here is read from the local index.`
+After Ask replies that may have come from the model, it says
+`Lens made no model calls. <N> Ask replies from get_answer may have been written by this repo's configured model.`
+
+### Compaction brief
+
+After Claude Code compacts the conversation, the band offers
+`context compacted 1: Brief Claude`, or `context compacted 4: Brief Claude`
+when a change review row is showing, since that row takes 1 to 3. Pressing it
+submits one visible prompt, at most 1,200 characters, built from this
+session's edits, the decisions the hook surfaced and the last change review,
+with no model call. It starts
+`The context was compacted. This brief is built from the Repowise index and this session's edits:`
+and lists `Files edited:`, `Decisions in play:` and `Open review items:` from
+this session. Lens does not change the compaction or its summary. The offer
+goes away when you press it or start the next turn.
+
+### Desktop map
+
+In the Claude desktop app, the Map tab draws the same map as an SVG image
+instead of terminal cells, without the animations. A map too detailed for the
+desktop drawing says
+`Lens map has too much detail to draw here; the terminal map shows it`. Other
+surfaces that open the pane say
+`Lens map: not drawn on this surface (terminal and desktop app only)`.
+
+## Turning it on
+
+Requirements:
+
+- **Claude Code 2.1.287 or later.** Older versions load the rest of the plugin
+ and skip Lens.
+- **The Repowise plugin**, installed as described in the
+ [plugin README](../../plugins/claude-code/README.md):
+ `/plugin marketplace add repowise-dev/repowise`, then
+ `/plugin install repowise@repowise`.
+- **An indexed repo.** In a git repo with no index, Lens shows the
+ `repowise init --no-prose --yes` hint. Outside a git work tree it stays
+ silent.
+
+Lens picks one of two modes at session start and checks again after each turn:
+
+| Mode | When | What shows |
+|---|---|---|
+| Full | `repowise serve --no-ui` is running for this repo on this machine | Everything: the band including savings, spinner text, margin notes, squeeze rows, the change review, the `/lens` pane with Flow, the map, Ask and Recap, and the compaction brief |
+| Lite | The repo is indexed but no local server serves it | Everything except the map and the savings row. The Map tab and the Recap's `Saved` row point at `repowise serve --no-ui` |
+
+Lite mode works through the plugin's MCP server, which the plugin starts on its
+own. Full mode adds the local server, which Lens finds through
+`.repowise/serve.lock.json`.
+
+## Settings
+
+Six toggles in the plugin's `userConfig`. Changing one reloads Lens.
+
+| Setting | Default | What it controls |
+|---|---|---|
+| `lens_margin` | on | Margin notes under Edit and Write |
+| `lens_squeeze` | on | Squeeze rows under distilled Bash output |
+| `lens_review` | on | The change review after a turn that edits files, its card and its buttons |
+| `lens_flow` | on | The Flow tab. Off, Lens records nothing for it and the pane opens on the Map |
+| `lens_map_health` | off | Start the map with health colours on its tiles. Off, the map is quiet tiles lit by Claude's turn; the `Health colours` button switches either way |
+| `lens_pane_autoopen` | off | Open the map pane on its own the first time Claude reads a file, when the terminal is wide enough to place it without asking. `/lens` opens it at any time |
+
+## Commands
+
+| Command | What it does |
+|---|---|
+| `/lens` | Opens the pane on the tab shown last (Flow at first), with keyboard focus |
+| `/lens flow` | Opens the pane on the Flow tab |
+| `/lens map` | Opens the pane on the Map tab |
+| `/lens ask` | Opens the pane on the Ask tab |
+| `/lens ask <question>` | Asks the question; its reply lands in the Ask tab |
+| `/lens recap` | Opens the pane on the Recap tab |
+
+`/lens` writes nothing into the transcript. The pane is the answer.
+
+## Troubleshooting
+
+**Nothing from Lens appears at all.** Lens needs Claude Code 2.1.287 or later.
+Mods can also be switched off by Claude Code's remote rollout setting or by an
+administrator. In each case only Lens is missing: the plugin's MCP tools,
+commands, skills and hooks keep working.
+
+**Nothing draws in some places.** Claude Code draws mod interface only in its
+terminal interface and the desktop app. Nothing from Lens appears in the VS
+Code chat panel, `claude -p`, the Agent SDK, cloud sessions, or desktop
+sessions running in WSL.
+
+**The map pane does not open on its own.** Claude Code places a pane nobody
+asked for only in a terminal at least 144 columns wide. Below that, with
+`lens_pane_autoopen` on, the band says
+`Lens map is ready; this pane is too narrow to open on its own. Run /lens`.
+`/lens` asks for the pane directly. If Claude Code still cannot place it, the
+band says `Lens map needs a wider terminal: <reason>`.
+
+**The Map tab shows a hint instead of a map.** The map needs the local server.
+Run `repowise serve --no-ui` in the repo. If the server has an API key
+configured, Lens stays in lite mode, because it never reads keys.
+
+**The docked pane is grey, not my terminal's background.** The docked pane's
+surface is Claude Code's own; mods cannot set or clear it. Lens draws nothing
+behind its own rows, and inside the map the empty ground is the terminal's
+own background.
+
+**The map says it could not load.** `Lens map could not load; it tries again on /lens`.
+Run `/lens` again once the server is up.
+
+**The change review timed out.** It has 20 seconds. The review is skipped for
+that turn and runs again after the next turn that edits files.
+
+**After `/clear`.** A `/clear` starts Lens's view of the conversation over. Flow's turns, the map's lighting
+and story, the change review, the Ask answer, the brief offer and the savings
+baseline all reset, since `/clear` restarts Claude Code's own session clock.
+What the index said stays (the health map, file cards and the importers already
+asked for), so the map redraws without asking the server again. Resuming a
+session does not reset anything.
+
+## Footprint
+
+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.
+- **Flow only counts what passes.** It records each tool call's name, a few
+ arguments, its timing and the size of its result, never the result itself
+ (Repowise replies keep a short summary and their first 2 KB). What Flow
+ keeps (the last six turns, at most 60 steps each) stays in memory and is
+ gone when the session ends. Its facts come from requests Lens already makes:
+ the file card, the map's blast radius and the change review.
+- **Anything that reaches Claude goes through a button you pressed.** `Run tests`
+ and `Brief Claude` submit a prompt you can see in the transcript. `Why` only
+ fills the Ask field. `Details` prints into the transcript for you. Lens does
+ not change your prompts or the compaction.
+- **Lens itself makes no model calls** and reads no environment variables or
+ API keys. The only Claude Code setting it reads is `prefersReducedMotion`.
+- **Lens talks only to the local Repowise server and the plugin's MCP server.**
+ It contacts the server only at a plain `http` loopback address
+ (`127.0.0.1`, `localhost` or `::1`) named in `.repowise/serve.lock.json`.
+- **Lens runs no command that writes to your repo.** It runs read-only git
+ (`git rev-parse` and `git diff --name-only`) to compare the index with HEAD,
+ and `tasklist` or `ps` to check whether a server process is alive. It reads
+ `.repowise/state.json`, `.repowise/serve.lock.json` and
+ `.repowise/.update.lock`, and writes no files. Setup and update commands are
+ shown for you to run.
+
+The rest of Repowise is not covered by those statements, and two things there
+matter:
+
+- **`get_answer` may use the model your repo configures.** An Ask question that
+ does not start with "why" goes to `get_answer`, which synthesizes its answer
+ with the repo's configured model provider when one is set. The Recap footer
+ counts those replies.
+- **The Repowise MCP server and local server send anonymous usage telemetry**
+ unless you turn it off. The MCP server records one event per tool call (the
+ tool name, status and coarse measures, never the question, results or paths),
+ and Lens's own lookups are tool calls like any other. See
+ [Telemetry](../reference/TELEMETRY.md) for what is collected, and
+ [how to opt out](../reference/TELEMETRY.md#how-to-opt-out): `repowise telemetry disable`
+ or `DO_NOT_TRACK=1`.
+
+## Related
+
+- [Repowise plugin for Claude Code](../../plugins/claude-code/README.md)
+- [Hooks](HOOKS.md): the context the plugin's hooks give Claude, which the
+ margin notes repeat for you
+- [Distill](DISTILL.md): the output compression behind squeeze rows
+- [MCP tools](MCP_TOOLS.md): the tools Lens calls
+
+The Lens source lives in [`packages/claude-mod`](../../packages/claude-mod).
diff --git a/packages/claude-mod/mod-test/lens-flow.test.ts b/packages/claude-mod/mod-test/lens-flow.test.ts
new file mode 100644
index 000000000..533e0a7af
--- /dev/null
+++ b/packages/claude-mod/mod-test/lens-flow.test.ts
@@ -0,0 +1,64 @@
+// Runs under `claude plugin test` against the built bundle (npm run test:mod):
+// tool.call returns what core returned, and the Flow tab shows the turn's
+// Repowise call with what its reply was built from, its detail on a press.
+// Core is the test's own stubs.
+import { expect, test } from 'claude-code/testing'
+
+const PANE = {
+ plugin: 'repowise',
+ component: 'Pane',
+ surface: 'terminal',
+ requestId: 'lens',
+ viewport: { columns: 160, rows: 50 },
+ props: { title: 'Lens', isFocused: true, bodyColumns: 140, placement: 'dock', scroll: { offset: 0, bodyRows: 40 }, view: {} },
+} as const
+
+// A get_risk reply recorded on an indexed Django copy (test/fixtures/flow/get_risk.json), cut to the fields Flow reads.
+const REPLY = JSON.stringify({
+ result: {
+ targets: { 'django/db/models/query.py': { dependents_count: 12, co_change_partners_total: 25, contributor_count: 172, is_hotspot: true } },
+ _meta: { indexed_commit: 'e78991410b78', index_age_days: 0, completeness: { capped: true }, omitted: { tokens: 1849 } },
+ },
+})
+
+function stubs(on: any, seen: { core: any[] }): void {
+ on('session.start', () => ({ cwd: '/work' }))
+ on('session.cwd', () => ({ value: '/work' }))
+ on('fs.exists', () => ({ value: false }))
+ on('process.run', () => ({ value: { exitCode: 0, stdout: 'true\n', stderr: '' } }))
+ on('settings.read', () => ({ value: {} }))
+ on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))
+ on('ui.open', () => ({ value: { isPlaced: true } }))
+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['drawn by Claude Code'] }))
+ on('ui.log', () => ({}))
+ on('turn.start', (_$: any, e: any) => ({ turnId: e.turnId }))
+ on('tool.call', (_$: any, e: any) => {
+ const out = { ref: 1, result: {}, text: e.tool === 'mcp__repowise__get_risk' ? REPLY : '' }
+ seen.core.push(out)
+ return out
+ })
+}
+
+const RISK = { tool: 'mcp__repowise__get_risk', tool_use_id: 'toolu_01rw', targets: ['django/db/models/query.py'] }
+
+test('tool.call returns what core returned; Flow shows the call, what its reply was built from, and its detail on a press', async ($: any, on: any) => {
+ const seen = { core: [] as any[] }
+ stubs(on, seen)
+ await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
+ await $.turn.start({ text: '<system-reminder>be brief</system-reminder>add a comment above bulk_create', turnId: 't1' })
+ const out = await $.tool.call(RISK as any)
+ expect(out).toEqual(seen.core[0])
+ await $.command.run({ command: 'lens' })
+ const ui = await $.ui.mount(PANE)
+ expect(await ui.find({ key: 'lens-flow' })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: /Working · \d+:\d\d/ })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: 'Repowise 1 call' })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: '"add a comment above bulk_create"' })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: /\d+ ms · 1 target · 12 direct dependents · index 0 days old/ })).toBeDefined()
+ await ui.press({ key: 'lens-flow-toolu_01rw' })
+ await ui.unmount()
+ const open = await $.ui.mount(PANE)
+ expect(await open.find({ type: 'Text', text: /1,849 tokens left out, restorable/ })).toBeDefined()
+ expect(await open.find({ type: 'Text', text: /indexed at e78991410b78/ })).toBeDefined()
+ await open.unmount()
+})
diff --git a/packages/claude-mod/mod-test/lens-map.test.ts b/packages/claude-mod/mod-test/lens-map.test.ts
index 05d26db0e..680037aae 100644
--- a/packages/claude-mod/mod-test/lens-map.test.ts
+++ b/packages/claude-mod/mod-test/lens-map.test.ts
@@ -58,6 +58,7 @@ function fullStubs(on: any, seen: { urls: string[]; blits: any[]; opened: any[]
on('process.run', (_$: any, e: any) => processRun(e.argv))
on('http.fetch', (_$: any, e: any) => (seen.urls.push(e.url), answer(e.url)))
on('settings.read', () => ({ value: {} }))
+ on('config.list', () => ({ value: [{ key: 'theme', value: 'dark' }] }))
on('ui.open', (_$: any, e: any) => (seen.opened.push(e), { value: { isPlaced: true } }))
on('ui.blit', (_$: any, e: any) => (seen.blits.push(e), { value: {} }))
on('tool.call', () => ({ result: {} }))
@@ -76,36 +77,42 @@ async function openMap($: any, on: any) {
fullStubs(on, seen)
await $.session.start({ surface: 'terminal', isInteractive: true, cwd: ROOT })
expect(await waitFor(() => seen.urls.some((u) => u.endsWith('/api/repos')))).toBe(true)
- await $.command.run({ command: 'lens' })
+ await $.command.run({ command: 'lens', args: 'map' })
const ui = await $.ui.mount(PANE)
expect(await waitFor(async () => (await ui.find({ key: 'lens-map' })) !== undefined)).toBe(true)
return { seen, ui }
}
-test('/lens draws the Django health map with its legend', async ($: any, on: any) => {
+test('/lens map draws Django as quiet tiles, says what will light up, and offers health colours', async ($: any, on: any) => {
const { seen, ui } = await openMap($, on)
expect(seen.opened).toEqual([{ id: 'lens', title: 'Lens', rows: 29, focus: true }])
expect(seen.urls.filter((u) => u.includes('/health/map?cap=4000'))).toHaveLength(1)
const map = await ui.find({ key: 'lens-map' })
expect(map?.type).toBe('Raster')
expect(map?.props.columns).toBe(180)
- expect(map?.props.rows).toBe(48)
- expect(String(map?.props.cells).length).toBe(180 * 48 * 16)
+ expect(map?.props.rows).toBe(47)
+ expect(String(map?.props.cells).length).toBe(180 * 47 * 16)
expect(await ui.find({ type: 'Text', text: /^1,\d{3} of 2,970 files drawn at this size/ })).toBeDefined()
- expect(await ui.find({ type: 'Text', text: ' Needs work' })).toBeDefined()
- expect(await ui.find({ type: 'Text', text: ' Claude read' })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: /^Nothing lit yet this turn/ })).toBeDefined()
+ expect(await ui.find({ type: 'Text', text: ' Needs work' })).toBeUndefined()
+ await ui.press({ key: 'lens-map-health' })
await ui.unmount()
+ const health = await $.ui.mount(PANE)
+ expect(await health.find({ type: 'Text', text: ' Needs work' })).toBeDefined()
+ await health.unmount()
})
test('an edit ripples to the importers the server returned, by blit', async ($: any, on: any) => {
const { seen, ui } = await openMap($, on)
- await $.tool.call({ tool: 'Edit', file_path: `${ROOT}\\django\\db\\models\\query.py`, old_string: 'a', new_string: 'b' })
+ await $.tool.call({ tool: 'Edit', tool_use_id: 'toolu_e1', file_path: `${ROOT}\\django\\db\\models\\query.py`, old_string: 'a', new_string: 'a\nb' })
expect(await waitFor(() => seen.blits.length >= 2)).toBe(true)
- expect(seen.blits[0]).toMatchObject({ requestId: 'lens', key: 'lens-map', columns: 180, rows: 48 })
+ expect(seen.blits[0]).toMatchObject({ requestId: 'lens', key: 'lens-map', columns: 180, rows: 47 })
const fetched = BLAST_RADIUS.transitive_affected.length
- const line = await ui.find({ type: 'Text', text: /^edited query\.py/ })
- expect(line?.text).toMatch(new RegExp(`^edited query\\.py · ${fetched} files import it \\(from imports, not calls\\)`))
await ui.unmount()
+ const after = await $.ui.mount(PANE)
+ expect(await after.find({ type: 'Text', text: '◉ query.py +1 line' })).toBeDefined()
+ expect(await after.find({ type: 'Text', text: new RegExp(`^${fetched} importers: `) })).toBeDefined()
+ await after.unmount()
})
test('without the local server the pane says what to run', async ($: any, on: any) => {
@@ -116,7 +123,9 @@ test('without the local server the pane says what to run', async ($: any, on: an
on('process.run', () => run('true\n'))
on('mcp.connect', () => ({ value: { isConnected: true, server: 'plugin:repowise:repowise' } }))
on('settings.read', () => ({ value: {} }))
+ on('ui.open', () => ({ value: { isPlaced: true } }))
await $.session.start({ surface: 'terminal', isInteractive: true, cwd: '/work' })
+ await $.command.run({ command: 'lens', args: 'map' })
const hint = 'Lens map needs the local server: repowise serve --no-ui'
expect(
await waitFor(async () => {
diff --git a/packages/claude-mod/mod-test/lens-pane.test.ts b/packages/claude-mod/mod-test/lens-pane.test.ts
index d1e5cc44f..c516a2527 100644
--- a/packages/claude-mod/mod-test/lens-pane.test.ts
+++ b/packages/claude-mod/mod-test/lens-pane.test.ts
@@ -67,11 +67,16 @@ test('/lens recap opens the pane with focus on the recap, and the tabs switch it
const ui = await $.ui.mount(PANE)
expect(await ui.find({ key: 'lens-recap' })).toBeDefined()
expect(await ui.find({ type: 'Text', text: 'Lens made no model calls. Every figure here is read from the local index.' })).toBeDefined()
- await ui.press({ key: 'lens-tab-ask' })
+ await ui.press({ key: 'lens-tab-flow' })
await ui.unmount()
const again = await $.ui.mount(PANE)
- expect(await again.find({ key: 'lens-ask' })).toBeDefined()
+ expect(await again.find({ key: 'lens-flow' })).toBeDefined()
await again.unmount()
+ // The Ask field is off the bar: /lens ask opens it.
+ await $.command.run({ command: 'lens', args: 'ask' })
+ const field = await $.ui.mount(PANE)
+ expect(await field.find({ key: 'lens-ask' })).toBeDefined()
+ await field.unmount()
expect(seen.mcp).toEqual([])
})
diff --git a/packages/claude-mod/scripts/bench-map.mjs b/packages/claude-mod/scripts/bench-map.mjs
index 425de8072..09960dd7c 100644
--- a/packages/claude-mod/scripts/bench-map.mjs
+++ b/packages/claude-mod/scripts/bench-map.mjs
@@ -1,6 +1,9 @@
-// Local benchmark for the map's per-frame work at 180x50 on the recorded
-// Django feed: layout, a ripple frame, and the cell encoding. Budget 16 ms per
-// frame; vitest guards at 5x that (test/overlay.test.ts).
+// Local benchmark for the map at 180x50: the layout (redone only on a resize
+// or a style change) and one lit frame with its encoding (a turn's searches,
+// reads, the edit and its importers, mid-ripple). Three scales: a 100-file
+// repo (synthetic), Django's 2,347 recorded files, and a 10,000-file repo
+// (synthetic; the server sends its 4,000 largest). Budget 16 ms each; vitest
+// guards a frame at 5x that (test/overlay.test.ts).
//
// npm run bench:map -w @repowise-dev/claude-mod
@@ -11,12 +14,13 @@ import { build } from "esbuild";
const BUDGET_MS = 16;
const RUNS = 50;
+const SERVER_CAP = 4_000;
const pkg = resolve(dirname(fileURLToPath(import.meta.url)), "..");
// test/setup gives Node the runtime's Uint8Array.prototype.toBase64.
const bundled = await build({
stdin: {
- contents: 'import "./test/setup"; export * from "./src/views/map"; export * from "./src/views/overlay"; export * from "./src/model/trail";',
+ contents: 'import "./test/setup"; export * from "./src/views/map"; export * from "./src/views/overlay"; export { syntheticTree } from "./test/synthetic";',
resolveDir: pkg,
loader: "ts",
},
@@ -30,15 +34,6 @@ const bundled = await build({
const map = await import(`data:text/javascript;base64,${Buffer.from(bundled.outputFiles[0].text).toString("base64")}`);
const fixture = (name) => JSON.parse(readFileSync(resolve(pkg, "test/fixtures", name), "utf8"));
-const feed = fixture("django-health-map.json");
-const importers = fixture("django-blast-radius-query-depth1.json").transitive_affected.map((t) => t.path);
-const root = "C:/work/django";
-let trail = map.initialTrail;
-for (const p of ["django/db/models/base.py", "django/db/models/manager.py"]) {
- trail = map.reduceTrail(trail, { type: "read", path: `c:/work/django/${p}` });
-}
-trail = map.reduceTrail(trail, { type: "edit", path: "c:/work/django/django/db/models/query.py" });
-trail = map.reduceTrail(trail, { type: "callers", edits: 1, callers: { status: "ready", paths: importers } });
function time(label, work) {
for (let i = 0; i < 5; i++) work(i);
@@ -51,18 +46,35 @@ function time(label, work) {
samples.sort((a, b) => a - b);
const median = samples[Math.floor(RUNS / 2)];
const p95 = samples[Math.floor(RUNS * 0.95)];
- console.log(`${label.padEnd(32)} median ${median.toFixed(2)} ms p95 ${p95.toFixed(2)} ms`);
+ console.log(` ${label.padEnd(30)} median ${median.toFixed(2)} ms p95 ${p95.toFixed(2)} ms`);
return p95;
}
-const layout = map.layoutMap(feed.files, 180, 50, true);
-const overlay = map.resolveOverlay(layout, trail, root).overlay;
-console.log(`Django feed: ${feed.files.length} files, ${layout.drawn.length} drawn at 180x50`);
-const layoutP95 = time("layout (on resize only)", () => map.layoutMap(feed.files, 180, 50, true));
-const frameP95 = time("ripple frame + encode", (i) =>
- map.frameCells(layout, map.resolveOverlay(layout, trail, root).overlay, { kind: "ripple", t: (i % 30) / 30 }),
+/** A turn over these files: matches, two reads, the edit, and importers, all real paths of the feed. */
+function turnOver(files, importers) {
+ const paths = files.map((f) => f.file_path);
+ const edit = paths[Math.floor(paths.length / 3)];
+ return { hits: paths.slice(10, 40), reads: [paths[5], edit], named: [paths[5]], importers: importers ?? paths.slice(50, 62), edit, current: edit };
+}
+
+function bench(label, files, importers) {
+ const layout = map.layoutMap(files, { columns: 180, rows: 50, caseInsensitive: true });
+ const lit = turnOver(files, importers);
+ console.log(`${label}: ${files.length} files, ${layout.drawn.length} with a pixel, ${layout.dense ? "drawn as folders" : "a tile each"}`);
+ const layoutP95 = time("layout (on resize only)", () => map.layoutMap(files, { columns: 180, rows: 50, caseInsensitive: true }));
+ const frameP95 = time("lit frame mid-ripple + encode", (i) =>
+ map.frameCells(layout, map.resolveLit(layout, lit), { kind: "ripple", t: (i % 30) / 30 }),
+ );
+ return Math.max(layoutP95, frameP95);
+}
+
+const django = fixture("django-health-map.json").files;
+const djangoImporters = fixture("django-blast-radius-query-depth1.json").transitive_affected.map((t) => t.path);
+const worst = Math.max(
+ bench("100 files (synthetic)", map.syntheticTree(100).files),
+ bench("Django (recorded)", django, djangoImporters),
+ bench("10,000 files (synthetic, the server's 4,000 largest)", map.syntheticTree(10_000).files.slice(0, SERVER_CAP)),
);
-time("resting frame + encode", () => map.frameCells(layout, overlay));
-const ok = frameP95 <= BUDGET_MS && layoutP95 <= BUDGET_MS;
+const ok = worst <= BUDGET_MS;
console.log(ok ? `within the ${BUDGET_MS} ms budget` : `OVER the ${BUDGET_MS} ms budget`);
process.exitCode = ok ? 0 : 1;
diff --git a/packages/claude-mod/scripts/e2e.mjs b/packages/claude-mod/scripts/e2e.mjs
index 7af7f3594..d775fee03 100644
--- a/packages/claude-mod/scripts/e2e.mjs
+++ b/packages/claude-mod/scripts/e2e.mjs
@@ -249,7 +249,8 @@ async function loadLens() {
'export { callTool, warmMcp } from "./src/data/mcp";',
'export { LensMap } from "./src/map-controller";',
'export { layoutMap } from "./src/views/map";',
- 'export { resolveOverlay } from "./src/views/overlay";',
+ 'export { NO_LIT, resolveLit } from "./src/views/overlay";',
+ 'export { NO_STORY, withImporters } from "./src/model/story";',
'export { legendRows } from "./src/views/mapPane";',
'export { fromToolCall, absolutePath, savingsTotals, savingsSince } from "./src/model/events";',
'export { reduce, initialSession } from "./src/model/session";',
@@ -320,6 +321,26 @@ function rasterOf(node) {
const num = (s) => Number(s.replace(/,/g, ""));
+/**
+ * The map's scope line as numbers: total files, the largest the server sent
+ * (when capped), and the files drawn (null when drawn as folders).
+ */
+function scopeOf(all) {
+ const patterns = [
+ [/([\d,]+) largest of ([\d,]+) files; drawn as folders at this size/, (m) => ({ shown: num(m[1]), total: num(m[2]), drawn: null })],
+ [/([\d,]+) of the ([\d,]+) largest \(of ([\d,]+) files\) drawn at this size/, (m) => ({ drawn: num(m[1]), shown: num(m[2]), total: num(m[3]) })],
+ [/([\d,]+) largest of ([\d,]+) files drawn/, (m) => ({ drawn: num(m[1]), shown: num(m[1]), total: num(m[2]) })],
+ [/([\d,]+) files?, drawn as folders at this size/, (m) => ({ drawn: null, shown: num(m[1]), total: num(m[1]) })],
+ [/([\d,]+) of ([\d,]+) files? drawn at this size/, (m) => ({ drawn: num(m[1]), shown: num(m[2]), total: num(m[2]) })],
+ [/([\d,]+) files?, all drawn/, (m) => ({ drawn: num(m[1]), shown: num(m[1]), total: num(m[1]) })],
+ ];
+ for (const [re, read] of patterns) {
+ const m = all.match(re);
+ if (m) return read(m);
+ }
+ return null;
+}
+
/** Distinct files owning at least one pixel, painted independently of the layout's own `drawn`. */
function pixelOwners(layout) {
const grid = new Int32Array(layout.width * layout.height).fill(-1);
@@ -338,251 +359,327 @@ function pixelOwners(layout) {
// ---------------------------------------------------------------- the run
-async function main() {
+/** A temp dir outside any workspace: under a workspace root, `repowise serve` serves the workspace's DB, not the copy's. */
+function tempWork() {
const work = mkdtempSync(join(tmpdir(), "lens-e2e-"));
- // Under a workspace root, `repowise serve` serves the workspace's DB, not the copy's.
- for (let d = work; d !== dirname(d); d = dirname(d)) {
- if (existsSync(join(d, ".repowise-workspace.yaml"))) {
- rmSync(work, { recursive: true, force: true });
- throw new Error(`temp dir ${work} sits inside the workspace at ${d}; set TMP elsewhere`);
- }
+ const inside = [];
+ for (let d = work; d !== dirname(d); d = dirname(d)) if (existsSync(join(d, ".repowise-workspace.yaml"))) inside.push(d);
+ if (inside.length === 0) return work;
+ rmSync(work, { recursive: true, force: true });
+ throw new Error(`temp dir ${work} sits inside the workspace at ${inside[0]}; set TMP elsewhere`);
+}
+
+/** The copy, re-indexed when asked, pointed at itself and served; `live.server` is set as soon as it runs. */
+async function prepare(dest, work, live) {
+ await timed("copy", async () => copyRepo(dest));
+ facts.indexVersion = indexVersion(src);
+ if (flag("--reindex")) {
+ await timed("reindex", async () =>
+ run("repowise", ["init", ".", "--no-prose", "-y", "--no-editor-setup", "--no-hook", "--embedder", "mock", "--no-workspace"], dest, 1_800_000),
+ );
+ facts.indexVersion = `${facts.indexVersion} -> ${indexVersion(dest)} (temp copy)`;
}
- const dest = join(work, basename(src));
- let server = null;
- const mcp = mcpClient(dest);
- try {
- await timed("copy", async () => copyRepo(dest));
- facts.indexVersion = indexVersion(src);
- if (flag("--reindex")) {
- await timed("reindex", async () =>
- run("repowise", ["init", ".", "--no-prose", "-y", "--no-editor-setup", "--no-hook", "--embedder", "mock", "--no-workspace"], dest, 1_800_000),
- );
- facts.indexVersion = `${facts.indexVersion} -> ${indexVersion(dest)} (temp copy)`;
- }
- const repoId = patchLocalPath(dest);
- server = await timed("server start", () => startServer(dest, join(work, "serve.log")));
- const api = server.url;
- const L = await loadLens();
- const host = nodeHost(dest, mcp);
-
- // Discovery: the lock, the pid, /health, and this repo in the server's list.
- const found = await timed("discovery", () => L.discover(host));
- facts.mode = found.mode;
- check("discovery mode is full", found.mode === "full", `${found.mode}${found.liteReason ? ` (${found.liteReason})` : ""}`);
- check("discovered repo id matches the local_path row", found.repo?.id === repoId, `${found.repo?.id} vs ${repoId}`);
- check("discovered root is the copy", norm(found.repoRoot ?? "") === norm(dest), String(found.repoRoot));
- if (found.mode !== "full" || found.repo === undefined) return;
- await timed("freshness", () => L.readFreshness(host, found.repoRoot));
-
- // The map, as the pane draws it.
- const root = found.repoRoot;
- const repo = { id: found.repo.id, root, updatedAt: found.repo.updatedAt, caseInsensitive: L.isWindowsPath(root) };
- let redraws = 0;
- const debug = [];
- const io = {
- redraw: () => redraws++,
- debug: (m) => debug.push(m),
- blit: async () => ({}),
- openPane: async () => ({ isPlaced: true }),
- closePane: async () => {},
- };
- const map = new L.LensMap(false);
- map.setReducedMotion(true);
- map.setRepo(io, repo);
- const pane = (columns) => map.paneTree(io, { surface: "terminal", notice: "", bodyColumns: columns, placement: "dock", bodyRows: DOCK_ROWS });
- async function until(ready, label, ms = 60_000) {
- const deadline = Date.now() + ms;
- while (!ready()) {
- if (Date.now() > deadline) throw new Error(`${label} not ready in ${ms} ms (${debug.join("; ")})`);
- await sleep(20);
- }
- }
- await timed("health map", async () => {
- await map.request(io);
- await until(() => rasterOf(pane(180)) !== null || debug.some((d) => d.startsWith("health map failed")), "health map", 60_000);
- });
- const feed = await getJson(`${api}/api/repos/${repo.id}/health/map?cap=4000`);
- facts.files = feed.repository_total;
- check("health map drew", rasterOf(pane(180)) !== null, debug.join("; "));
- check("feed shown equals its files", feed.shown === feed.files.length, `${feed.shown} vs ${feed.files.length}`);
-
- facts.drawn = {};
- for (const columns of WIDTHS) {
- const tree = pane(columns);
- const raster = rasterOf(tree);
- if (!raster) {
- check(`map at ${columns} columns`, false, textsOf(tree).join(" | "));
- continue;
- }
- const layout = await timed(`layout ${columns}`, async () => L.layoutMap(feed.files, raster.props.columns, raster.props.rows, repo.caseInsensitive));
- const { owners, overlaps } = pixelOwners(layout);
- const cellsBytes = Buffer.from(raster.props.cells, "base64").length;
- check(`${columns}: raster is ${raster.props.columns}x${raster.props.rows} cells`, cellsBytes === raster.props.columns * raster.props.rows * 12, `${cellsBytes} bytes`);
- check(`${columns}: no pixel owned twice`, overlaps === 0, `${overlaps} overlaps`);
- check(`${columns}: layout drawn equals pixel owners`, layout.drawn.length === owners, `${layout.drawn.length} vs ${owners}`);
- const lines = textsOf(tree);
- check(`${columns}: legend rows fit`, lines.every((l) => l.length <= columns), lines.filter((l) => l.length > columns).join(" | "));
- const all = lines.join("\n");
- const some = all.match(/([\d,]+) of ([\d,]+) files? drawn at this size/);
- const every = all.match(/([\d,]+) files?, all drawn/);
- const drawn = some ? num(some[1]) : every ? num(every[1]) : NaN;
- const total = some ? num(some[2]) : every ? num(every[1]) : NaN;
- facts.drawn[columns] = `${drawn}/${total}`;
- check(`${columns}: legend drawn equals pixel owners`, drawn === owners, `legend ${drawn}, owners ${owners}`);
- check(`${columns}: legend total equals feed repository_total`, total === feed.repository_total, `legend ${total}, feed ${feed.repository_total}`);
- if (feed.omitted.files > 0) {
- const beyond = all.match(/([\d,]+) beyond the ([\d,]+)-file cap/);
- check(`${columns}: legend beyond-cap equals feed`, beyond !== null && num(beyond[1]) === feed.omitted.files && num(beyond[2]) === feed.cap, beyond?.[0] ?? `missing from "${lines.slice(-2).join(" / ")}" (feed: ${feed.omitted.files} beyond the ${feed.cap}-file cap)`);
- }
+ const repoId = patchLocalPath(dest);
+ live.server = await timed("server start", () => startServer(dest, join(work, "serve.log")));
+ return repoId;
+}
+
+/** Discovery: the lock, the pid, /health, and this repo in the server's list; null unless full. */
+async function discoverRepo(L, host, repoId, dest) {
+ const found = await timed("discovery", () => L.discover(host));
+ facts.mode = found.mode;
+ check("discovery mode is full", found.mode === "full", `${found.mode}${found.liteReason ? ` (${found.liteReason})` : ""}`);
+ check("discovered repo id matches the local_path row", found.repo?.id === repoId, `${found.repo?.id} vs ${repoId}`);
+ check("discovered root is the copy", norm(found.repoRoot ?? "") === norm(dest), String(found.repoRoot));
+ if (found.mode !== "full" || found.repo === undefined) return null;
+ await timed("freshness", () => L.readFreshness(host, found.repoRoot));
+ return found;
+}
+
+/** The map as the pane draws it, with a turn the run sets once it edits a file. */
+function mapSession(L, found, api) {
+ const root = found.repoRoot;
+ const repo = { id: found.repo.id, root, updatedAt: found.repo.updatedAt, caseInsensitive: L.isWindowsPath(root) };
+ const debug = [];
+ const io = { redraw: () => {}, debug: (m) => debug.push(m), blit: async () => ({}), openPane: async () => ({ isPlaced: true }), closePane: async () => {} };
+ const s = { L, api, root, repo, debug, io, turn: { lit: L.NO_LIT, story: L.NO_STORY } };
+ s.map = new L.LensMap(false, undefined, false, () => s.turn);
+ s.map.setReducedMotion(true);
+ s.map.setRepo(io, repo);
+ s.pane = (columns) => s.map.paneTree(io, { surface: "terminal", notice: "", bodyColumns: columns, placement: "dock", bodyRows: DOCK_ROWS, theme: "dark" });
+ s.until = async (ready, label, ms = 60_000) => {
+ const deadline = Date.now() + ms;
+ while (!ready()) {
+ if (Date.now() > deadline) throw new Error(`${label} not ready in ${ms} ms (${debug.join("; ")})`);
+ await sleep(20);
}
+ };
+ return s;
+}
- // Importers of an edited file against the server's direct list.
- const layout180 = L.layoutMap(feed.files, 180, DOCK_ROWS - L.legendRows(180), repo.caseInsensitive);
- const direct = async (rel) => {
- const r = await getJson(`${api}/api/repos/${repo.id}/blast-radius`, {
- method: "POST",
- headers: { "content-type": "application/json" },
- body: JSON.stringify({ changed_files: [rel], max_depth: 1 }),
- });
- return [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);
- };
- let chosen = option("--file");
- let expected = chosen ? await direct(chosen) : null;
- if (!chosen) {
- // Largest first, source before tests: a test file rarely has importers.
- const isTest = (p) => /(^|\/)(tests?|__tests__|spec)\/|[._-](test|spec)\.[a-z]+$|(^|\/)test_[^/]*$/i.test(p);
- const biggest = layout180.drawn
- .map((i) => layout180.files[i])
- .sort((a, b) => isTest(a.path) - isTest(b.path) || b.nloc - a.nloc || (a.path < b.path ? -1 : 1))
- .slice(0, CANDIDATES);
- for (const f of biggest) {
- const list = await direct(f.path);
- if (chosen === undefined || (expected.length === 0 && list.length > 0)) [chosen, expected] = [f.path, list];
- if (list.length > 0) break;
- }
+/** The health map drawn, and the feed as the server sends it. */
+async function loadMap(s) {
+ await timed("health map", async () => {
+ await s.map.request(s.io);
+ await s.until(() => rasterOf(s.pane(180)) !== null || s.debug.some((d) => d.startsWith("health map failed")), "health map", 60_000);
+ });
+ const feed = await getJson(`${s.api}/api/repos/${s.repo.id}/health/map?cap=4000`);
+ facts.files = feed.repository_total;
+ check("health map drew", rasterOf(s.pane(180)) !== null, s.debug.join("; "));
+ check("feed shown equals its files", feed.shown === feed.files.length, `${feed.shown} vs ${feed.files.length}`);
+ return feed;
+}
+
+const layoutFor = (s, feed, raster) =>
+ s.L.layoutMap(feed.files, { columns: raster.props.columns, rows: raster.props.rows, caseInsensitive: s.repo.caseInsensitive });
+
+/** The scope line against the layout: folders exactly when dense, else the drawn count; the total; the cap. */
+function checkScope({ columns, scope, layout, owners, feed }) {
+ check(`${columns}: scope says folders exactly when dense`, (scope.drawn === null) === layout.dense, `dense ${layout.dense}, scope drawn ${scope.drawn}`);
+ if (scope.drawn !== null) check(`${columns}: scope drawn equals pixel owners`, scope.drawn === owners, `scope ${scope.drawn}, owners ${owners}`);
+ check(`${columns}: scope total equals feed repository_total`, scope.total === feed.repository_total, `scope ${scope.total}, feed ${feed.repository_total}`);
+ if (feed.omitted.files > 0) check(`${columns}: capped scope names the largest the feed sent`, scope.shown === feed.files.length, `scope ${scope.shown}, feed ${feed.files.length}`);
+}
+
+/** One pane width: the raster's size, pixel ownership, rows that fit, and the scope line. */
+async function checkWidth(s, feed, columns) {
+ const tree = s.pane(columns);
+ const raster = rasterOf(tree);
+ if (!raster) return check(`map at ${columns} columns`, false, textsOf(tree).join(" | "));
+ const layout = await timed(`layout ${columns}`, async () => layoutFor(s, feed, raster));
+ const { owners, overlaps } = pixelOwners(layout);
+ const cellsBytes = Buffer.from(raster.props.cells, "base64").length;
+ check(`${columns}: raster is ${raster.props.columns}x${raster.props.rows} cells`, cellsBytes === raster.props.columns * raster.props.rows * 12, `${cellsBytes} bytes`);
+ check(`${columns}: no pixel owned twice`, overlaps === 0, `${overlaps} overlaps`);
+ check(`${columns}: layout drawn equals pixel owners`, layout.drawn.length === owners, `${layout.drawn.length} vs ${owners}`);
+ const lines = textsOf(tree);
+ check(`${columns}: legend rows fit`, lines.every((l) => l.length <= columns), lines.filter((l) => l.length > columns).join(" | "));
+ const scope = scopeOf(lines.join("\n"));
+ facts.drawn[columns] = scope === null ? "none" : `${scope.drawn ?? `${owners} as folders`}/${scope.total}`;
+ check(`${columns}: scope line read`, scope !== null, lines.slice(-3).join(" | "));
+ if (scope !== null) checkScope({ columns, scope, layout, owners, feed });
+}
+
+/** The server's direct importers of a file. */
+async function direct(s, rel) {
+ const r = await getJson(`${s.api}/api/repos/${s.repo.id}/blast-radius`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({ changed_files: [rel], max_depth: 1 }),
+ });
+ return [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);
+}
+
+const isTest = (p) => /(^|\/)(tests?|__tests__|spec)\/|[._-](test|spec)\.[a-z]+$|(^|\/)test_[^/]*$/i.test(p);
+
+/** The largest drawn files, source before tests (a test file rarely has importers). */
+function candidates(s, feed) {
+ const layout = s.L.layoutMap(feed.files, { columns: 180, rows: DOCK_ROWS - s.L.legendRows(180), caseInsensitive: s.repo.caseInsensitive });
+ const order = (a, b) => isTest(a.path) - isTest(b.path) || b.nloc - a.nloc || (a.path < b.path ? -1 : 1);
+ return layout.drawn
+ .map((i) => layout.files[i])
+ .sort(order)
+ .slice(0, CANDIDATES)
+ .map((f) => f.path);
+}
+
+/**
+ * The file to edit: `--file`, else the first of the largest few that has
+ * importers (else the largest). The blast radius answers for all its changed
+ * files at once, so each candidate is asked on its own, all together.
+ */
+async function chooseFile(s, feed) {
+ const named = option("--file");
+ if (named) return { chosen: named, expected: await direct(s, named) };
+ const paths = candidates(s, feed);
+ const lists = await Promise.all(paths.map((p) => direct(s, p)));
+ const at = Math.max(0, lists.findIndex((l) => l.length > 0));
+ return { chosen: paths[at], expected: lists[at] };
+}
+
+/** Claude edits the chosen file: the map's turn lights it, and its importers are asked for. */
+async function editChosen(s, chosen) {
+ const { L, root, repo } = s;
+ const raw = WIN ? `${root}\\${chosen.replace(/\//g, "\\")}` : `${root}/${chosen}`;
+ const ctx = { cwd: root, isWindows: repo.caseInsensitive };
+ const action = L.fromToolCall({ tool: "Edit", tool_use_id: "toolu_e2e_edit", file_path: raw }, {}, ctx);
+ const name = chosen.slice(chosen.lastIndexOf("/") + 1);
+ s.turn = {
+ lit: { ...L.NO_LIT, reads: [chosen], edits: [chosen], edit: chosen, current: chosen },
+ story: { searched: [], opened: [{ name, namedBy: null }], edited: [{ name, lines: null }] },
+ };
+ await timed("blast radius", async () => {
+ s.map.observe(s.io, action, L.absolutePath(raw, ctx));
+ await s.until(() => s.map.trail.callers?.status !== "loading", "importers", 60_000);
+ });
+ return s.map.trail.callers;
+}
+
+/** At one width: the REACHES count, every importer on the map marked, and only those. */
+function checkImportersAt(s, feed, expected, columns) {
+ const tree = s.pane(columns);
+ const raster = rasterOf(tree);
+ if (!raster) return;
+ const layout = layoutFor(s, feed, raster);
+ const resolved = s.L.resolveLit(layout, s.L.withImporters(s.turn.lit, (p) => s.map.importersOf(p)).lit);
+ // The story strip's REACHES row: `12 importers: a.py (opened), b.py, +9`.
+ const line = textsOf(tree).find((l) => /^[\d,]+ importers?: /.test(l)) ?? "";
+ const said = line.match(/^([\d,]+) importers?: /);
+ const n = said ? num(said[1]) : expected.length === 0 ? 0 : NaN;
+ check(`${columns}: REACHES importer count equals the API`, n === expected.length, `"${line}", api ${expected.length}`);
+ // Every importer the feed has (so the map draws it) is marked; a tiny file still lights a cell.
+ const key = (p) => (layout.caseInsensitive ? p.toLowerCase() : p);
+ const onMap = expected.filter((p) => layout.index.has(key(p)));
+ check(`${columns}: every importer on the map is marked`, resolved.importers.length === onMap.length, `${resolved.importers.length} marked, ${onMap.length} on the map`);
+ const drawnPaths = resolved.importers.map((i) => layout.files[i].path);
+ check(`${columns}: every marked importer is in the API list`, drawnPaths.every((p) => expected.includes(p)));
+ facts.importers[`drawn${columns}`] = resolved.importers.length;
+}
+
+/** Importers of the edited file against the server's direct list, then at each width. */
+async function checkImporters(s, feed, chosen, expected) {
+ facts.importers = { file: chosen, api: expected.length };
+ const callers = await editChosen(s, chosen);
+ check("importers loaded", callers?.status === "ready", `${callers?.status} ${s.debug.join("; ")}`);
+ facts.importers.lens = callers?.status === "ready" ? callers.paths.length : null;
+ if (callers?.status !== "ready") return;
+ const got = [...callers.paths].sort();
+ const want = [...expected].sort();
+ check("importer paths equal the blast-radius direct list", JSON.stringify(got) === JSON.stringify(want), `${got.length} vs ${want.length}`);
+ for (const columns of WIDTHS) checkImportersAt(s, feed, expected, columns);
+}
+
+/** Savings: Lens's baseline then a later read, and the raw ledger beside it. */
+async function checkSavings(s, state) {
+ const { L, api, repo } = s;
+ const first = await timed("savings", () => L.getSavings(repo.id));
+ const rawLedger = await getJson(`${api}/api/repos/${repo.id}/savings`);
+ const totals = L.savingsTotals(first);
+ check("savings tokens equal the ledger", totals.tokens === rawLedger.saved_input_tokens, `${totals.tokens} vs ${rawLedger.saved_input_tokens}`);
+ check("savings dollars equal the ledger", totals.usd === rawLedger.priced_input_savings_usd, `${totals.usd} vs ${rawLedger.priced_input_savings_usd}`);
+ const delta = L.savingsSince(L.savingsTotals(await L.getSavings(repo.id)), totals);
+ const next = delta === null ? state : L.reduce(state, { type: "savings", delta });
+ const row = next.savings === null ? null : L.savingsLine(next.savings, 180);
+ const rows = L.bandRows(next, 180);
+ const quiet = delta === null || delta.tokens === 0;
+ check(
+ "savings row absent or equal to the ledger delta",
+ quiet ? next.savings === null && !rows.some((r) => r.includes("saved")) : rows.includes(row),
+ delta === null ? "ledger shrank" : `${delta.tokens} tokens since the baseline`,
+ );
+ facts.savingsTokens = rawLedger.saved_input_tokens;
+ return next;
+}
+
+/** The review card after an edit: renders, counts the one changed file, and its test total is the tool's. */
+function checkEditedReview(L, risk, state) {
+ const next = L.reduce(state, { type: "reviewed", risk });
+ const card = L.reviewText(next.review.outcome);
+ check("edited tree: review card renders", typeof card === "string" && card.length > 0, card?.split("\n")[0] ?? "null");
+ check("edited tree: card counts the one changed file", typeof card === "string" && card.includes("1 changed file"), card ?? "null");
+ const tests = L.testsToRun(risk);
+ if (tests !== null && risk.impacted_tests?.total !== undefined) check("review test total equals the tool's", tests.total === risk.impacted_tests.total, `${tests.total}`);
+ facts.review = { ms: timings["change risk"], overLensTimeout: timings["change risk"] > 20_000, percentile: risk.risk_percentile ?? null };
+ return next;
+}
+
+/**
+ * The change review through the MCP layer, headless over stdio: first the
+ * clean copy (nothing to say), then after a one-line edit to the chosen file
+ * (the copy only).
+ */
+async function checkReview(s, chosen, state) {
+ const { L, host, dest } = s;
+ L.warmMcp(host);
+ await timed("mcp connect", () => host.mcp.server());
+ await sleep(0);
+ const review = () => L.callTool(host, "get_change_risk", {}, { timeoutMs: 120_000 });
+ const clean = await timed("change risk (clean)", review);
+ const quiet = L.reduce(state, { type: "reviewed", risk: clean });
+ const quietBand = L.bandView(quiet, { columns: 180, hasSurvey: false });
+ const noRow = quietBand === null || !textsOf(quietBand).some((l) => l.startsWith("review"));
+ check("clean tree: no review card and no review row", L.reviewText(quiet.review.outcome) === null && noRow, L.reviewText(quiet.review.outcome) ?? "card null");
+ appendFileSync(join(dest, ...chosen.split("/")), "\n");
+ return checkEditedReview(L, await timed("change risk", review), state);
+}
+
+/** The band at each width, as the session would hold it. */
+function checkBands(L, state) {
+ for (const columns of WIDTHS) {
+ try {
+ const band = L.bandView(state, { columns, hasSurvey: false });
+ const lines = band === null ? [] : textsOf(band);
+ check(`${columns}: band rows fit`, lines.every((l) => l.length <= columns), lines.join(" | "));
+ } catch (err) {
+ check(`${columns}: band renders`, false, String(err));
}
- facts.importers = { file: chosen, api: expected.length };
- const raw = WIN ? `${root}\\${chosen.replace(/\//g, "\\")}` : `${root}/${chosen}`;
- const ctx = { cwd: root, isWindows: repo.caseInsensitive };
- const action = L.fromToolCall({ tool: "Edit", tool_use_id: "toolu_e2e_edit", file_path: raw }, {}, ctx);
- await timed("blast radius", async () => {
- map.observe(io, action, L.absolutePath(raw, ctx));
- await until(() => map.trail.callers?.status !== "loading", "importers", 60_000);
- });
- const callers = map.trail.callers;
- check("importers loaded", callers?.status === "ready", `${callers?.status} ${debug.join("; ")}`);
- if (callers?.status === "ready") {
- const got = [...callers.paths].sort();
- const want = [...expected].sort();
- check("importer paths equal the blast-radius direct list", JSON.stringify(got) === JSON.stringify(want), `${got.length} vs ${want.length}`);
- for (const columns of WIDTHS) {
- const tree = pane(columns);
- const raster = rasterOf(tree);
- if (!raster) continue;
- const layout = L.layoutMap(feed.files, raster.props.columns, raster.props.rows, repo.caseInsensitive);
- const resolved = L.resolveOverlay(layout, map.trail, root);
- const all = textsOf(tree).join("\n");
- const line = textsOf(tree).find((l) => l.startsWith("edited ")) ?? "";
- // Narrow panes use the short form: `edited x.py · 12 import it · 3 not drawn`.
- const said = line.match(/([\d,]+) (?:files? )?imports? it/);
- const notDrawn = line.match(/· ([\d,]+) not drawn/);
- const n = said ? num(said[1]) : NaN;
- const missing = notDrawn ? num(notDrawn[1]) : 0;
- const unmarked = expected.length - resolved.overlay.callers.length;
- check(`${columns}: legend importer count equals the API`, n === expected.length, `legend ${n}, api ${expected.length}`);
- check(`${columns}: overlay not-drawn importers equal the API's unmarked`, resolved.edit?.notDrawn === unmarked, `${resolved.edit?.notDrawn} vs ${unmarked}`);
- check(`${columns}: legend states the not-drawn importers`, missing === unmarked, `"${line}" (${unmarked} not drawn)`);
- const drawnPaths = resolved.overlay.callers.map((i) => layout.files[i].path);
- check(`${columns}: every marked importer is in the API list`, drawnPaths.every((p) => expected.includes(p)));
- facts.importers[`drawn${columns}`] = resolved.overlay.callers.length;
- }
+ }
+}
+
+/** Savings and the review, unless `--map-only`; a review that fails is a failed check, not a failed run. */
+async function checkSession(s, chosen) {
+ let state = s.L.reduce(s.L.initialSession, { type: "discovered", mode: "full", freshness: null, repoRoot: s.root });
+ if (flag("--map-only")) return state;
+ state = await checkSavings(s, state);
+ try {
+ return await checkReview(s, chosen, state);
+ } catch (err) {
+ check("change review ran", false, String(err));
+ return state;
+ }
+}
+
+/** Every phase in order, on a copy served from `live.server`. */
+async function runAll(dest, work, mcp, live) {
+ const repoId = await prepare(dest, work, live);
+ const L = await loadLens();
+ const host = nodeHost(dest, mcp);
+ const found = await discoverRepo(L, host, repoId, dest);
+ if (found === null) return;
+ // The same object the map's turn source reads, so a turn set later reaches it.
+ const s = Object.assign(mapSession(L, found, live.server.url), { host, dest });
+ const feed = await loadMap(s);
+ facts.drawn = {};
+ for (const columns of WIDTHS) await checkWidth(s, feed, columns);
+ const { chosen, expected } = await chooseFile(s, feed);
+ await checkImporters(s, feed, chosen, expected);
+ checkBands(L, await checkSession(s, chosen));
+ s.map.dispose();
+}
+
+/** The server, the MCP child and the copy are always removed, pass or fail. */
+async function cleanup(mcp, server, dest, work) {
+ killTree(mcp.pid());
+ if (server) {
+ killTree(server.child.pid);
+ // The lock names the python process itself; stop it too if the launcher left it.
+ try {
+ killTree(JSON.parse(readFileSync(join(dest, ".repowise", "serve.lock.json"), "utf8")).pid);
+ } catch {
+ // removed by the server on exit
}
- facts.importers.lens = callers?.status === "ready" ? callers.paths.length : null;
-
- // Band rows as the session would hold them.
- let state = L.reduce(L.initialSession, { type: "discovered", mode: "full", freshness: null, repoRoot: root });
-
- if (!flag("--map-only")) {
- // Savings: Lens's baseline then a later read, and the raw ledger beside it.
- const first = await timed("savings", () => L.getSavings(repo.id));
- const rawLedger = await getJson(`${api}/api/repos/${repo.id}/savings`);
- const totals = L.savingsTotals(first);
- check("savings tokens equal the ledger", totals.tokens === rawLedger.saved_input_tokens, `${totals.tokens} vs ${rawLedger.saved_input_tokens}`);
- check("savings dollars equal the ledger", totals.usd === rawLedger.priced_input_savings_usd, `${totals.usd} vs ${rawLedger.priced_input_savings_usd}`);
- const delta = L.savingsSince(L.savingsTotals(await L.getSavings(repo.id)), totals);
- if (delta !== null) state = L.reduce(state, { type: "savings", delta });
- const row = state.savings === null ? null : L.savingsLine(state.savings, 180);
- const rows = L.bandRows(state, 180);
- check(
- "savings row absent or equal to the ledger delta",
- delta === null || delta.tokens === 0 ? state.savings === null && !rows.some((r) => r.includes("saved")) : rows.includes(row),
- delta === null ? "ledger shrank" : `${delta.tokens} tokens since the baseline`,
- );
- facts.savingsTokens = rawLedger.saved_input_tokens;
-
- // The change review through the MCP layer, headless over stdio: first
- // the clean copy (nothing to say), then after a one-line edit to the
- // chosen file (the copy only).
- try {
- L.warmMcp(host);
- await timed("mcp connect", () => host.mcp.server());
- await sleep(0);
- const review = () => L.callTool(host, "get_change_risk", {}, { timeoutMs: 120_000 });
- const clean = await timed("change risk (clean)", review);
- const quiet = L.reduce(state, { type: "reviewed", risk: clean });
- const quietBand = L.bandView(quiet, { columns: 180, hasSurvey: false });
- check(
- "clean tree: no review card and no review row",
- L.reviewText(quiet.review.outcome) === null && (quietBand === null || !textsOf(quietBand).some((l) => l.startsWith("review"))),
- L.reviewText(quiet.review.outcome) ?? "card null",
- );
- appendFileSync(join(dest, ...chosen.split("/")), "\n");
- const risk = await timed("change risk", review);
- state = L.reduce(state, { type: "reviewed", risk });
- const card = L.reviewText(state.review.outcome);
- check("edited tree: review card renders", typeof card === "string" && card.length > 0, card?.split("\n")[0] ?? "null");
- check("edited tree: card counts the one changed file", typeof card === "string" && card.includes("1 changed file"), card ?? "null");
- const tests = L.testsToRun(risk);
- if (tests !== null && risk.impacted_tests?.total !== undefined) {
- check("review test total equals the tool's", tests.total === risk.impacted_tests.total, `${tests.total}`);
- }
- facts.review = { ms: timings["change risk"], overLensTimeout: timings["change risk"] > 20_000, percentile: risk.risk_percentile ?? null };
- } catch (err) {
- check("change review ran", false, String(err));
- }
+ }
+ for (let i = 0; i < 10 && existsSync(work); i++) {
+ try {
+ rmSync(work, { recursive: true, force: true, maxRetries: 3 });
+ } catch {
+ await sleep(1000);
}
+ }
+ if (existsSync(work)) console.error(`could not remove ${work}`);
+}
- for (const columns of WIDTHS) {
- try {
- const band = L.bandView(state, { columns, hasSurvey: false });
- const lines = band === null ? [] : textsOf(band);
- check(`${columns}: band rows fit`, lines.every((l) => l.length <= columns), lines.join(" | "));
- } catch (err) {
- check(`${columns}: band renders`, false, String(err));
- }
- }
- map.dispose();
+async function main() {
+ const work = tempWork();
+ const dest = join(work, basename(src));
+ const live = { server: null };
+ const mcp = mcpClient(dest);
+ try {
+ await runAll(dest, work, mcp, live);
} catch (err) {
check("run completed", false, err instanceof Error ? err.message : String(err));
} finally {
- killTree(mcp.pid());
- if (server) {
- killTree(server.child.pid);
- // The lock names the python process itself; stop it too if the launcher left it.
- try {
- killTree(JSON.parse(readFileSync(join(dest, ".repowise", "serve.lock.json"), "utf8")).pid);
- } catch {
- // removed by the server on exit
- }
- }
- for (let i = 0; i < 10 && existsSync(work); i++) {
- try {
- rmSync(work, { recursive: true, force: true, maxRetries: 3 });
- } catch {
- await sleep(1000);
- }
- }
- if (existsSync(work)) console.error(`could not remove ${work}`);
+ await cleanup(mcp, live.server, dest, work);
}
}
diff --git a/packages/claude-mod/src/animator.ts b/packages/claude-mod/src/animator.ts
new file mode 100644
index 000000000..de5c658ab
--- /dev/null
+++ b/packages/claude-mod/src/animator.ts
@@ -0,0 +1,109 @@
+/**
+ * One animation at a time for the pane, whichever tab drives it: a frame every
+ * FRAME_MS for the animation's length, each frame blitted into the Raster it
+ * names, one blit at a time. A frame source returning null (its tab went off
+ * screen) ends the animation; a refused blit stops it and asks for a redraw,
+ * which draws the resting frame. It never sees `$`: register.ts hands it
+ * closures from each hook it enters (`use`), and the timer uses the latest,
+ * never one kept from an earlier hook.
+ */
+
+import { FRAME_MS } from "./views/overlay";
+
+export interface AnimIO {
+ redraw(): void;
+ /** Debug log only (`--debug-file`), never the user's screen. */
+ debug(message: string): void;
+ blit(key: string, cells: string, columns: number, rows: number): Promise<{ deny?: string }>;
+}
+
+/** One frame for a Raster; null once its tab is off screen. */
+export type Frame = { key: string; cells: string; columns: number; rows: number } | null;
+
+/** Where an animation stands: its kind and `t` from 0 to 1. */
+export interface Step {
+ kind: string;
+ t: number;
+}
+
+export class Animator {
+ private anim: { kind: string; start: number; duration: number } | null = null;
+ private timer: ReturnType<typeof setInterval> | undefined;
+ private blitting = false;
+ private stopped = false;
+ private io: AnimIO | null = null;
+
+ /** The closures of the hook running now; the timer's next frame goes through them. */
+ use(io: AnimIO): void {
+ this.io = io;
+ }
+
+ progress(now: number): Step | undefined {
+ const a = this.anim;
+ return a === null ? undefined : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };
+ }
+
+ /**
+ * Plays `kind` for `duration` ms, replacing whatever played. `redraw` false
+ * when called from a render, which already draws the first step.
+ */
+ play(io: AnimIO, kind: string, duration: number, screen: (step: Step) => Frame, redraw = true): void {
+ this.stop();
+ if (this.stopped) return;
+ this.io = io;
+ this.anim = { kind, start: Date.now(), duration };
+ if (redraw) io.redraw();
+ this.timer = setInterval(() => this.tick(screen), FRAME_MS);
+ }
+
+ stop(): void {
+ clearInterval(this.timer);
+ this.timer = undefined;
+ this.anim = null;
+ }
+
+ /** For good: a disposed session plays nothing more. */
+ end(): void {
+ this.stopped = true;
+ this.stop();
+ }
+
+ /** A timer's frame: never throws out of the timer; a failure stops the animation. */
+ private tick(screen: (step: Step) => Frame): void {
+ try {
+ this.frame(screen);
+ } catch (err) {
+ this.failed(err);
+ }
+ }
+
+ /** A failed frame: the animation stops and the failure goes to the debug log. */
+ private failed(err: unknown): void {
+ this.stop();
+ this.io?.debug(`animation failed: ${String(err)}`);
+ }
+
+ private frame(screen: (step: Step) => Frame): void {
+ const step = this.progress(Date.now());
+ const frame = step === undefined ? null : screen(step);
+ const io = this.io;
+ if (step === undefined || frame === null || io === null) return this.stop();
+ // One blit at a time: a slow surface drops frames rather than queueing them.
+ if (this.blitting) return;
+ if (step.t >= 1) this.stop();
+ this.blitting = true;
+ io.blit(frame.key, frame.cells, frame.columns, frame.rows)
+ .then((r) => r.deny === undefined || this.refused(io, r.deny))
+ .catch((err: unknown) => this.refused(io, String(err)))
+ .finally(() => {
+ this.blitting = false;
+ });
+ }
+
+ /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */
+ private refused(io: AnimIO, why: string): void {
+ io.debug(`blit refused: ${why}`);
+ this.stop();
+ if (!this.stopped) io.redraw();
+ }
+}
diff --git a/packages/claude-mod/src/data/mcp.ts b/packages/claude-mod/src/data/mcp.ts
index 8135cbf6e..5730dfe98 100644
--- a/packages/claude-mod/src/data/mcp.ts
+++ b/packages/claude-mod/src/data/mcp.ts
@@ -117,15 +117,22 @@ export function callTool<T>(
}
// Typed here, not shared: the MCP server has no generated TypeScript types,
-// and Lens reads three fields of a larger card.
+// and Lens reads a few fields of a larger card.
interface ContextTarget {
error?: string;
callers?: unknown[];
callers_total?: number;
- ownership?: { contributor_count?: number | null };
+ hotspot?: boolean;
+ ownership?: { contributor_count?: number | null; recent_owner?: string | null; recent_owner_pct?: number | null };
}
-/** The file card's caller and contributor counts; null when the index does not know the file. */
+function recentOwner(o: ContextTarget["ownership"]): FileContext["recentOwner"] {
+ const name = o?.recent_owner;
+ const share = o?.recent_owner_pct;
+ return typeof name === "string" && name !== "" && typeof share === "number" ? { name, share } : null;
+}
+
+/** The file card's caller and contributor counts, hotspot mark and recent owner; null when the index does not know the file. */
export async function fetchFileContext(host: Host, path: string): Promise<FileContext | null> {
const result = await callTool<{ targets?: Record<string, ContextTarget> }>(host, "get_context", {
targets: [path],
@@ -140,5 +147,7 @@ export async function fetchFileContext(host: Host, path: string): Promise<FileCo
return {
callerFiles: typeof callers === "number" ? callers : null,
contributors: typeof contributors === "number" ? contributors : null,
+ hotspot: typeof target.hotspot === "boolean" ? target.hotspot : null,
+ recentOwner: recentOwner(target.ownership),
};
}
diff --git a/packages/claude-mod/src/flow-controller.ts b/packages/claude-mod/src/flow-controller.ts
new file mode 100644
index 000000000..05cf36681
--- /dev/null
+++ b/packages/claude-mod/src/flow-controller.ts
@@ -0,0 +1,137 @@
+/**
+ * Flow's session: its model, the redraws (at most 8 a second, and only
+ * while the Flow tab is on screen) and the owl's clock (ticking only while
+ * Claude works and Flow is on screen). One instance per session; a disposed
+ * one stops its timers. It never sees `$`: each hook hands it a fresh IO,
+ * and timers use the latest one, never one kept from an earlier hook.
+ */
+
+import { initialFlow, isWorking, reduceFlow, type FlowAction, type FlowState } from "./model/flow";
+import type { ChangeRisk } from "./model/review";
+import type { FileContext, Mode } from "./model/session";
+import type { Node } from "./views/elements";
+import { flowView, HAPPY_MS } from "./views/flow";
+import { BLINK_MS } from "./views/owl";
+
+/** At most 8 redraws a second. */
+export const REDRAW_MS = 125;
+/** With reduced motion the owl holds still; the turn's clock still counts seconds. */
+const STILL_TICK_MS = 1_000;
+/** Redraws unanswered this long mean the pane is gone (closed, or another tab). */
+const GONE_MS = 1_000;
+
+export interface FlowIO {
+ redraw(): void;
+ debug(message: string): void;
+}
+
+export interface FlowPane {
+ columns: number;
+ rows: number;
+ mode: Mode | null;
+ contexts: Readonly<Record<string, FileContext>>;
+ review: ChangeRisk | null;
+ light?: boolean;
+}
+
+export class LensFlow {
+ state: FlowState = initialFlow;
+ /** Flow is on screen: set by its render; cleared by another tab, or by a redraw no render answered. */
+ private shown = false;
+ private still = false;
+ private io: FlowIO | null = null;
+ private lastDraw = Number.NEGATIVE_INFINITY;
+ /** When the first redraw no Flow render has answered was asked for; null once one did. */
+ private unansweredSince: number | null = null;
+ private pending: ReturnType<typeof setTimeout> | undefined;
+ private ticker: ReturnType<typeof setInterval> | undefined;
+ private happy: ReturnType<typeof setTimeout> | undefined;
+
+ setReducedMotion(on: boolean): void {
+ this.still = on;
+ }
+
+ /** Another tab is shown, or the pane is gone: nothing of Flow is on screen. */
+ hide(): void {
+ this.shown = false;
+ this.stopTick();
+ }
+
+ dispatch(io: FlowIO, action: FlowAction): void {
+ this.io = io;
+ const next = reduceFlow(this.state, action);
+ if (next === this.state) return;
+ this.state = next;
+ if (action.type === "turnEnded") this.afterTurn();
+ this.request();
+ }
+
+ /** The tab's tree at `now`; a render marks Flow on screen and keeps the owl's clock going while Claude works. */
+ paneTree(io: FlowIO, pane: FlowPane, now: number): Node {
+ this.io = io;
+ this.shown = true;
+ this.unansweredSince = null;
+ this.ensureTick();
+ return flowView(this.state, { ...pane, now, still: this.still });
+ }
+
+ dispose(): void {
+ this.hide();
+ clearTimeout(this.pending);
+ clearTimeout(this.happy);
+ this.pending = undefined;
+ this.happy = undefined;
+ this.io = null;
+ }
+
+ /** A redraw now, or once the throttle allows; nothing while Flow is not on screen. */
+ private request(): void {
+ if (!this.shown || this.pending !== undefined) return;
+ const wait = this.lastDraw + REDRAW_MS - Date.now();
+ if (wait <= 0) return this.draw();
+ this.pending = setTimeout(() => this.timer(() => ((this.pending = undefined), true)), wait);
+ }
+
+ /** A timer's body: its step says whether to redraw; a failure is logged, never thrown into the runtime. */
+ private timer(step: () => boolean): void {
+ try {
+ if (step()) this.draw();
+ } catch (err) {
+ this.io?.debug(`flow timer failed: ${String(err)}`);
+ }
+ }
+
+ /** Redraws, unless redraws have gone unanswered for a while: then the pane is gone and Flow stops asking. */
+ private draw(): void {
+ const now = Date.now();
+ if (this.unansweredSince !== null && now - this.unansweredSince >= GONE_MS) return this.hide();
+ if (!this.shown || this.io === null) return;
+ this.lastDraw = now;
+ this.unansweredSince ??= now;
+ this.io.redraw();
+ }
+
+ /** The owl is happy for a moment, then sleeps: one redraw when that moment ends. */
+ private afterTurn(): void {
+ this.stopTick();
+ clearTimeout(this.happy);
+ this.happy = setTimeout(() => this.timer(() => ((this.happy = undefined), true)), HAPPY_MS);
+ }
+
+ private ensureTick(): void {
+ if (this.ticker !== undefined || !this.shown || !isWorking(this.state)) return;
+ this.ticker = setInterval(() => this.timer(() => this.tick()), this.still ? STILL_TICK_MS : BLINK_MS);
+ }
+
+ /** Redraw while Claude works; stop once it is done. Off screen, `draw` stops it. */
+ private tick(): boolean {
+ if (isWorking(this.state)) return true;
+ this.stopTick();
+ return false;
+ }
+
+ private stopTick(): void {
+ clearInterval(this.ticker);
+ this.ticker = undefined;
+ }
+}
diff --git a/packages/claude-mod/src/format.ts b/packages/claude-mod/src/format.ts
index b1a0e9f50..07ac1b353 100644
--- a/packages/claude-mod/src/format.ts
+++ b/packages/claude-mod/src/format.ts
@@ -14,3 +14,16 @@ export function fit(text: string, columns: number): string {
if (text.length <= columns) return text;
return `${text.slice(0, columns - 1).trimEnd()}…`;
}
+
+/** Code points that are not one terminal cell: controls, lone surrogates, East Asian wide and fullwidth. */
+const NOT_ONE_CELL = /[\u0000-\u001f\u007f-\u009f\ud800-\udfffᄀ-ᅟ⺀-꓏가-힣豈-﫿︰-﹏＀-⦆¢-₩]/;
+
+/**
+ * `text` with every code point that is not one terminal cell (outside the
+ * BMP, a lone surrogate, East Asian wide, a control) replaced by `?`, so its
+ * length is its width in cells.
+ */
+export function cellSafe(text: string): string {
+ // A code point outside the BMP comes out of Array.from as two code units.
+ return Array.from(text, (ch) => (ch.length === 1 && !NOT_ONE_CELL.test(ch) ? ch : "?")).join("");
+}
diff --git a/packages/claude-mod/src/map-controller.ts b/packages/claude-mod/src/map-controller.ts
index 26ef5db80..ad43b9b1c 100644
--- a/packages/claude-mod/src/map-controller.ts
+++ b/packages/claude-mod/src/map-controller.ts
@@ -8,20 +8,24 @@
* or an auto-open that was placed).
*/
-import { analyzeBlastRadius } from "@repowise-dev/api-client/blast-radius";
+import { analyzeBlastRadius, type BlastRadiusResponse } from "@repowise-dev/api-client/blast-radius";
import { getHealthMap } from "@repowise-dev/api-client/code-health";
import type { HealthMapFeed } from "@repowise-dev/types/health";
import { formatRelativeTimeOrNull } from "@repowise-dev/ui/lib/format";
+import { Animator, type AnimIO, type Frame, type Step } from "./animator";
import { withTimeout } from "./data/transport";
import type { UiOpenResult } from "./mod-api";
import { relativeTo } from "./model/events";
-import { initialTrail, reduceTrail, type TrailAction, type TrailState } from "./model/trail";
+import { NO_STORY, withImporters, type Reach, type Story } from "./model/story";
+import { initialTrail, reduceTrail, type Callers, type TrailAction, type TrailState } from "./model/trail";
import { MAP_COPY, notPlacedLine, type ScopeFacts } from "./views/copy";
import type { Node } from "./views/elements";
-import { layoutMap, type MapLayout } from "./views/map";
+import { layoutMap, type MapLayout, type MapStyle } from "./views/map";
import { mapPaneView, mapSize, noticeView, type PaneSize } from "./views/mapPane";
import { desktopSize, svgPaneView } from "./views/mapSvg";
-import { FLASH_MS, FRAME_MS, RIPPLE_MS, frameCells, resolveOverlay, rippleRadius, type Anim } from "./views/overlay";
+import { FLASH_MS, NO_LIT, RIPPLE_MS, frameCells, notOnMap, resolveLit, rippleRadius, type Anim, type Lit } from "./views/overlay";
+import { MAP_KEY } from "./views/mapPane";
+import type { ThemeName } from "./views/theme";
/** The server's own maximum: Django's 2,347 drawable files fit in one call. */
const MAP_CAP = 4_000;
@@ -30,14 +34,12 @@ const CALLERS_TIMEOUT_MS = 20_000;
/** Direct importers only: 0.6 s on Django's query.py, against 2 s for three levels. */
const CALLERS_DEPTH = 1;
-export interface MapIO {
- redraw(): void;
- /** Debug log only (`--debug-file`), never the user's screen. */
- debug(message: string): void;
- blit(cells: string, columns: number, rows: number): Promise<{ deny?: string }>;
+export interface MapIO extends AnimIO {
/** `focus` only when the person asked for the pane; an automatic open never takes the keyboard. */
openPane(focus: boolean): Promise<UiOpenResult>;
closePane(): Promise<void>;
+ /** The whole blast radius answer for an edited file, for Flow; the map keeps only the importers. */
+ blastLanded?(path: string, r: BlastRadiusResponse): void;
}
/** The repo the map draws, once discovery found the local server for it. */
@@ -55,80 +57,29 @@ export interface PaneInput extends PaneSize {
surface: string | undefined;
/** Why there is no repo to draw, when there is none. */
notice: string;
+ theme: ThemeName;
}
-function scopeFacts(layout: MapLayout, data: HealthMapFeed, repo: MapRepo): ScopeFacts {
+/** The current turn as it stands: what it lit (before its importers are joined) and its story. */
+export type TurnSource = () => { lit: Lit; story: Story };
+
+const NO_TURN: TurnSource = () => ({ lit: NO_LIT, story: NO_STORY });
+
+function scopeFacts(layout: MapLayout, data: HealthMapFeed, repo: MapRepo, offMap: number): ScopeFacts {
return {
drawn: layout.drawn.length,
+ shown: data.files.length,
repositoryTotal: data.repository_total,
indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,
beyondCap: data.omitted.files,
- cap: data.cap,
+ dense: layout.dense,
+ notOnMap: offMap,
};
}
-/** What an animation draws on: the frame for a step, or null once nothing is on screen. */
-type Screen = (step: Anim) => { cells: string; columns: number; rows: number } | null;
-
-/**
- * Plays a flash or a ripple with blits, a frame every FRAME_MS for about a
- * second, one blit at a time. Stops on a refused blit and asks for a redraw,
- * which draws the resting frame.
- */
-class Animator {
- private anim: { kind: Anim["kind"]; start: number; duration: number } | null = null;
- private timer: ReturnType<typeof setInterval> | undefined;
- private blitting = false;
- private stopped = false;
-
- progress(now: number): Anim | undefined {
- const a = this.anim;
- return a === null ? undefined : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };
- }
-
- play(io: MapIO, kind: Anim["kind"], screen: Screen): void {
- this.stop();
- if (this.stopped) return;
- this.anim = { kind, start: Date.now(), duration: kind === "flash" ? FLASH_MS : RIPPLE_MS };
- io.redraw();
- this.timer = setInterval(() => this.tick(io, screen), FRAME_MS);
- }
-
- stop(): void {
- clearInterval(this.timer);
- this.timer = undefined;
- this.anim = null;
- }
-
- /** For good: a disposed map plays nothing more. */
- end(): void {
- this.stopped = true;
- this.stop();
- }
-
- private tick(io: MapIO, screen: Screen): void {
- const step = this.progress(Date.now());
- const frame = step === undefined ? null : screen(step);
- if (step === undefined || frame === null) return this.stop();
- // One blit at a time: a slow surface drops frames rather than queueing them.
- if (this.blitting) return;
- if (step.t >= 1) this.stop();
- this.blitting = true;
- io.blit(frame.cells, frame.columns, frame.rows)
- .then((r) => r.deny === undefined || this.refused(io, r.deny))
- .catch((err: unknown) => this.refused(io, String(err)))
- .finally(() => {
- this.blitting = false;
- });
- }
-
- /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */
- private refused(io: MapIO, why: string): void {
- io.debug(`blit refused: ${why}`);
- this.stop();
- if (!this.stopped) io.redraw();
- }
-}
+type LayoutKey = { data: HealthMapFeed; columns: number; rows: number; style: MapStyle };
+const keyParts = (k: LayoutKey): unknown[] => [k.data, k.columns, k.rows, k.style.theme, k.style.health];
+const sameKey = (a: LayoutKey, b: LayoutKey): boolean => keyParts(a).every((v, i) => v === keyParts(b)[i]);
export class LensMap {
trail: TrailState = initialTrail;
@@ -139,19 +90,52 @@ export class LensMap {
private feed: Feed = { status: "idle" };
private requested = false;
private autoOpenTried = false;
- /** The latest edit's absolute path with its case, for the importers request. */
+ /** The latest edit's absolute path with its case. */
private editPath: string | null = null;
- /** The edit whose importers were asked for, so each is asked once. */
- private callersAsked = 0;
+ /**
+ * Every file edited this session (absolute, case kept), and the importers
+ * of each, asked once per distinct path. Ceiling: never asked again, so an
+ * index update mid-session is not seen; nothing tells Lens it changed.
+ */
+ private readonly edited = new Set<string>();
+ private readonly importers = new Map<string, Callers>();
private drawn: { layout: MapLayout; root: string } | null = null;
- private layoutCache: { data: HealthMapFeed; columns: number; rows: number; layout: MapLayout } | null = null;
- private readonly animator = new Animator();
+ private layoutCache: { key: LayoutKey; layout: MapLayout } | null = null;
private reducedMotion = false;
+ /** Health colours on the tiles: off by default (`lens_map_health`), toggled from the pane. */
+ private health: boolean;
+ /** Read at every frame, so an animation sees the turn as it is now. */
+ private readonly turn: TurnSource;
private readonly autoOpenOnRead: boolean;
+ /** The pane's one animator, shared with the trail: whichever tab is shown drives it. */
+ private readonly animator: Animator;
- constructor(autoOpenOnRead: boolean) {
+ constructor(autoOpenOnRead: boolean, animator: Animator = new Animator(), health = false, turn: TurnSource = NO_TURN) {
this.autoOpenOnRead = autoOpenOnRead;
+ this.animator = animator;
+ this.health = health;
+ this.turn = turn;
+ }
+
+ /** The importers of a repo-relative path, as far as they are known; null when never asked. */
+ importersOf(path: string): Callers | null {
+ return this.importers.get(this.keyOf(path)) ?? null;
+ }
+
+ private keyOf(rel: string): string {
+ return this.repo?.caseInsensitive === false ? rel : rel.toLowerCase();
+ }
+
+ /** The pane's toggle: health colours on the tiles, or the quiet ghost map. */
+ toggleHealth(io: MapIO): void {
+ this.health = !this.health;
+ io.redraw();
+ }
+
+ /** What the turn lit, with the latest edit's importers joined as they stand now. */
+ private lighting(): { lit: Lit; reach: Reach | null } {
+ return withImporters(this.turn().lit, (p) => this.importersOf(p));
}
/** The band row the map wants shown, if any. */
@@ -169,6 +153,19 @@ export class LensMap {
this.animator.end();
}
+ /**
+ * A `/clear`: the conversation's trail and edits go, so nothing of it stays
+ * lit. The feed, the repo and the importers already asked for (index data,
+ * by path) stay, and so does an open pane.
+ */
+ clearConversation(io: MapIO): void {
+ this.trail = initialTrail;
+ this.edited.clear();
+ this.editPath = null;
+ this.band = null;
+ io.redraw();
+ }
+
setRepo(io: MapIO, repo: MapRepo | null): void {
this.repo = repo;
this.fetchWanted(io);
@@ -176,6 +173,7 @@ export class LensMap {
/** One observed tool call; `editPath` is the edited file's absolute path, case kept. */
observe(io: MapIO, action: TrailAction, editPath: string | null): void {
+ if (action.type === "edit" && editPath !== null) this.edited.add(editPath);
if (action.type === "edit") this.editPath = editPath;
this.apply(io, action);
if (action.type === "edit") this.fetchWanted(io);
@@ -210,14 +208,17 @@ export class LensMap {
if (notice !== null) return noticeView(notice, pane.bodyColumns);
const { data } = this.feed as { data: HealthMapFeed };
const repo = this.repo as MapRepo;
- // The terminal draws cells and the desktop app SVG, with no blits: its resting frame redraws as the trail grows.
+ // The terminal draws cells and the desktop app SVG, with no blits: its resting frame redraws as the turn goes on.
const desktop = pane.surface === "desktop";
- const layout = this.layoutFor(data, desktop ? desktopSize(mapSize(pane)) : mapSize(pane), repo.caseInsensitive);
- const resolved = resolveOverlay(layout, this.trail, repo.root);
- const scope = scopeFacts(layout, data, repo);
- if (desktop) return svgPaneView(layout, resolved, scope);
+ const style: MapStyle = { theme: pane.theme, health: this.health };
+ const size = mapSize(pane, this.health);
+ const layout = this.layoutFor({ data, ...(desktop ? desktopSize(size) : size), style }, repo.caseInsensitive);
+ const { lit, reach } = this.lighting();
+ const overlay = resolveLit(layout, lit);
+ const parts = { story: this.turn().story, reach, scope: scopeFacts(layout, data, repo, notOnMap(layout, lit)) };
+ if (desktop) return svgPaneView(layout, overlay, parts);
this.drawn = { layout, root: repo.root };
- return mapPaneView(layout, frameCells(layout, resolved.overlay, this.animator.progress(Date.now())), resolved, scope);
+ return mapPaneView(layout, frameCells(layout, overlay, mapStep(this.animator.progress(Date.now()))), parts);
}
/** Why there is no map to draw yet (and the feed fetch started when wanted), or null once it can be drawn. */
@@ -231,18 +232,13 @@ export class LensMap {
return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;
}
- private layoutFor(data: HealthMapFeed, size: { columns: number; rows: number }, caseInsensitive: boolean): MapLayout {
- const cached = this.cachedLayout(data, size);
- if (cached !== null) return cached;
- const layout = layoutMap(data.files, size.columns, size.rows, caseInsensitive);
- this.layoutCache = { data, columns: size.columns, rows: size.rows, layout };
- return layout;
- }
-
- private cachedLayout(data: HealthMapFeed, size: { columns: number; rows: number }): MapLayout | null {
+ /** The layout for this feed, size and style; laid out again only when one of them changed. */
+ private layoutFor(key: LayoutKey, caseInsensitive: boolean): MapLayout {
const c = this.layoutCache;
- const same = c !== null && c.data === data && c.columns === size.columns && c.rows === size.rows;
- return same ? c.layout : null;
+ if (c !== null && sameKey(c.key, key)) return c.layout;
+ const layout = layoutMap(key.data.files, { columns: key.columns, rows: key.rows, caseInsensitive, style: key.style });
+ this.layoutCache = { key, layout };
+ return layout;
}
private apply(io: MapIO, action: TrailAction): void {
@@ -254,11 +250,11 @@ export class LensMap {
else io.redraw();
}
- /** The feed and the latest edit's importers, once the map is wanted and the repo known. */
+ /** The feed and the importers of every edited file not yet asked for, once the map is wanted and the repo known. */
private fetchWanted(io: MapIO): void {
if (!this.requested || this.repo === null) return;
this.loadFeed(io, this.repo);
- this.loadCallers(io, this.repo);
+ for (const path of this.edited) this.loadCallers(io, this.repo, path);
}
private loadFeed(io: MapIO, repo: MapRepo): void {
@@ -277,24 +273,34 @@ export class LensMap {
});
}
- private loadCallers(io: MapIO, repo: MapRepo): void {
- const edits = this.trail.edits;
- if (this.editPath === null || this.callersAsked === edits) return;
- this.callersAsked = edits;
- const rel = relativeTo(this.editPath, repo.root, repo.caseInsensitive);
- if (rel === null) return this.apply(io, { type: "callers", edits, callers: { status: "failed" } });
+ /** One edited file's importers, asked once; the answer is kept by path. */
+ private loadCallers(io: MapIO, repo: MapRepo, abs: string): void {
+ const rel = relativeTo(abs, repo.root, repo.caseInsensitive);
+ const key = rel === null ? null : this.keyOf(rel);
+ if (rel === null || key === null || this.importers.has(key)) return;
+ this.importers.set(key, { status: "loading" });
const request = { changed_files: [rel], max_depth: CALLERS_DEPTH };
withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers")
.then((r) => {
const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);
- if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "ready", paths } });
+ if (this.disposed) return;
+ this.landed(io, abs, { status: "ready", paths });
+ io.blastLanded?.(rel, r);
})
.catch((err: unknown) => {
io.debug(`importers failed: ${String(err)}`);
- if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "failed" } });
+ if (!this.disposed) this.landed(io, abs, { status: "failed" });
});
}
+ /** An answer for one edited file: kept by path; for the latest edit, also the trail's (which ripples). */
+ private landed(io: MapIO, abs: string, callers: Callers): void {
+ const rel = this.repo === null ? null : relativeTo(abs, this.repo.root, this.repo.caseInsensitive);
+ if (rel !== null) this.importers.set(this.keyOf(rel), callers);
+ if (abs === this.editPath) this.apply(io, { type: "callers", edits: this.trail.edits, callers });
+ else io.redraw();
+ }
+
/** The first read opens the map when the toggle is on and the pane would be placed; never forced. */
private async autoOpen(io: MapIO): Promise<void> {
if (!this.mayAutoOpen()) return;
@@ -321,21 +327,29 @@ export class LensMap {
private canAnimate(kind: Anim["kind"]): boolean {
const on = this.drawn;
if (this.reducedMotion || on === null) return false;
- return kind === "flash" || rippleRadius(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay) > 0;
+ return kind === "flash" || rippleRadius(on.layout, resolveLit(on.layout, this.lighting().lit)) > 0;
}
- /** A flash or a ripple when it would show; otherwise (reduced motion, nothing on screen) the resting frame. */
+ /**
+ * A flash or a ripple when it would show; otherwise (reduced motion, nothing
+ * on screen) the resting frame, leaving another tab's animation playing.
+ */
private animate(io: MapIO, kind: Anim["kind"]): void {
- this.animator.stop();
if (!this.canAnimate(kind)) return io.redraw();
- this.animator.play(io, kind, (step) => this.frame(step));
+ this.animator.play(io, kind, kind === "flash" ? FLASH_MS : RIPPLE_MS, (step) => this.frame(step));
}
/** The current trail on the drawn map at one step, or null once the map is off screen. */
- private frame(step: Anim): { cells: string; columns: number; rows: number } | null {
+ private frame(step: Step): Frame {
const on = this.drawn;
- if (on === null) return null;
- const cells = frameCells(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay, step);
- return { cells, columns: on.layout.columns, rows: on.layout.rows };
+ const anim = mapStep(step);
+ if (on === null || anim === undefined) return null;
+ const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit), anim);
+ return { key: MAP_KEY, cells, columns: on.layout.columns, rows: on.layout.rows };
}
}
+
+/** The animator's step when it is one of the map's own. */
+function mapStep(step: Step | undefined): Anim | undefined {
+ return step !== undefined && (step.kind === "flash" || step.kind === "ripple") ? (step as Anim) : undefined;
+}
diff --git a/packages/claude-mod/src/mod-api.ts b/packages/claude-mod/src/mod-api.ts
index 642965889..1b2331dbe 100644
--- a/packages/claude-mod/src/mod-api.ts
+++ b/packages/claude-mod/src/mod-api.ts
@@ -73,14 +73,32 @@ export interface ModApi {
register(command: { name: string; description: string; argumentHint?: string; immediate?: true }): Promise<unknown>;
};
settings: { read(): Promise<Readonly<Record<string, unknown>>> };
+ /** The `/config` menu's rows; Lens reads only `theme`. */
+ config: { list(): Promise<ReadonlyArray<{ key: string; value: unknown }>> };
}
export interface SessionStartEvent {
cwd?: string;
}
+/**
+ * The conversation ending. `clear` is a `/clear`: the process goes on under a
+ * new session id and no `session.start` fires for it.
+ */
+export interface SessionEndEvent {
+ reason?: "clear" | "resume" | "logout" | "prompt_input_exit" | "other";
+ sessionId?: string;
+}
+
+/** A prompt's turn starting; `text` is "" for one started without a typed prompt. */
+export interface TurnStartEvent {
+ text?: string;
+ turnId?: string;
+}
+
export interface TurnCompleteEvent {
agentId?: string;
+ durationMs?: number;
/** Claude's final text this turn. */
answer?: string;
reason?: "answer" | "aborted" | "refusal" | "error";
@@ -150,8 +168,9 @@ export type PluginOptions = Readonly<Record<string, string | number | boolean |
export interface On {
(event: "session.start", hook: Hook<SessionStartEvent>): unknown;
+ (event: "session.end", hook: Hook<SessionEndEvent>): unknown;
(event: "turn.complete", hook: Hook<TurnCompleteEvent>): unknown;
- (event: "turn.start", hook: Hook<unknown>): unknown;
+ (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;
diff --git a/packages/claude-mod/src/model/ask.ts b/packages/claude-mod/src/model/ask.ts
index fc1e64033..15e013747 100644
--- a/packages/claude-mod/src/model/ask.ts
+++ b/packages/claude-mod/src/model/ask.ts
@@ -5,7 +5,11 @@
import type { DecisionsArtifactData } from "@repowise-dev/types";
-export type PaneTab = "map" | "ask" | "recap";
+/** The pane's tab bar, in order; each tab's hotkey is its position. */
+export const TAB_BAR = ["flow", "map", "ask", "recap"] as const;
+export type BarTab = (typeof TAB_BAR)[number];
+/** The tab shown; every tab is on the bar. */
+export type PaneTab = BarTab;
export type AskTool = "get_why" | "get_answer";
@@ -88,19 +92,18 @@ export function mayHaveUsedModel(a: AskReply): boolean {
return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";
}
-/** What `/lens <args>` asks for: a tab to show, and a question to ask. */
-export function lensCommand(args: string): { tab: PaneTab | null; question: string | null } {
+/**
+ * What `/lens <args>` asks for: a tab to show, and a question to ask. A
+ * question opens the Ask tab, where its answer lands; `ask` alone opens the
+ * field. `tabs` is the bar as shown (Flow leaves it when its toggle is off).
+ */
+export function lensCommand(args: string, tabs: readonly BarTab[] = TAB_BAR): { tab: PaneTab | null; question: string | null } {
const [word = "", ...rest] = args.trim().split(/\s+/);
const question = rest.join(" ");
- switch (word.toLowerCase()) {
- case "map":
- case "recap":
- return { tab: word.toLowerCase() as PaneTab, question: null };
- case "ask":
- return { tab: "ask", question: question === "" ? null : question };
- default:
- return { tab: null, question: null };
- }
+ const named = word.toLowerCase();
+ if (named === "ask") return { tab: "ask", question: question === "" ? null : question };
+ const tab = tabs.find((t) => t === named);
+ return { tab: tab ?? null, question: null };
}
/** The Ask field's text after `Why` on a review: the decision that governs the edit. */
diff --git a/packages/claude-mod/src/model/flow.ts b/packages/claude-mod/src/model/flow.ts
new file mode 100644
index 000000000..662cc0c3b
--- /dev/null
+++ b/packages/claude-mod/src/model/flow.ts
@@ -0,0 +1,544 @@
+/**
+ * Flow: Claude's tool calls this session as the engine reported them, in
+ * order and timed: what each Repowise reply carried, how many bytes each
+ * result put in Claude's context, the files it read and edited after a reply
+ * named them, and what the index says each edited file reaches. Pure: every
+ * time arrives on an action (epoch ms); nothing here reads a clock. The map
+ * reads visit order and timing from `visits`.
+ */
+
+import { summarizeReply, type ReplySummary } from "./replies";
+
+/** Turns kept whole; older ones fold into `earlier`. */
+export const MAX_TURNS = 6;
+/** Activities kept per turn; older ones are counted in `dropped`. */
+export const MAX_ACTIVITIES = 60;
+const PROMPT_CHARS = 160;
+/**
+ * Paths Repowise named this session, for "found via". Ceiling: past this the
+ * newest namings are not kept; raise it if long sessions need more.
+ */
+const MAX_NAMED = 2_000;
+/** Argument values kept per activity, and their length. */
+const MAX_ARGS = 4;
+const ARG_CHARS = 160;
+/** Characters of a shell command kept, to see which tests it ran. */
+const COMMAND_CHARS = 2_000;
+/** Hit paths kept per search. */
+const MAX_HIT_PATHS = 200;
+
+/** Tool names of the Repowise MCP servers: a user-level one, the plugin's, the hosted connector. */
+const REPOWISE_TOOL = /^mcp__(?:repowise|plugin_repowise_repowise|claude_ai_repowise)__(\w+)$/i;
+/** Lens's own MCP calls fire tool events too; they are not Claude's steps. */
+const OWN_CALL_PREFIX = "toolu_plugin_";
+
+export type ActivityKind = "repowise" | "read" | "edit" | "search" | "shell" | "other";
+
+export interface Activity {
+ /** The call's tool_use_id. */
+ id: string;
+ kind: ActivityKind;
+ /** The tool's short name: `get_context`, `Read`, `Bash`. */
+ tool: string;
+ /** Set on a subagent's call. */
+ agentId: string | null;
+ startedAt: number;
+ endedAt: number | null;
+ /** Arguments as sent, compacted to a few named values. */
+ args: ReadonlyArray<readonly [string, string]>;
+ /** Files the call worked on, relative to the session's directory when inside it. */
+ paths: readonly string[];
+ /** The files a Repowise call asked about (its `targets`), relative like `paths`. */
+ asked: readonly string[];
+ /** A shell call's command, for which tests it ran. */
+ command: string | null;
+ isError: boolean;
+ /** UTF-8 bytes of the result Claude received; null until it lands. */
+ bytes: number | null;
+ reply: ReplySummary | null;
+ /** For a read or edit: the Repowise reply that named this file first this session. */
+ namedBy: Naming | null;
+ /** An edit's size from its arguments: lines added less removed, or lines written. */
+ lines: { delta: number } | { written: number } | null;
+ /** Files a search returned, and (up to a cap) which, relative like `paths`. */
+ hits: number | null;
+ hitPaths: readonly string[];
+}
+
+export interface Naming {
+ id: string;
+ /** The Repowise tool whose reply named the file. */
+ tool: string;
+ at: number;
+ turn: number;
+}
+
+export type TurnEnd = "answer" | "stopped" | "failed";
+
+export interface FlowTurn {
+ /** 1 for the session's first turn. */
+ seq: number;
+ turnId: string | null;
+ /** The prompt's first characters; "" for a turn Lens did not see start. */
+ prompt: string;
+ startedAt: number;
+ endedAt: number | null;
+ durationMs: number | null;
+ /** How the turn ended: an answer, stopped (aborted), or did not finish (refusal, error); null while open. */
+ end: TurnEnd | null;
+ activities: readonly Activity[];
+ dropped: number;
+}
+
+/** What the index says an edited file reaches (the depth-1 blast radius), repo-relative. */
+export interface BlastFacts {
+ /** Files that import it directly. */
+ importers: readonly string[];
+ /** Files that usually change with it, strongest first, with the server's 0 to 1 score. */
+ cochange: ReadonlyArray<{ path: string; score: number }>;
+ /** Tests that reach it: how many, which (as emitted), and whether measured or inferred. */
+ tests: { total: number; files: readonly string[]; basis: "measured" | "inferred" } | null;
+}
+
+export interface Totals {
+ turns: number;
+ repowise: number;
+ reads: number;
+ edits: number;
+}
+
+export interface FlowState {
+ turns: readonly FlowTurn[];
+ /** Totals of the turns folded away. */
+ earlier: Totals;
+ /** Paths Repowise named, by `pathKey`, at their first naming. */
+ named: Readonly<Record<string, Naming>>;
+ /** Blast radius facts of edited files, by `pathKey`, as the map's request returned them. */
+ blast: Readonly<Record<string, BlastFacts>>;
+ /** The Repowise call whose detail is open. */
+ open: string | null;
+}
+
+export const initialFlow: FlowState = {
+ turns: [],
+ earlier: { turns: 0, repowise: 0, reads: 0, edits: 0 },
+ named: {},
+ blast: {},
+ open: null,
+};
+
+/** A tool call as `tool.call` sees it: its arguments ride beside these keys. */
+export interface ToolCall {
+ tool: string;
+ tool_use_id: string;
+ agentId?: string | undefined;
+ [arg: string]: unknown;
+}
+
+export type FlowAction =
+ | { type: "turnStarted"; turnId: string | null; prompt: string; at: number }
+ | { type: "turnEnded"; at: number; durationMs: number | null; end: TurnEnd }
+ | { type: "toolStarted"; activity: Activity }
+ | {
+ type: "toolEnded";
+ id: string;
+ at: number;
+ isError: boolean;
+ bytes: number | null;
+ reply: ReplySummary | null;
+ hits: number | null;
+ hitPaths: readonly string[];
+ }
+ | { type: "blastLanded"; path: string; facts: BlastFacts }
+ | { type: "toggle"; id: string }
+ | { type: "step"; by: 1 | -1 };
+
+const END_OF: Record<string, TurnEnd> = { answer: "answer", aborted: "stopped", refusal: "failed", error: "failed" };
+
+/** How a `turn.complete` ended the turn, from its `reason` (and `isAborted` when no reason came). */
+export function turnEnd(reason: string | undefined, isAborted: boolean | undefined): TurnEnd {
+ return END_OF[reason ?? ""] ?? (isAborted === true ? "stopped" : "answer");
+}
+
+/** The Repowise tool a name calls (`get_context`), or null for any other tool. */
+export function repowiseTool(name: string): string | null {
+ return REPOWISE_TOOL.exec(name)?.[1] ?? null;
+}
+
+const KIND_OF: Record<string, ActivityKind> = {
+ Read: "read",
+ Edit: "edit",
+ MultiEdit: "edit",
+ Write: "edit",
+ NotebookEdit: "edit",
+ Grep: "search",
+ Glob: "search",
+ Bash: "shell",
+};
+
+/** The arguments worth a glance, in this order. */
+const ARG_KEYS = ["targets", "query", "question", "id", "file_path", "notebook_path", "pattern", "path", "command", "url", "description"];
+const PATH_ARGS = new Set(["file_path", "notebook_path", "path"]);
+
+/** `path` relative to `root` with `/` separators when inside it; else as given, slashed. */
+export function shortPath(path: string, root: string | null): string {
+ const slashed = path.replace(/\\/g, "/");
+ if (root === null) return slashed;
+ const base = root.replace(/\\/g, "/").replace(/\/+$/, "");
+ const inside = slashed.toLowerCase().startsWith(`${base.toLowerCase()}/`);
+ return inside ? slashed.slice(base.length + 1) : slashed;
+}
+
+function argValue(key: string, v: unknown, root: string | null): string | null {
+ if (typeof v === "string") return (PATH_ARGS.has(key) ? 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 === undefined || v === null) return null;
+ return JSON.stringify(v).slice(0, ARG_CHARS);
+}
+
+function compactArgs(e: ToolCall, root: string | null): Array<readonly [string, string]> {
+ const out: Array<readonly [string, string]> = [];
+ for (const key of ARG_KEYS) {
+ const value = argValue(key, e[key], root);
+ if (value !== null && out.length < MAX_ARGS) out.push([key, value]);
+ }
+ return out;
+}
+
+const lineCount = (s: unknown): number | null => (typeof s === "string" ? s.split("\n").length : null);
+
+function editLines(e: ToolCall): Activity["lines"] {
+ const written = e.tool === "Write" ? lineCount(e["content"]) : null;
+ if (written !== null) return { written };
+ const before = lineCount(e["old_string"]);
+ const after = lineCount(e["new_string"]);
+ return before !== null && after !== null ? { delta: after - before } : null;
+}
+
+/** The files a Repowise call names in its `targets` (symbol ids left out), as paths. */
+function askedFiles(e: ToolCall, root: string | null): string[] {
+ const targets = e["targets"];
+ const list: unknown[] = Array.isArray(targets) ? targets : [];
+ return list.filter((t): t is string => typeof t === "string" && !t.includes("::")).map((t) => shortPath(t, root));
+}
+
+/** A call Claude made: it has an id, and not one of Lens's own. */
+function isClaudeCall(e: ToolCall): boolean {
+ return typeof e.tool_use_id === "string" && typeof e.tool === "string" && !e.tool_use_id.startsWith(OWN_CALL_PREFIX);
+}
+
+/**
+ * The activity a tool call starts, or null for Lens's own calls. `root` is
+ * the session's directory, which paths are shown relative to.
+ */
+export function activityOf(e: ToolCall, at: number, root: string | null): Activity | null {
+ if (!isClaudeCall(e)) return null;
+ const rw = repowiseTool(e.tool);
+ const kind: ActivityKind = 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) };
+}
+
+/** An activity's fields before anything about its call is known. */
+const BLANK: Omit<Activity, "id" | "kind" | "tool" | "agentId" | "startedAt" | "args"> = {
+ endedAt: null,
+ paths: [],
+ asked: [],
+ command: null,
+ isError: false,
+ bytes: null,
+ reply: null,
+ namedBy: null,
+ lines: null,
+ hits: null,
+ hitPaths: [],
+};
+
+const agentOf = (e: ToolCall): string | null => (typeof e.agentId === "string" ? e.agentId : null);
+
+/** The file a file tool works on, relative to `root`. */
+function fileOf(e: ToolCall, root: string | null): Pick<Activity, "paths"> {
+ const file = e["file_path"] ?? e["notebook_path"];
+ return { paths: typeof file === "string" ? [shortPath(file, root)] : [] };
+}
+
+/** A shell call's command, kept to see which tests it ran. */
+function commandOf(e: ToolCall): Pick<Activity, "command"> {
+ const command = e["command"];
+ return { command: typeof command === "string" ? command.slice(0, COMMAND_CHARS) : null };
+}
+
+/** What each kind of call adds to its activity. */
+const BY_KIND: Record<ActivityKind, (e: ToolCall, root: string | null) => Partial<Activity>> = {
+ repowise: (e, root) => ({ ...fileOf(e, root), asked: askedFiles(e, root) }),
+ read: fileOf,
+ edit: (e, root) => ({ ...fileOf(e, root), lines: editLines(e) }),
+ search: fileOf,
+ shell: (e) => commandOf(e),
+ other: fileOf,
+};
+
+/**
+ * Files a search returned, from what `next(e)` resolved to: the count, and
+ * the names relative to `root` (a Grep that printed lines names none).
+ */
+export function searchHits(outcome: unknown, root: string | null): { hits: number | null; hitPaths: string[] } {
+ const result = (outcome as { result?: { filenames?: unknown; numFiles?: unknown } } | null)?.result;
+ if (typeof result !== "object" || result === null) return { hits: null, hitPaths: [] };
+ if (!Array.isArray(result.filenames)) return { hits: typeof result.numFiles === "number" ? result.numFiles : null, hitPaths: [] };
+ const names = result.filenames.filter((f): f is string => typeof f === "string");
+ return { hits: names.length, hitPaths: names.slice(0, MAX_HIT_PATHS).map((f) => shortPath(f, root)) };
+}
+
+/** The text of a call's outcome (`next(e)`'s `text`): what Claude received, or null. */
+export function outcomeText(outcome: unknown): string | null {
+ const text = (outcome as { text?: unknown } | null)?.text;
+ return typeof text === "string" ? text : null;
+}
+
+/**
+ * The end of a tool call, from what `next(e)` resolved to (null when it
+ * threw): its time, whether it failed, the bytes Claude received (counted,
+ * never kept), a Repowise reply's summary, a search's hits. Null for Lens's
+ * own calls.
+ */
+export function toolEnded(e: ToolCall, outcome: unknown, at: number, root: string | null): FlowAction | null {
+ if (!isClaudeCall(e)) return null;
+ const rw = repowiseTool(e.tool);
+ const text = outcomeText(outcome);
+ const isError = outcome === null || (outcome as { isError?: unknown } | undefined)?.isError === true;
+ const summary = rw === null || text === null ? null : summarizeReply(rw, text);
+ // Named paths compare repo-relative: an absolute one under the root is made relative here.
+ const reply = summary === null ? null : { ...summary, paths: summary.paths.map((p) => shortPath(p, root)) };
+ const bytes = summary?.bytes ?? (text === null ? null : new TextEncoder().encode(text).length);
+ return { type: "toolEnded", id: e.tool_use_id, at, isError, bytes, reply, ...searchHits(outcome, root) };
+}
+
+/** A key matching a path however it was written: `/` separators, no case. */
+export function pathKey(path: string): string {
+ // Ceiling: case is folded everywhere, so two files differing only in case share a key.
+ return path.replace(/\\/g, "/").replace(/^\.\//, "").toLowerCase();
+}
+
+/**
+ * The first naming of exactly this path. Both sides are relative to the same
+ * root (`shortPath`), so a file outside it never matches a reply's path.
+ */
+function namingOf(named: FlowState["named"], path: string): Naming | null {
+ return named[pathKey(path)] ?? null;
+}
+
+/** Folds paths a reply named into the session's namings; first naming wins. */
+function withNamed(named: FlowState["named"], paths: readonly string[], naming: Naming): FlowState["named"] {
+ let out = named;
+ let size = Object.keys(named).length;
+ for (const p of paths) {
+ const key = pathKey(p);
+ if (out[key] !== undefined || size >= MAX_NAMED) continue;
+ if (out === named) out = { ...named };
+ (out as Record<string, Naming>)[key] = naming;
+ size++;
+ }
+ return out;
+}
+
+export interface TurnTotals {
+ /** Repowise calls made, and those that came back without an error, with their time. */
+ repowise: number;
+ answered: number;
+ answeredMs: number;
+ reads: number;
+ edits: number;
+ /** Distinct files read or edited, and how many of them a Repowise reply named first. */
+ opened: number;
+ named: number;
+ /** An edit landed in a file a Repowise reply named first. */
+ editNamed: boolean;
+}
+
+export const isFile = (a: Activity): boolean => a.kind === "read" || a.kind === "edit";
+const isAnswered = (a: Activity): boolean => a.kind === "repowise" && a.endedAt !== null && !a.isError;
+
+/** Counts for a turn: Repowise calls and their time, distinct files read and edited, and how many Repowise named first. */
+export function turnTotals(turn: FlowTurn): TurnTotals {
+ const files = turn.activities.filter(isFile);
+ const keys = (list: Activity[]) => new Set(list.map((a) => pathKey(a.paths[0] ?? "")));
+ const answered = turn.activities.filter(isAnswered);
+ const edits = files.filter((a) => a.kind === "edit");
+ return {
+ repowise: turn.activities.filter((a) => a.kind === "repowise").length,
+ answered: answered.length,
+ answeredMs: answered.reduce((ms, a) => ms + (a.endedAt as number) - a.startedAt, 0),
+ reads: keys(files.filter((a) => a.kind === "read")).size,
+ edits: keys(edits).size,
+ opened: keys(files).size,
+ named: keys(files.filter((a) => a.namedBy !== null)).size,
+ editNamed: edits.some((a) => a.namedBy !== null),
+ };
+}
+
+function fold(earlier: Totals, turn: FlowTurn): Totals {
+ const t = turnTotals(turn);
+ return { turns: earlier.turns + 1, repowise: earlier.repowise + t.repowise, reads: earlier.reads + t.reads, edits: earlier.edits + t.edits };
+}
+
+function withTurn(state: FlowState, turn: FlowTurn): FlowState {
+ const turns = [...state.turns, turn];
+ if (turns.length <= MAX_TURNS) return { ...state, turns };
+ const gone = turns.shift() as FlowTurn;
+ return { ...state, turns, earlier: fold(state.earlier, gone) };
+}
+
+/**
+ * Blocks the harness puts around what the person typed: agent hand-backs,
+ * system reminders, task notifications, slash-command wrappers. A tag may
+ * arrive escaped (`<\\agent-message`); one never closed runs to the end.
+ */
+const INJECTED = /\s*<\\?((?:agent-message|system-reminder|task-notification|local-command-[\w-]+|command-[\w-]+))\b[^>]*>[\s\S]*?(?:<\/\1>|$)\s*/g;
+
+/** The person's own words in a turn's text: injected blocks removed wherever they sit; "" when nothing they typed remains. */
+export function userWords(text: string): string {
+ return text.replace(INJECTED, " ").trim();
+}
+
+function newTurn(state: FlowState, turnId: string | null, prompt: string, at: number): FlowTurn {
+ const seq = (state.turns.at(-1)?.seq ?? state.earlier.turns) + 1;
+ return { seq, turnId, prompt: userWords(prompt).slice(0, PROMPT_CHARS), startedAt: at, endedAt: null, durationMs: null, end: null, activities: [], dropped: 0 };
+}
+
+/** The open turn, or a new one when Lens did not see this turn start. */
+function openTurn(state: FlowState, at: number): FlowState {
+ const last = state.turns.at(-1);
+ return last !== undefined && last.endedAt === null ? state : withTurn(state, newTurn(state, null, "", at));
+}
+
+function mapLast(state: FlowState, f: (t: FlowTurn) => FlowTurn): FlowState {
+ const last = state.turns.at(-1);
+ const next = last === undefined ? last : f(last);
+ return next === last ? state : { ...state, turns: [...state.turns.slice(0, -1), next as FlowTurn] };
+}
+
+/** Rewrites the activity `id` wherever it is; the state as it was when no turn holds it. */
+function mapActivity(state: FlowState, id: string, f: (a: Activity) => Activity): FlowState {
+ const i = state.turns.findIndex((t) => t.activities.some((a) => a.id === id));
+ if (i < 0) return state;
+ const turn = state.turns[i] as FlowTurn;
+ const activities = turn.activities.map((a) => (a.id === id ? f(a) : a));
+ const turns = state.turns.map((t, j) => (j === i ? { ...turn, activities } : t));
+ return { ...state, turns };
+}
+
+/** The turn with one more activity, the oldest dropped (and counted) past the cap. */
+function pushActivity(t: FlowTurn, activity: Activity): FlowTurn {
+ 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 };
+}
+
+function append(state: FlowState, activity: Activity): FlowState {
+ return mapLast(openTurn(state, activity.startedAt), (t) => pushActivity(t, activity));
+}
+
+/** Ends the open turn, if any, as `end`. */
+function closeTurn(state: FlowState, at: number, durationMs: number | null, end: TurnEnd): FlowState {
+ return mapLast(state, (t) => (t.endedAt !== null ? t : { ...t, endedAt: at, durationMs: durationMs ?? at - t.startedAt, end }));
+}
+
+function started(state: FlowState, activity: Activity): FlowState {
+ const namedBy = isFile(activity) && activity.paths[0] !== undefined ? namingOf(state.named, activity.paths[0]) : null;
+ return append(state, { ...activity, namedBy });
+}
+
+function ended(state: FlowState, action: Extract<FlowAction, { type: "toolEnded" }>): FlowState {
+ const { id, at, isError, bytes, reply, hits, hitPaths } = action;
+ const next = mapActivity(state, id, (a) => ({ ...a, endedAt: at, isError, bytes, reply, hits, hitPaths }));
+ if (next === state || reply === null || isError) return next;
+ const turn = next.turns.find((t) => t.activities.some((a) => a.id === id)) as FlowTurn;
+ return { ...next, named: withNamed(next.named, reply.paths, { id, tool: reply.tool, at, turn: turn.seq }) };
+}
+
+/** The rows a press or a hotkey can open: Repowise calls, oldest first. */
+export function openable(state: FlowState): string[] {
+ return state.turns.flatMap((t) => t.activities.filter((a) => a.kind === "repowise").map((a) => a.id));
+}
+
+function stepped(state: FlowState, by: 1 | -1): FlowState {
+ const ids = openable(state);
+ if (ids.length === 0) return state;
+ const at = state.open === null ? -1 : ids.indexOf(state.open);
+ const i = at < 0 ? (by === 1 ? 0 : ids.length - 1) : Math.min(ids.length - 1, Math.max(0, at + by));
+ return ids[i] === state.open ? state : { ...state, open: ids[i] as string };
+}
+
+export function reduceFlow(state: FlowState, action: FlowAction): FlowState {
+ switch (action.type) {
+ case "turnStarted": {
+ // A prompt while the last turn is still open: that one was stopped.
+ const closed = closeTurn(state, action.at, null, "stopped");
+ return withTurn(closed, newTurn(closed, action.turnId, action.prompt, action.at));
+ }
+ case "turnEnded":
+ return closeTurn(state, action.at, action.durationMs, action.end);
+ case "toolStarted":
+ return started(state, action.activity);
+ case "toolEnded":
+ return ended(state, action);
+ case "blastLanded":
+ return { ...state, blast: { ...state.blast, [pathKey(action.path)]: action.facts } };
+ case "toggle":
+ return { ...state, open: state.open === action.id ? null : action.id };
+ case "step":
+ return stepped(state, action.by);
+ }
+}
+
+/** Every activity kept, oldest first, across turns. */
+export function activities(state: FlowState): Activity[] {
+ return state.turns.flatMap((t) => [...t.activities]);
+}
+
+/** One place Claude's attention went: a file read or edited, or a file a search returned. */
+export interface Visit {
+ path: string;
+ kind: "read" | "edit" | "search-hit";
+ /** Increasing per read, edit or search; every hit of one search shares its search's number. */
+ order: number;
+ at: number;
+ turn: number;
+}
+
+/**
+ * Claude's visits this session, in order, for the map: reads and
+ * edits each get the next number, and a search's hits all share one. Paths
+ * are as `activityOf` and `searchHits` kept them (relative to the session's
+ * root, `/` separators). Failed calls are left out.
+ */
+export function visits(state: FlowState): Visit[] {
+ const out: Visit[] = [];
+ let order = 0;
+ const steps = state.turns.flatMap((t) => t.activities.map((a) => [a, t.seq] as const));
+ for (const [a, turn] of steps) {
+ const found = visitsOf(a, turn, order + 1);
+ if (found.length > 0) order++;
+ out.push(...found);
+ }
+ return out;
+}
+
+/** One activity's visits, all numbered `order`: a read or edit's file, or a search's hits. */
+function visitsOf(a: Activity, turn: number, order: number): Visit[] {
+ if (a.isError) return [];
+ if (a.kind === "search") return a.hitPaths.map((path): Visit => ({ path, kind: "search-hit", order, at: a.endedAt ?? a.startedAt, turn }));
+ const path = a.paths[0];
+ return (a.kind === "read" || a.kind === "edit") && path !== undefined ? [{ path, kind: a.kind, order, at: a.startedAt, turn }] : [];
+}
+
+/** Whether Claude is in a turn now. */
+export function isWorking(state: FlowState): boolean {
+ const last = state.turns.at(-1);
+ return last !== undefined && last.endedAt === null;
+}
+
+/** A Repowise call still waiting on its reply. */
+export function inFlight(state: FlowState): Activity | null {
+ return state.turns.at(-1)?.activities.find((a) => a.kind === "repowise" && a.endedAt === null) ?? null;
+}
diff --git a/packages/claude-mod/src/model/replies.ts b/packages/claude-mod/src/model/replies.ts
new file mode 100644
index 000000000..2af40f43c
--- /dev/null
+++ b/packages/claude-mod/src/model/replies.ts
@@ -0,0 +1,286 @@
+/**
+ * What a Repowise reply carried, read from the MCP text Claude received.
+ * Pure. Each tool has a small reader for the evidence it returns; an unknown
+ * tool, or a shape a reader does not know, falls back to the reply's own
+ * top-level lists. Only fields the reply has are read; nothing is inferred.
+ */
+
+/** Characters of a reply parsed: larger replies are summarized by size alone. */
+export const PARSE_CHARS = 64 * 1024;
+/** Characters of a reply kept for display. */
+export const EXCERPT_CHARS = 2 * 1024;
+/** Paths kept per reply for "led to". */
+const MAX_PATHS = 200;
+/** How deep the path walk goes into a reply. */
+const MAX_DEPTH = 6;
+
+type Rec = Record<string, unknown>;
+
+/**
+ * One count the reply carried. `what` is a known evidence kind
+ * (views/copy.ts names its unit) or, from the fallback, the reply's own key.
+ */
+export interface ReplyFact {
+ what: string;
+ n: number;
+ /** The total when the reply said it showed only part. */
+ of?: number;
+}
+
+/** The reply's own account of where it came from and how complete it is. */
+export interface Behind {
+ commit: string | null;
+ ageDays: number | null;
+ /** The local server's word on whether the index is behind the checkout; null when it did not say. */
+ indexBehind: boolean | null;
+ verified: boolean | null;
+ complete: boolean | null;
+ confidence: string | null;
+ grounding: string | null;
+ retrieval: string | null;
+ /** Characters served against the response budget. */
+ budget: { used: number; limit: number } | null;
+ /** Tokens the server left out, restorable by ref. */
+ omittedTokens: number | null;
+ /** Why the reply is not the full answer (`no-llm-provider`). */
+ degraded: string | null;
+ semantic: boolean | null;
+}
+
+export interface ReplySummary {
+ tool: string;
+ /** UTF-8 bytes of the reply text; null when the text was not seen. */
+ bytes: number | null;
+ /** False when the text was not JSON or too large to parse. */
+ parsed: boolean;
+ inside: ReplyFact[];
+ behind: Behind;
+ /** Repo-relative paths the reply named, first seen first. */
+ paths: string[];
+ excerpt: string;
+ /** The error the server returned instead of a result. */
+ error: string | null;
+}
+
+const isRec = (v: unknown): v is Rec => typeof v === "object" && v !== null && !Array.isArray(v);
+const rec = (v: unknown): Rec => (isRec(v) ? v : {});
+const str = (v: unknown): string | null => (typeof v === "string" && v !== "" ? v : null);
+const num = (v: unknown): number | null => (typeof v === "number" && Number.isFinite(v) ? v : null);
+const bool = (v: unknown): boolean | null => (typeof v === "boolean" ? v : null);
+/** A count: a number as sent, or a list's length. */
+const count = (v: unknown): number | null => (Array.isArray(v) ? v.length : num(v));
+
+function fact(what: string, n: number | null, of: number | null = null): ReplyFact[] {
+ if (n === null) return [];
+ return of !== null && of > n ? [{ what, n, of }] : [{ what, n }];
+}
+
+/** A sum over targets of one count, or null when no target carried it. */
+function sumOver(targets: Rec[], read: (t: Rec) => number | null): number | null {
+ const found = targets.map(read).filter((n): n is number => n !== null);
+ return found.length === 0 ? null : found.reduce((a, b) => a + b, 0);
+}
+
+const targetsOf = (r: Rec): Rec[] => Object.values(rec(r["targets"])).filter(isRec);
+const flagged = (targets: Rec[], key: string): number | null =>
+ targets.some((t) => key in t) ? targets.filter((t) => t[key] === true).length : null;
+
+function contextFacts(r: Rec): ReplyFact[] {
+ const targets = targetsOf(r);
+ const docs = targets.map((t) => rec(t["docs"]));
+ const symbols = sumOver(docs, (d) => count(d["symbols"]));
+ const symbolTotal = sumOver(docs, (d) => num(rec(d["symbols_truncated"])["total"]) ?? count(d["symbols"]));
+ return [
+ ...fact("targets", targets.length),
+ ...fact("docs", docs.filter((d) => str(d["title"]) !== null).length || null),
+ ...fact("symbols", symbols, symbolTotal),
+ ...fact("callers", sumOver(targets, (t) => count(t["callers"]))),
+ ...fact("callees", sumOver(targets, (t) => count(t["callees"]))),
+ ...fact("decisions", sumOver(targets, (t) => count(t["decisions"]))),
+ ...fact("hotspots", flagged(targets, "hotspot") || null),
+ ];
+}
+
+function riskFacts(r: Rec): ReplyFact[] {
+ const targets = targetsOf(r);
+ return [
+ ...fact("targets", targets.length),
+ ...fact("dependents", sumOver(targets, (t) => num(t["dependents_count"]))),
+ ...fact("coChange", sumOver(targets, (t) => num(t["co_change_partners_total"]) ?? count(t["co_change_partners"]))),
+ ...fact("contributors", sumOver(targets, (t) => num(t["contributor_count"]))),
+ ...fact("hotspots", flagged(targets, "is_hotspot") || null),
+ ];
+}
+
+function answerFacts(r: Rec): ReplyFact[] {
+ return [
+ ...fact("citations", count(r["citations"])),
+ ...fact("bodies", count(r["symbol_bodies"])),
+ ...fact("rationale", count(r["code_rationale"]), num(r["code_rationale_total"])),
+ ...fact("guesses", count(r["best_guesses"])),
+ ];
+}
+
+function whyFacts(r: Rec): ReplyFact[] {
+ const git = rec(r["git_archaeology"]);
+ return [
+ ...fact("decisions", count(r["decisions"])),
+ ...fact("rationale", count(r["code_rationale"]), num(r["code_rationale_total"])),
+ ...fact("commits", count(git["git_log"] ?? git["file_commits"])),
+ ];
+}
+
+function searchFacts(r: Rec): ReplyFact[] {
+ return fact("results", count(r["results"]));
+}
+
+function symbolFacts(r: Rec): ReplyFact[] {
+ const start = num(r["start_line"]);
+ const end = num(r["end_line"]);
+ return [
+ ...fact("lines", start !== null && end !== null && end >= start ? end - start + 1 : null),
+ ...fact("callers", count(r["callers"])),
+ ...fact("callees", count(r["callees"])),
+ ];
+}
+
+/** The reply's own top-level lists, by key, for a tool without a reader. */
+function listFacts(r: Rec): ReplyFact[] {
+ return Object.entries(r)
+ .filter(([key, v]) => Array.isArray(v) && v.length > 0 && !key.startsWith("_"))
+ .slice(0, 3)
+ .map(([key, v]) => ({ what: key, n: (v as unknown[]).length }));
+}
+
+const READERS: Record<string, (r: Rec) => ReplyFact[]> = {
+ get_context: contextFacts,
+ get_risk: riskFacts,
+ get_answer: answerFacts,
+ get_why: whyFacts,
+ search_codebase: searchFacts,
+ get_symbol: symbolFacts,
+};
+
+function insideOf(tool: string, r: Rec): ReplyFact[] {
+ const known = READERS[tool]?.(r) ?? [];
+ return known.length > 0 ? known : listFacts(r);
+}
+
+function behindOf(r: Rec, meta: Rec): Behind {
+ const budget = rec(meta["response_budget"]);
+ const used = num(budget["serialized_chars"]);
+ const limit = num(budget["limit_chars"]);
+ const completeness = rec(meta["completeness"]);
+ const capped = bool(completeness["capped"]);
+ return {
+ commit: str(meta["indexed_commit"]),
+ ageDays: num(meta["index_age_days"]),
+ indexBehind: bool(meta["index_behind"]),
+ verified: bool(r["verified"]),
+ complete: bool(meta["complete"]) ?? (capped === null ? null : !capped),
+ confidence: str(r["confidence"]),
+ grounding: str(r["grounding"]),
+ retrieval: str(r["retrieval_quality"]),
+ budget: used !== null && limit !== null ? { used, limit } : null,
+ omittedTokens: num(rec(meta["omitted"])["tokens"]),
+ degraded: str(r["degraded"]) ?? str(meta["degraded"]),
+ semantic: bool(meta["semantic_search"]),
+ };
+}
+
+type Add = (p: unknown) => void;
+
+/** Where a key holds paths: a path-like value, a list of cited files, the targets answered for. */
+const PATH_READERS: Record<string, (value: unknown, add: Add) => void> = {
+ 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) : undefined),
+ targets: (v, add) => (isRec(v) ? Object.keys(v).forEach(add) : undefined),
+};
+
+function walkPaths(v: unknown, depth: number, add: Add): void {
+ if (depth > MAX_DEPTH) return;
+ if (Array.isArray(v)) return v.forEach((item) => walkPaths(item, depth + 1, add));
+ for (const [key, value] of Object.entries(rec(v))) {
+ if (key === "_meta") continue;
+ PATH_READERS[key]?.(value, add);
+ walkPaths(value, depth + 1, add);
+ }
+}
+
+/** Paths the reply named, first seen first, at most MAX_PATHS. */
+function pathsOf(r: Rec): string[] {
+ const found = new Set<string>();
+ walkPaths(r, 0, (p) => {
+ if (typeof p === "string" && p !== "" && found.size < MAX_PATHS) found.add(p.replace(/\\/g, "/"));
+ });
+ return [...found];
+}
+
+const EMPTY_BEHIND: Behind = behindOf({}, {});
+
+function utf8Bytes(text: string): number {
+ return new TextEncoder().encode(text).length;
+}
+
+/** The first line of an error, as the server wrote it. */
+function errorOf(body: Rec): string | null {
+ const err = body["error"];
+ if (typeof err === "string") return err.split("\n")[0] ?? err;
+ return str(rec(err)["message"]);
+}
+
+/** A reply already parsed, with its size when known. */
+function summarizeBody(tool: string, body: unknown, bytes: number | null, excerpt = ""): ReplySummary {
+ const r = rec(body);
+ const meta = rec(r["_meta"]);
+ return {
+ tool,
+ bytes,
+ parsed: true,
+ inside: insideOf(tool, r),
+ behind: behindOf(r, meta),
+ paths: pathsOf(r),
+ excerpt,
+ error: errorOf(r),
+ };
+}
+
+/**
+ * A reply as Claude received it: the MCP text (`{"result": {...}}`, its
+ * `_meta` inside the result or beside it). Text that is not JSON, or too
+ * large to parse here, keeps its size and excerpt only.
+ */
+export function summarizeReply(tool: string, text: string): ReplySummary {
+ const bytes = utf8Bytes(text);
+ const excerpt = text.slice(0, EXCERPT_CHARS);
+ const parsed = text.length <= PARSE_CHARS ? parseObject(text) : null;
+ if (parsed === null) return unparsed(tool, text, bytes, excerpt);
+ const summary = summarizeBody(tool, resultOf(parsed), bytes, excerpt);
+ return summary.error === null ? { ...summary, error: errorOf(parsed) } : summary;
+}
+
+/** The text as a JSON object, or null when it is not one. */
+function parseObject(text: string): Rec | null {
+ try {
+ const v: unknown = JSON.parse(text);
+ return isRec(v) ? v : null;
+ } catch {
+ // Not JSON: an error message, or a reply cut short. The caller keeps its first line.
+ return null;
+ }
+}
+
+/** The result object, with a `_meta` that came beside it moved inside. */
+function resultOf(parsed: Rec): Rec {
+ const result = isRec(parsed["result"]) ? parsed["result"] : parsed;
+ return isRec(parsed["_meta"]) && !isRec(result["_meta"]) ? { ...result, _meta: parsed["_meta"] } : result;
+}
+
+/** A reply read by size alone; its first line is the error when short enough to be one. */
+function unparsed(tool: string, text: string, bytes: number, excerpt: string): ReplySummary {
+ const first = text.trim().split("\n")[0] ?? "";
+ const error = text.length <= PARSE_CHARS && first !== "" ? first : null;
+ return { tool, bytes, parsed: false, inside: [], behind: EMPTY_BEHIND, paths: [], excerpt, error };
+}
diff --git a/packages/claude-mod/src/model/session.ts b/packages/claude-mod/src/model/session.ts
index f4310eecf..97c3d6fb9 100644
--- a/packages/claude-mod/src/model/session.ts
+++ b/packages/claude-mod/src/model/session.ts
@@ -25,6 +25,10 @@ export interface FileContext {
/** Files that import this one or call into it (the server's file-level rollup). */
callerFiles: number | null;
contributors: number | null;
+ /** The index marks the file a hotspot; null when it did not say. */
+ hotspot: boolean | null;
+ /** Who changed it most lately, and their share of its recent commits (0 to 1). */
+ recentOwner: { name: string; share: number } | null;
}
/** A Read, Edit or Write running on a file inside the indexed repo. */
@@ -121,7 +125,7 @@ export const initialSession: SessionState = {
review: initialReview,
lastReview: null,
touched: [],
- pane: { tab: "map", draft: "" },
+ pane: { tab: "flow", draft: "" },
ask: { phase: "idle" },
modelAsks: 0,
compacted: false,
@@ -133,6 +137,16 @@ export function hintFor(mode: Mode, liteReason: LiteReason | undefined): HintKin
return mode;
}
+/**
+ * After a `/clear`: what the index said stays (mode, freshness, hints, the repo,
+ * file cards) and so does the pane's tab; everything the old conversation did
+ * goes (its tools, notes, savings, review, touched files, Ask, compaction).
+ */
+export function clearedConversation(state: SessionState): SessionState {
+ const { mode, freshness, hint, hintsShown, repoRoot, contexts } = state;
+ return { ...initialSession, mode, freshness, hint, hintsShown, repoRoot, contexts, pane: { tab: state.pane.tab, draft: "" } };
+}
+
export function reduce(state: SessionState, action: SessionAction): SessionState {
switch (action.type) {
case "discovered": {
diff --git a/packages/claude-mod/src/model/story.ts b/packages/claude-mod/src/model/story.ts
new file mode 100644
index 000000000..ef9993093
--- /dev/null
+++ b/packages/claude-mod/src/model/story.ts
@@ -0,0 +1,129 @@
+/**
+ * The current turn for the map: which files it lit, and its story (what
+ * Claude searched, opened and edited, and what the edit reaches). Read from
+ * Flow's record, or, with Flow off, from the map's own trail of the session.
+ * Paths come out repo-relative with `/`. Pure.
+ */
+
+import { NO_LIT, type Lit } from "../views/overlay";
+import { relativeTo } from "./events";
+import { visits, type Activity, type FlowState, type FlowTurn } from "./flow";
+import type { Callers, TrailState } from "./trail";
+
+export interface Story {
+ searched: { pattern: string; hits: number | null }[];
+ opened: { name: string; namedBy: string | null }[];
+ edited: { name: string; lines: Activity["lines"] }[];
+}
+
+/** What the latest edit reaches: its importers as the graph has them so far. */
+export interface Reach {
+ edit: string;
+ callers: Callers;
+ /** Lowercased paths Claude opened this turn, to mark importers it already read. */
+ opened: ReadonlySet<string>;
+}
+
+export const NO_STORY: Story = { searched: [], opened: [], edited: [] };
+
+const nameOf = (path: string): string => path.slice(path.lastIndexOf("/") + 1);
+const FILE_KINDS: ReadonlySet<string> = new Set(["read", "edit", "search"]);
+const isFileStep = (a: Activity): boolean => !a.isError && FILE_KINDS.has(a.kind);
+const isOpen = (a: Activity): boolean => a.kind === "read" || a.kind === "edit";
+
+/** The latest turn in which Claude read, edited or searched: the one in progress once it touches a file, else the last that did. */
+export function storyTurn(state: FlowState): FlowTurn | null {
+ for (let i = state.turns.length - 1; i >= 0; i--) {
+ const t = state.turns[i] as FlowTurn;
+ if (t.activities.some(isFileStep)) return t;
+ }
+ return null;
+}
+
+function argOf(a: Activity, keys: readonly string[]): string {
+ return a.args.find(([k]) => keys.includes(k))?.[1] ?? "";
+}
+
+/** One opened file once, in order; a file read then edited counts as opened once. */
+function openedOf(steps: readonly Activity[]): Story["opened"] {
+ const seen = new Map<string, Story["opened"][number]>();
+ for (const a of steps) {
+ const path = a.paths[0];
+ if (!isOpen(a) || path === undefined || seen.has(path)) continue;
+ seen.set(path, { name: nameOf(path), namedBy: a.namedBy?.tool ?? null });
+ }
+ return [...seen.values()];
+}
+
+/** The story of a turn in Flow's record. */
+export function storyFromFlow(state: FlowState): Story {
+ const turn = storyTurn(state);
+ if (turn === null) return NO_STORY;
+ const steps = turn.activities.filter(isFileStep);
+ return {
+ searched: steps.filter((a) => a.kind === "search").map((a) => ({ pattern: argOf(a, ["pattern", "query"]), hits: a.hits })),
+ opened: openedOf(steps),
+ edited: steps.filter((a) => a.kind === "edit" && a.paths[0] !== undefined).map((a) => ({ name: nameOf(a.paths[0] as string), lines: a.lines })),
+ };
+}
+
+/** What a turn in Flow's record lit: its visits, and the files a Repowise reply named during it. */
+export function litFromFlow(state: FlowState): Lit {
+ const turn = storyTurn(state);
+ if (turn === null) return NO_LIT;
+ const mine = visits(state).filter((v) => v.turn === turn.seq);
+ const opened = mine.filter((v) => v.kind !== "search-hit");
+ const edits = opened.filter((v) => v.kind === "edit");
+ return {
+ hits: mine.filter((v) => v.kind === "search-hit").map((v) => v.path),
+ reads: [...new Set(opened.map((v) => v.path))],
+ named: Object.entries(state.named)
+ .filter(([, n]) => n.turn === turn.seq)
+ .map(([key]) => key),
+ importers: [],
+ edits: [...new Set(edits.map((v) => v.path))],
+ edit: edits.at(-1)?.path ?? null,
+ current: opened.at(-1)?.path ?? null,
+ };
+}
+
+const rel = (abs: string, root: string, ci: boolean): string | null => relativeTo(abs, root, ci);
+
+/** With Flow off: the map's own trail of the session, as what it lit. */
+export function litFromTrail(trail: TrailState, root: string, caseInsensitive: boolean): Lit {
+ const all = (paths: readonly string[]) => paths.map((p) => rel(p, root, caseInsensitive)).filter((p): p is string => 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 };
+}
+
+/** With Flow off: the trail's story, without patterns or line counts (only Flow records those). */
+export function storyFromTrail(trail: TrailState): Story {
+ return {
+ searched: trail.searches === 0 ? [] : [{ pattern: "", hits: trail.hits.length }],
+ opened: trail.reads.map((p) => ({ name: nameOf(p), namedBy: null })),
+ edited: trail.edit === null ? [] : [{ name: nameOf(trail.edit), lines: null }],
+ };
+}
+
+/** The importers of several edits as one answer: their union once any is in, else loading, else failed. */
+export function combineCallers(answers: readonly Callers[], edited: ReadonlySet<string>): Callers | null {
+ const ready = answers.filter((c): c is Extract<Callers, { status: "ready" }> => 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;
+}
+
+/**
+ * The lit files with the importers of every file the turn edited added, and
+ * what they reach. `importersOf` answers for a repo-relative path, or null when
+ * nothing was asked for it.
+ */
+export function withImporters(lit: Lit, importersOf: (path: string) => Callers | null): { lit: Lit; reach: Reach | null } {
+ if (lit.edit === null) return { lit, reach: null };
+ const answers = lit.edits.map(importersOf).filter((c): c is Callers => c !== null);
+ const callers = combineCallers(answers, new Set(lit.edits.map((p) => p.toLowerCase())));
+ if (callers === null) return { lit, reach: null };
+ 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())) } };
+}
diff --git a/packages/claude-mod/src/model/turnFacts.ts b/packages/claude-mod/src/model/turnFacts.ts
new file mode 100644
index 000000000..c755dae96
--- /dev/null
+++ b/packages/claude-mod/src/model/turnFacts.ts
@@ -0,0 +1,215 @@
+/**
+ * The figures Flow's turn dashboard draws, derived from the activity record
+ * and what the index returned. Pure. Each answers one question the chat
+ * cannot: what an edit reaches that Claude did not look at, which files it
+ * worked from and how it found them, what filled its context, and which
+ * Repowise answers came from the index before an edit.
+ */
+
+import { isFile, pathKey, type Activity, type BlastFacts, type FlowState, type FlowTurn } from "./flow";
+
+/** Co-change partners shown per edited file. */
+const COCHANGE_SHOWN = 2;
+/** Names too generic to say which tests a command ran (`runtests.py`, a `tests/` folder). */
+const GENERIC = new Set(["test", "tests", "spec", "specs", "__init__"]);
+/** Shell commands that run tests. */
+const TEST_RUNNER = /\b(?:pytest|py\.test|manage\.py test|runtests|npm (?:run )?test|vitest|jest|go test|cargo test)\b/;
+
+/** The blast radius response fields Flow reads; the server's own names. */
+export interface BlastResponse {
+ transitive_affected?: ReadonlyArray<{ path: string; depth?: number }>;
+ cochange_warnings?: ReadonlyArray<{ changed: string; missing_partner: string; score: number }>;
+ test_impact?: {
+ files?: ReadonlyArray<{
+ source_file: string;
+ measured_tests?: readonly string[];
+ measured_tests_total?: number;
+ inferred_tests?: readonly string[];
+ inferred_tests_total?: number;
+ }>;
+ };
+}
+
+type TestFile = NonNullable<NonNullable<BlastResponse["test_impact"]>["files"]>[number];
+
+function testsOf(file: TestFile | undefined): BlastFacts["tests"] {
+ if (file === undefined) return null;
+ const measured = file.measured_tests_total ?? 0;
+ if (measured > 0) return { total: measured, files: file.measured_tests ?? [], basis: "measured" };
+ const inferred = file.inferred_tests_total ?? 0;
+ return inferred > 0 ? { total: inferred, files: file.inferred_tests ?? [], basis: "inferred" } : null;
+}
+
+/** What one edited file reaches, from the depth-1 blast radius the map asked for. */
+export function blastFacts(path: string, r: BlastResponse): BlastFacts {
+ const key = pathKey(path);
+ const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key);
+ const cochange = (r.cochange_warnings ?? [])
+ .filter((w) => pathKey(w.changed) === key)
+ .map((w) => ({ path: w.missing_partner, score: w.score }))
+ .sort((a, b) => b.score - a.score);
+ const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key));
+ return { importers, cochange, tests };
+}
+
+const allActivities = (state: FlowState): Activity[] => state.turns.flatMap((t) => t.activities);
+
+/** Files Claude read or edited this session, as keys. */
+export function openedKeys(state: FlowState): Set<string> {
+ return new Set(allActivities(state).filter(isFile).map((a) => pathKey(a.paths[0] ?? "")));
+}
+
+/** The shell commands this session that ran tests. */
+function testCommands(state: FlowState): string[] {
+ return allActivities(state)
+ .map((a) => a.command)
+ .filter((c): c is string => c !== null && TEST_RUNNER.test(c));
+}
+
+const asWord = (command: string, word: string): boolean =>
+ !GENERIC.has(word) && new RegExp(`(^|[^\\w])${word.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}($|[^\\w])`).test(command);
+
+/**
+ * Whether a test-running command names this test file: its path, its file
+ * name without the extension, or its folder (`runtests.py queries` runs
+ * `tests/queries/`), each as a whole word and never a generic one.
+ */
+function names(command: string, test: string): boolean {
+ const slashed = test.replace(/\\/g, "/");
+ const parts = slashed.split("/");
+ const stem = (parts.at(-1) ?? "").replace(/\.[^.]+$/, "");
+ const folder = parts.at(-2) ?? "";
+ const cmd = command.replace(/\\/g, "/");
+ return cmd.includes(slashed) || asWord(cmd, stem) || asWord(cmd, folder);
+}
+
+/** How many of these test files a test-running command this session named. */
+export function testsRun(state: FlowState, tests: readonly string[]): number {
+ const commands = testCommands(state);
+ return tests.filter((t) => commands.some((c) => names(c, t))).length;
+}
+
+/** What one edited file reaches that Claude did not look at; only the exceptions. */
+export interface Gaps {
+ path: string;
+ /** Direct importers, and how many Claude opened; null when it opened them all, or there are none. */
+ importers: { total: number; opened: number } | null;
+ /** The strongest co-change partners Claude did not open, with the server's score. */
+ cochange: ReadonlyArray<{ path: string; score: number }>;
+ /** Tests that reach the file, and how many a command this session ran; null when all ran, or none reach it. */
+ tests: { total: number; run: number; basis: "measured" | "inferred" } | null;
+}
+
+function gapsOf(state: FlowState, path: string, facts: BlastFacts, opened: Set<string>): Gaps {
+ const seen = facts.importers.filter((p) => opened.has(pathKey(p))).length;
+ const t = facts.tests;
+ const run = t === null ? 0 : testsRun(state, t.files);
+ return {
+ path,
+ importers: facts.importers.length > seen ? { total: facts.importers.length, opened: seen } : null,
+ cochange: facts.cochange.filter((c) => !opened.has(pathKey(c.path))).slice(0, COCHANGE_SHOWN),
+ tests: t !== null && run < t.total ? { total: t.total, run, basis: t.basis } : null,
+ };
+}
+
+const hasGap = (g: Gaps): boolean => g.importers !== null || g.cochange.length > 0 || g.tests !== null;
+
+/** The files this turn edited, each once, in the order first edited. */
+export function editedFiles(turn: FlowTurn): string[] {
+ const out = new Map<string, string>();
+ for (const a of turn.activities) {
+ const path = a.kind === "edit" && !a.isError ? a.paths[0] : undefined;
+ if (path !== undefined && !out.has(pathKey(path))) out.set(pathKey(path), path);
+ }
+ return [...out.values()];
+}
+
+/** For each file this turn edited whose blast radius landed: what it reaches that Claude did not look at. Quiet when nothing. */
+export function beforeAccept(state: FlowState, turn: FlowTurn): Gaps[] {
+ const opened = openedKeys(state);
+ return editedFiles(turn)
+ .map((path) => [path, state.blast[pathKey(path)]] as const)
+ .filter((pair): pair is readonly [string, BlastFacts] => pair[1] !== undefined)
+ .map(([path, facts]) => gapsOf(state, path, facts, opened))
+ .filter(hasGap);
+}
+
+/** How Claude came to a file: the Repowise tool that named it first, a search that returned it, or directly. */
+export type Via = { kind: "repowise"; tool: string } | { kind: "search" } | { kind: "direct" };
+
+export interface WorkingFile {
+ path: string;
+ kind: "edited" | "read";
+ via: Via;
+}
+
+/** Whether a search before `at` this session returned the file. */
+function searchedBefore(state: FlowState, key: string, at: number): boolean {
+ return allActivities(state).some((a) => a.kind === "search" && a.startedAt < at && a.hitPaths.some((p) => pathKey(p) === key));
+}
+
+function viaOf(state: FlowState, first: Activity): Via {
+ if (first.namedBy !== null) return { kind: "repowise", tool: first.namedBy.tool };
+ return searchedBefore(state, pathKey(first.paths[0] ?? ""), first.startedAt) ? { kind: "search" } : { kind: "direct" };
+}
+
+/** The files this turn worked on: edited first, then read, each once, with how Claude came to it. */
+export function workingSet(state: FlowState, turn: FlowTurn): WorkingFile[] {
+ const first = new Map<string, Activity>();
+ const edited = new Set<string>();
+ for (const a of turn.activities.filter((x) => isFile(x) && !x.isError && x.paths[0] !== undefined)) {
+ const key = pathKey(a.paths[0] as string);
+ if (!first.has(key)) first.set(key, a);
+ if (a.kind === "edit") edited.add(key);
+ }
+ const rows = [...first].map(([key, a]): WorkingFile => ({ path: a.paths[0] as string, kind: edited.has(key) ? "edited" : "read", via: viaOf(state, a) }));
+ return [...rows.filter((r) => r.kind === "edited"), ...rows.filter((r) => r.kind === "read")];
+}
+
+export type ContextKind = "repowise" | "read" | "search" | "shell" | "other";
+export const CONTEXT_KINDS: readonly ContextKind[] = ["repowise", "read", "search", "shell", "other"];
+
+const CONTEXT_OF: Record<Activity["kind"], ContextKind | null> = {
+ repowise: "repowise",
+ read: "read",
+ search: "search",
+ shell: "shell",
+ edit: "other",
+ other: "other",
+};
+
+/** Bytes of tool results Claude received this turn, by kind (measured from each result's text). */
+export function contextBytes(turn: FlowTurn): Record<ContextKind, number> {
+ const out: Record<ContextKind, number> = { repowise: 0, read: 0, search: 0, shell: 0, other: 0 };
+ for (const a of turn.activities) {
+ const kind = CONTEXT_OF[a.kind];
+ if (kind !== null && a.bytes !== null) out[kind] += a.bytes;
+ }
+ return out;
+}
+
+/** How long after the turn started its first edit began; null without one. */
+export function firstEditMs(turn: FlowTurn): number | null {
+ const edit = turn.activities.find((a) => a.kind === "edit");
+ return edit === undefined ? null : edit.startedAt - turn.startedAt;
+}
+
+/** When Claude first edited each file this session, by key. */
+function firstEdits(state: FlowState): Map<string, number> {
+ const out = new Map<string, number>();
+ for (const a of allActivities(state)) {
+ const key = a.kind === "edit" && a.paths[0] !== undefined ? pathKey(a.paths[0]) : null;
+ if (key !== null && !out.has(key)) out.set(key, a.startedAt);
+ }
+ return out;
+}
+
+/**
+ * The Repowise calls that asked about a file Claude had already edited this
+ * session: the index describes the file as it was before that edit.
+ */
+export function answeredBeforeEdit(state: FlowState): Set<string> {
+ const edits = firstEdits(state);
+ const before = (a: Activity) => a.asked.some((p) => (edits.get(pathKey(p)) ?? Number.POSITIVE_INFINITY) < a.startedAt);
+ return new Set(allActivities(state).filter((a) => a.kind === "repowise" && before(a)).map((a) => a.id));
+}
diff --git a/packages/claude-mod/src/register.ts b/packages/claude-mod/src/register.ts
index be898c8a1..e9fb6cc50 100644
--- a/packages/claude-mod/src/register.ts
+++ b/packages/claude-mod/src/register.ts
@@ -10,6 +10,12 @@ import { callTool, fetchFileContext, isOwnLensCall, mcpReady, resetMcp, warmMcp
import { withTimeout } from "./data/transport";
import { fit } from "./format";
import type { Host } from "./host";
+import { Animator } from "./animator";
+import { LensFlow, type FlowPane } from "./flow-controller";
+import { themeOf, type ThemeName } from "./views/theme";
+import { litFromFlow, litFromTrail, storyFromFlow, storyFromTrail, type Story } from "./model/story";
+import { NO_LIT, type Lit } from "./views/overlay";
+import { HEALTH_KEY } from "./views/mapPane";
import { LensMap, type MapIO, type MapRepo } from "./map-controller";
import type {
CheckNext,
@@ -21,6 +27,7 @@ import type {
PostCompactEvent,
PostToolUseEvent,
RenderEvent,
+ SessionEndEvent,
SessionStartEvent,
SpinnerEvent,
ToolCallEvent,
@@ -28,8 +35,11 @@ import type {
ToolResultEvent,
ToolUseEvent,
TurnCompleteEvent,
+ TurnStartEvent,
UiInputEvent,
} from "./mod-api";
+import { activityOf, toolEnded, turnEnd, type FlowAction } from "./model/flow";
+import { blastFacts, type BlastResponse } from "./model/turnFacts";
import {
EDIT_TOOLS,
OBSERVED_TOOLS,
@@ -42,16 +52,16 @@ import {
savingsTotals,
touchedPath,
} from "./model/events";
-import { askReply, askRoute, lensCommand, whyDraft, type PaneTab } from "./model/ask";
-import { hintFor, initialSession, reduce, type SavingsDelta, type SessionAction, type SessionState } from "./model/session";
+import { askReply, askRoute, lensCommand, whyDraft, type BarTab, type PaneTab } from "./model/ask";
+import { clearedConversation, hintFor, initialSession, reduce, type SavingsDelta, type SessionAction, type SessionState } from "./model/session";
import { bandView } from "./views/band";
import { materialize, type ElementTable, type Node } from "./views/elements";
import { marginView } from "./views/margin";
import { isFileEdit, isRetryable, shouldReview, type ChangeRisk } from "./model/review";
import { BRIEF_PRESS, briefText } from "./views/brief";
import { HINTS, MAP_COPY, PANE_COPY, REVIEW_TIMEOUT_S } from "./views/copy";
-import { MAP_KEY } from "./views/mapPane";
-import { ASK_KEY, TABS, TAB_PRESS, TAB_ROWS, askView, paneView, recapView } from "./views/pane";
+import { FLOW_NEXT, flowPresses } from "./views/flow";
+import { ASK_KEY, TAB_ROWS, askView, paneView, recapView, tabBar, tabPress } from "./views/pane";
import { PRESS, directiveRows, reviewText, runTestsText, withCard } from "./views/review";
import { spinnerSuffix } from "./views/spinner";
import { bashText, parseSqueeze, type Squeeze } from "./model/squeeze";
@@ -69,6 +79,17 @@ const PANE_ROWS = 29;
/** get_why took 22 s cold on Django, get_answer about 4 s. */
const ASK_TIMEOUT_MS = 30_000;
+/** The `lens_flow` toggle, fixed for one activation. */
+let flowOn = true;
+let flow = new LensFlow();
+/** The person's `prefersReducedMotion`, read at session start, for a Flow made again after a `/clear`. */
+let reducedMotion = false;
+
+/** A new session's state: on the Flow tab, or the Map when Flow is off. */
+function freshSession(): SessionState {
+ return flowOn ? initialSession : reduce(initialSession, { type: "tab", tab: "map" });
+}
+
let state: SessionState = initialSession;
/** Bumped per session, so a refresh started in an earlier one never lands in this one. */
let generation = 0;
@@ -107,11 +128,15 @@ interface StartedReview {
let started: StartedReview | null = null;
/** The `lens_pane_autoopen` toggle, fixed for one activation. */
let autoOpenOn = false;
+/** The `lens_map_health` default: health colours on the map's tiles when it opens. */
+let healthOn = false;
/** The last discovery, for the map pane's notice and its repo. */
let discovery: Discovery | null = null;
/** The session's cwd, from its start event, so observing a tool call waits on nothing. */
let cwd: string | null = null;
let map = new LensMap(false);
+/** The pane's one animator, driven by the tab shown (today the map). */
+let animator = new Animator();
/** Cut so an error stays one line under the answer. */
const ERROR_CELLS = 160;
@@ -152,20 +177,28 @@ function bind($: ModApi): Bound {
call: (server, tool, args) => $.mcp.call(server, tool, args),
},
};
- return {
+ const bound: Bound = {
host,
+ blastLanded: (path, r) => flowBlast(bound, path, r),
redraw: () => $.ui.invalidate("ui.render"),
debug: (message) => $.ui.log(`lens: ${message}`, { to: "debug" }),
- blit: (cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: MAP_KEY, cells, columns, rows }),
+ blit: (key, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key, cells, columns, rows }),
// Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.
- openPane: (focus) =>
+ // 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: (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 },
- ),
+ )
+ ),
closePane: () => $.ui.close({ id: PANE_ID }),
};
+ // Each hook's closures for the animator's next frame: never a `$` kept from an earlier hook.
+ animator.use(bound);
+ return bound;
}
function mapRepo(d: Discovery): MapRepo | null {
@@ -252,8 +285,12 @@ async function onSessionStart(
generation++;
cwd = typeof e.cwd === "string" ? e.cwd : null;
map.dispose();
- map = new LensMap(autoOpenOn);
- state = initialSession;
+ animator.end();
+ animator = new Animator();
+ map = new LensMap(autoOpenOn, animator, healthOn, mapTurn);
+ flow.dispose();
+ flow = new LensFlow();
+ state = freshSession();
reviewGeneration++;
editsThisTurn = 0;
started = null;
@@ -265,7 +302,10 @@ async function onSessionStart(
warmMcp(b.host);
refresh(b);
await $.command.register({ name: "lens", description: PANE_COPY.command, argumentHint: PANE_COPY.argumentHint, immediate: true });
- map.setReducedMotion((await $.settings.read())["prefersReducedMotion"] === true);
+ readTheme($);
+ reducedMotion = (await $.settings.read())["prefersReducedMotion"] === true;
+ map.setReducedMotion(reducedMotion);
+ flow.setReducedMotion(reducedMotion);
} catch (err) {
// Lens stays quiet; the session is unaffected.
b.debug(`session.start failed: ${String(err)}`);
@@ -289,6 +329,7 @@ function noteTurnEnd(b: Bound, e: TurnCompleteEvent): void {
try {
const action = fromTurnComplete(e);
if (action === null) return;
+ noteFlow(b, () => ({ type: "turnEnded", at: Date.now(), durationMs: e.durationMs ?? null, end: turnEnd(e.reason, e.isAborted) }));
map.turnEnded();
dispatch(b, action);
refresh(b);
@@ -374,7 +415,8 @@ async function finishReview(b: Bound): Promise<string | null> {
return reviewText(state.review.outcome);
}
-async function onTurnStart($: ModApi, e: unknown, next: (e: unknown) => Promise<unknown>): Promise<unknown> {
+async function onTurnStart($: ModApi, e: TurnStartEvent, next: (e: TurnStartEvent) => Promise<unknown>): Promise<unknown> {
+ noteFlow(bind($), () => ({ type: "turnStarted", turnId: e.turnId ?? null, prompt: e.text ?? "", at: Date.now() }));
try {
// With reviews off the review state is never touched; a new turn only retires the brief offer.
if (reviewOn) {
@@ -428,6 +470,37 @@ function pressBrief($: ModApi): void {
}
}
+/**
+ * A `/clear` starts a new conversation in the same process, with no
+ * `session.start`: Flow, the map's lighting, the review, Ask and the savings
+ * baseline start over. What the index said (discovery, the health map, file
+ * cards, importers by path) and the MCP connection stay. Savings restart
+ * because the engine's own session clock (`usage().startedAt`) does too.
+ * Any other end (exit, resume, logout) leaves everything to the next activation.
+ */
+async function onSessionEnd($: ModApi, e: SessionEndEvent, next: (e: SessionEndEvent) => Promise<unknown>): Promise<unknown> {
+ if (e.reason !== "clear") return next(e);
+ const b = bind($);
+ try {
+ animator.end();
+ flow.dispose();
+ flow = new LensFlow();
+ flow.setReducedMotion(reducedMotion);
+ map.clearConversation(b);
+ state = clearedConversation(state);
+ reviewGeneration++;
+ editsThisTurn = 0;
+ started = null;
+ squeezes.clear();
+ savingsBase = null;
+ savingsAskedAt = Number.NEGATIVE_INFINITY;
+ b.redraw();
+ } catch (err) {
+ b.debug(`clear failed: ${String(err)}`);
+ }
+ return next(e);
+}
+
// Only offers the brief: the compaction and its summary pass on untouched.
async function onPostCompact(
$: ModApi,
@@ -457,12 +530,15 @@ function startAsk(b: Bound, question: string): void {
const gen = generation;
callTool<unknown>(b.host, tool, args, { timeoutMs: ASK_TIMEOUT_MS })
.then((reply) => {
- if (gen === generation) dispatch(b, { type: "answered", question: q, answer: askReply(tool, reply) });
+ if (gen !== generation) return;
+ const answer = askReply(tool, reply);
+ dispatch(b, { type: "answered", question: q, answer });
})
.catch((err: unknown) => {
b.debug(`ask failed: ${String(err)}`);
const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);
- if (gen === generation) dispatch(b, { type: "askFailed", question: q, tool, message });
+ if (gen !== generation) return;
+ dispatch(b, { type: "askFailed", question: q, tool, message });
});
}
@@ -537,17 +613,60 @@ function fetchContext(b: Bound, file: string): void {
async function onToolCall($: ModApi, e: ToolCallEvent, next: (e: ToolCallEvent) => Promise<unknown>): Promise<unknown> {
const b = bind($);
const file = fileToolStarted(b, e);
- let result: unknown;
+ noteFlow(b, () => {
+ const activity = activityOf(e, Date.now(), flowRoot());
+ return activity === null ? null : { type: "toolStarted", activity };
+ });
+ let result: unknown = null;
try {
result = await next(e);
} finally {
if (file !== null) dispatch(b, { type: "toolEnded", id: e.tool_use_id });
+ // `result` stays null when the call threw: Flow marks it failed.
+ noteFlow(b, () => toolEnded(e, result, Date.now(), flowRoot()));
}
editLanded(b, e, result);
observeTrail($, b, e, result);
return result;
}
+/** What the Flow tab draws from beyond its own record: the file cards and this turn's review. */
+function flowPane(columns: number, rows: number): FlowPane {
+ const outcome = state.review.outcome;
+ return { columns, rows, mode: state.mode, contexts: state.contexts, review: outcome.phase === "done" ? outcome.risk : null, light: theme === "light" };
+}
+
+/** The map's blast radius for an edited file, handed to Flow: never a second request. */
+function flowBlast(b: Bound, path: string, r: BlastResponse): void {
+ noteFlow(b, () => ({ type: "blastLanded", path, facts: blastFacts(path, r) }));
+}
+
+/** What Flow shows paths relative to: the indexed repo, else the session's directory. */
+function flowRoot(): string | null {
+ return state.repoRoot ?? cwd;
+}
+
+/** Records into Flow; a failure is logged and never reaches Claude's turn. */
+function noteFlow(b: Bound, action: () => FlowAction | null): void {
+ if (!flowOn) return;
+ try {
+ const a = action();
+ if (a !== null) flow.dispatch(b, a);
+ } catch (err) {
+ flowFailed(b, err);
+ }
+}
+
+/** Logs a recording failure; if even the log fails, Flow stops recording for this activation. */
+function flowFailed(b: Bound, err: unknown): void {
+ try {
+ b.debug(`flow failed: ${String(err)}`);
+ } catch {
+ // Not even the debug log works: stop recording rather than risk Claude's turn.
+ flowOn = false;
+ }
+}
+
/** Where Claude looked, for the map: recorded from what next(e) returned, waiting on nothing. */
function observeTrail($: ModApi, b: Bound, e: ToolCallEvent, result: unknown): void {
if (!OBSERVED_TOOLS.has(e.tool)) return;
@@ -685,12 +804,13 @@ async function onToolUse($: ModApi, e: ToolUseEvent, next: (e: ToolUseEvent) =>
}
}
-// `/lens`, `/lens map`, `/lens recap`, `/lens ask <question>`: the pane, with
+// `/lens`, `/lens flow`, `/lens map`, `/lens ask [question]`, `/lens recap`: the pane, with
// focus, on the tab asked for (else the last one shown).
async function onLensCommand($: ModApi, e: CommandRunEvent): Promise<unknown> {
const b = bind($);
try {
- const asked = lensCommand(e.args ?? "");
+ readTheme($);
+ const asked = lensCommand(e.args ?? "", tabBar(flowOn));
if (asked.tab !== null) dispatch(b, { type: "tab", tab: asked.tab });
if (discovery === null || mapRepo(discovery) === null) refresh(b);
await map.request(b);
@@ -707,6 +827,19 @@ async function onLensCommand($: ModApi, e: CommandRunEvent): Promise<unknown> {
return {};
}
+function tabPresses($: ModApi, bar: readonly BarTab[]): Record<string, () => void> {
+ return Object.fromEntries(bar.map((tab) => [tabPress(tab), () => selectTab($, tab)]));
+}
+
+/** Flow's rows open and close their detail; `j` and `k` step between calls. */
+function flowRowPresses($: ModApi): Record<string, () => void> {
+ return Object.fromEntries(flowPresses(flow.state).map(([key, id]) => [key, () => pressFlow($, key, id)]));
+}
+
+function pressFlow($: ModApi, key: string, id: string | null): void {
+ noteFlow(bind($), () => (id !== null ? { type: "toggle", id } : { type: "step", by: key === FLOW_NEXT ? 1 : -1 }));
+}
+
function selectTab($: ModApi, tab: PaneTab): void {
try {
dispatch(bind($), { type: "tab", tab });
@@ -715,25 +848,69 @@ function selectTab($: ModApi, tab: PaneTab): void {
}
}
-/** The shown tab's body; the map draws only on its own tab. */
-function tabBody(b: Bound, e: PaneRenderEvent): Node {
+/** Claude Code's theme, for the map's and Flow's colors; dark until read. */
+let theme: ThemeName = "dark";
+
+/** Reads the theme in the background; a failure keeps the last one (dark by default). */
+function readTheme($: ModApi): void {
+ $.config
+ .list()
+ .then((rows) => {
+ theme = themeOf(rows.find((r) => r.key === "theme")?.value);
+ })
+ .catch((err: unknown) => bind($).debug(`theme failed: ${String(err)}`));
+}
+
+/** A tab's body at this pane size; `rows` is the body's height under the tab row. */
+type TabBody = (b: Bound, e: PaneRenderEvent, rows: number) => Node;
+
+const TAB_BODIES: Record<PaneTab, TabBody> = {
+ 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),
+};
+
+/** The current turn for the map: from Flow's record, or from the map's own trail when Flow is off. */
+function mapTurn(): { lit: Lit; story: Story } {
+ if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state) };
+ const root = state.repoRoot;
+ const lit = root === null ? NO_LIT : litFromTrail(map.trail, root, isWindowsPath(root));
+ return { lit, story: storyFromTrail(map.trail) };
+}
+
+function mapBody(b: Bound, e: PaneRenderEvent): Node {
const { bodyColumns, placement, scroll } = e.props;
- const tab = state.pane.tab;
- if (tab !== "map") map.offScreen();
- if (tab === "ask") return askView(state, bodyColumns);
- if (tab === "recap") return recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, bodyColumns);
const d = discovery;
const notice = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];
- const bodyRows = scroll.bodyRows - TAB_ROWS;
- return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows });
+ return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows: scroll.bodyRows - TAB_ROWS, theme });
+}
+
+/** The map's "Health colours" button. */
+function pressHealth($: ModApi): void {
+ try {
+ map.toggleHealth(bind($));
+ } catch (err) {
+ bind($).debug(`health toggle failed: ${String(err)}`);
+ }
+}
+
+/** The shown tab's body; the map draws (and animates) only on its own tab, the owl ticks only on Flow's. */
+function tabBody(b: Bound, e: PaneRenderEvent): Node {
+ const tab = state.pane.tab;
+ if (tab !== "map") map.offScreen();
+ if (tab !== "flow") flow.hide();
+ const rows = (e.props.placement === "dock" ? e.props.scroll.bodyRows : PANE_ROWS) - TAB_ROWS;
+ return TAB_BODIES[tab](b, e, rows);
}
async function onPane($: ModApi, e: PaneRenderEvent, next: (e: PaneRenderEvent) => Promise<unknown>): Promise<unknown> {
if (e.requestId !== PANE_ID) return next(e);
const b = bind($);
try {
- const presses = Object.fromEntries(TABS.map((tab) => [TAB_PRESS[tab], () => selectTab($, tab)]));
- return materialize(paneView(state.pane.tab, tabBody(b, e)), $.ui.resolve(e), presses);
+ const bar = tabBar(flowOn);
+ const presses = { ...tabPresses($, bar), ...flowRowPresses($), [HEALTH_KEY]: () => pressHealth($) };
+ return materialize(paneView(state.pane.tab, tabBody(b, e), bar), $.ui.resolve(e), presses);
} catch (err) {
b.debug(`pane render failed: ${String(err)}`);
return next(e);
@@ -744,7 +921,11 @@ async function onPane($: ModApi, e: PaneRenderEvent, next: (e: PaneRenderEvent)
export function register(on: On, options: PluginOptions = {}): void {
reviewOn = options["lens_review"] !== false;
autoOpenOn = options["lens_pane_autoopen"] === true;
+ healthOn = options["lens_map_health"] === true;
+ flowOn = options["lens_flow"] !== false;
+ state = freshSession();
on("session.start", onSessionStart);
+ on("session.end", onSessionEnd);
on("turn.start", onTurnStart);
on("turn.complete", onTurnComplete);
on("ui.render", { component: "AbovePrompt" }, onBand);
diff --git a/packages/claude-mod/src/views/copy.ts b/packages/claude-mod/src/views/copy.ts
index d4f9cf309..4487cdb3a 100644
--- a/packages/claude-mod/src/views/copy.ts
+++ b/packages/claude-mod/src/views/copy.ts
@@ -7,7 +7,7 @@ import { formatNumber } from "@repowise-dev/ui/lib/format";
import { countOf, fit } from "../format";
import type { FileContext, HintKind, IndexFreshness, MarginNote, SavingsDelta } from "../model/session";
import type { Squeeze } from "../model/squeeze";
-import type { Callers } from "../model/trail";
+import type { Behind, ReplyFact } from "../model/replies";
export const HINTS: Record<HintKind, string> = {
"no-server": "Lens map needs the local server: repowise serve --no-ui",
@@ -183,26 +183,33 @@ export function runTestsPrompt(t: { tests: string[]; truncated: boolean; total:
return `Run the tests Repowise names for this change${rest}, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
}
-// The living map.
+// The map: the repo as quiet tiles, lit by the turn, with its story underneath.
export const MAP_COPY = {
title: "Lens",
looking: "Lens map: looking for the local server",
- loading: "Lens map: loading the health map",
- failed: "Lens map could not load the health map; it tries again on /lens",
+ loading: "Lens map: loading the map",
+ failed: "Lens map could not load; it tries again on /lens",
desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",
tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",
noScore: "Not scored",
- read: "Claude read",
- edited: "edited",
- importer: "imports the edited file",
- match: "search match",
waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens",
+ healthOn: "Health colours: on",
+ healthOff: "Health colours: off",
+ quiet: "Nothing lit yet this turn. Files Claude searches, opens and edits light up here.",
+} as const;
+
+/** The story strip's row heads, padded to one width. */
+export const STORY_COPY = {
+ searched: "SEARCHED",
+ opened: "OPENED",
+ edited: "EDITED",
+ reaches: "REACHES",
} as const;
/** What the desktop map says to a reader that cannot see it. */
export function mapAlt(drawn: number): string {
- return `Code health map: ${countOf(drawn, "file", "files")} drawn, colored by health band, with the files Claude read and edited marked`;
+ 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`;
}
/** /lens could not place the pane; the engine's reason names the width it needs. */
@@ -212,81 +219,85 @@ export function notPlacedLine(reason: string): string {
export interface ScopeFacts {
drawn: number;
+ /** Files in the feed: the largest, up to the server's cap. */
+ shown: number;
repositoryTotal: number;
/** "2h ago", or null when the server did not say. */
indexed: string | null;
- /** Files the server left out at its cap, and the cap. */
+ /** Files the server left out at its cap. */
beyondCap: number;
- cap: number;
+ /** Too many files for a pixel each: drawn as folders. */
+ dense: boolean;
+ /** Files the turn touched that are not on the map (outside the feed). */
+ notOnMap: number;
}
-/** Scope parts a narrow legend may leave out; the counts and the cap always stay. */
-export const SCOPE_REST = "rest empty or too small";
+/** Scope parts a narrow line may leave out; the counts and the cap always stay. */
+export const SCOPE_REST = "rest too small to draw";
export function indexedPart(age: string): string {
return `indexed ${age}`;
}
-/** The scope, as parts the legend joins with ` · ` and wraps onto two rows when narrow. */
+/** Under the server's cap: the largest files only, and of those, as many as are drawn (or as folders). */
+function cappedPart(s: ScopeFacts): string[] {
+ 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];
+}
+
+function drawnPart(s: ScopeFacts): string[] {
+ 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];
+}
+
+/** The scope, as parts the pane joins with ` · ` and wraps onto two rows when narrow. */
export function scopeParts(s: ScopeFacts): string[] {
- const parts =
- s.drawn === s.repositoryTotal
- ? [`${countOf(s.drawn, "file", "files")}, all drawn`]
- : [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];
+ const parts = drawnPart(s);
if (s.indexed !== null) parts.push(indexedPart(s.indexed));
- if (s.beyondCap > 0) parts.push(`${formatNumber(s.beyondCap)} beyond the ${formatNumber(s.cap)}-file cap`);
+ if (s.notOnMap > 0) parts.push(`${countOf(s.notOnMap, "touched file", "touched files")} not on the map`);
return parts;
}
-/**
- * Reads so far (`200+` once capped), what was not drawn, and what the last
- * search matched. Narrower than `columns`, a short form that keeps every count.
- */
-export function readsLine(
- reads: { count: number; capped: boolean; notDrawn: number },
- matched: number | null,
- columns = Number.POSITIVE_INFINITY,
-): string | null {
- const count = reads.capped ? `${formatNumber(reads.count)}+` : formatNumber(reads.count);
- const full: string[] = [];
- const short: string[] = [];
- if (reads.count > 0) {
- full.push(reads.capped ? `${count} files read` : countOf(reads.count, "file read", "files read"));
- short.push(`${count} read`);
- }
- if (reads.notDrawn > 0) {
- full.push(`${formatNumber(reads.notDrawn)} not drawn`);
- short.push(`${formatNumber(reads.notDrawn)} not drawn`);
- }
- if (matched !== null) {
- full.push(`last search matched ${countOf(matched, "file", "files")}`);
- short.push(`search matched ${formatNumber(matched)}`);
- }
- if (full.length === 0) return null;
- const line = full.join(" · ");
- return line.length <= columns ? line : short.join(" · ");
+/** `class QuerySet: 4 files`; a search with Flow off has no pattern. */
+export function searchedPart(pattern: string, hits: number | null): string {
+ const count = hits === null ? "matches not counted" : countOf(hits, "file", "files");
+ return pattern === "" ? `last search matched ${count}` : `${pattern}: ${count}`;
}
-/**
- * The importers of the edited file: inferred from the import graph, not
- * observed calls. Narrower than `columns`, a short form that keeps the counts
- * and cuts the file name instead (the legend's swatch names the basis).
- */
-export function callersLine(name: string, callers: Callers | null, notDrawn: number, columns = Number.POSITIVE_INFINITY): string {
- if (callers === null || callers.status === "loading") return `edited ${name} · finding the files that import it`;
- if (callers.status === "failed") return `edited ${name} · import graph unavailable`;
- const missing = notDrawn === 0 ? "" : ` · ${formatNumber(notDrawn)} not drawn`;
- const full = `edited ${name} · ${countOf(callers.paths.length, "file imports", "files import")} it (from imports, not calls)${missing}`;
- if (full.length <= columns) return full;
- const rest = ` · ${formatNumber(callers.paths.length)} import it${missing}`;
- return `edited ${fit(name, columns - "edited ".length - rest.length)}${rest}`;
+/** An edit's size: `+1 line`, `-3 lines`, `40 lines written`; nothing when unknown. */
+export function linesPart(lines: { delta: number } | { written: number } | null): string {
+ 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")}`;
+}
+
+export function namedByPart(name: string, tool: string): string {
+ return `◆ ${name} named by ${tool}`;
+}
+
+/** `12 importers: manager.py (opened), base.py, +9`. */
+export function reachesPart(total: number, names: readonly { name: string; opened: boolean }[]): string {
+ const shown = names.map((n) => (n.opened ? `${n.name} (opened)` : n.name));
+ const more = total - names.length;
+ return `${countOf(total, "importer", "importers")}: ${[...shown, ...(more > 0 ? [`+${formatNumber(more)}`] : [])].join(", ")}`;
+}
+
+export function reachesPending(edit: string): string {
+ return `finding the files that import ${edit}`;
}
+export const REACHES_FAILED = "import graph unavailable";
+
// The pane's tabs, Ask and Recap.
export const PANE_COPY = {
- command: "Open Lens: the health map, ask the index, and the session recap",
- argumentHint: "[map | ask <question> | recap]",
- tabs: { map: "Map", ask: "Ask", recap: "Recap" },
+ 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]",
+ tabs: { flow: "Flow", map: "Map", ask: "Ask", recap: "Recap" },
askLabel: "ask ",
askPlaceholder: "why ...? asks the decision records; anything else asks the index",
askSubmit: "ask",
@@ -389,3 +400,204 @@ export function briefDecision(title: string, reviewed: boolean): string {
export function briefTests(t: { tests: string[]; measured: boolean }): string {
return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
}
+
+// Flow: the turn dashboard. Every figure is measured by Lens (times, bytes,
+// counts of calls and files) or read from what Repowise returned, which says
+// when it is inferred.
+
+export const 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.",
+ notConnected: "Repowise is not connected in this repo, so only Claude's own steps show here.",
+ beforeAccept: "BEFORE YOU ACCEPT",
+ workingSet: "WORKING SET",
+ context: "CONTEXT",
+ calls: "REPOWISE CALLS",
+ asOfIndex: "as of the last index",
+ edited: "edited",
+ read: "read",
+ search: "search",
+ direct: "direct",
+ hotspot: "hotspot",
+ subagent: "subagent",
+ asking: "asking...",
+ error: "error",
+ beforeEdit: "from the index before this edit",
+ howAnswered: "how it was answered",
+ excerpt: "reply begins",
+ thenOpened: "Claude then opened",
+ nothingOpened: "nothing yet",
+ noRepowise: "No Repowise calls",
+ editNamed: "edit landed in a file Repowise named",
+ next: "Next call",
+ previous: "Previous call",
+} as const;
+
+/** `0:42`: minutes and seconds since the turn started. */
+export function clockText(ms: number): string {
+ const s = Math.max(0, Math.floor(ms / 1000));
+ return `${Math.floor(s / 60)}:${String(s % 60).padStart(2, "0")}`;
+}
+
+/** `420 ms`, `2.2 s`, `41 s`, `3 min 12 s`. */
+export function durationText(ms: number): string {
+ if (ms < 1000) return `${Math.max(0, Math.round(ms))} ms`;
+ if (ms < 10_000) return `${(ms / 1000).toFixed(1)} s`;
+ const s = Math.round(ms / 1000);
+ return s < 60 ? `${s} s` : `${Math.floor(s / 60)} min ${s % 60} s`;
+}
+
+/** `820 B`, `2.1 KB`, `1.2 MB`. */
+export function sizeText(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`;
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+}
+
+const END_WORD = { answer: "Done", stopped: "Stopped", failed: "Did not finish" } as const;
+export type EndWord = keyof typeof END_WORD;
+
+/**
+ * The status: `Working · 0:42` while Claude works, else how the turn ended
+ * (`Done`, `Stopped` when aborted, `Did not finish` on a refusal or an error)
+ * and how long it took; then `edited 1 file` when it edited.
+ */
+export function statusLine(end: EndWord | null, ms: number, edited: number): string {
+ const head = end === null ? `Working · ${clockText(ms)}` : `${END_WORD[end]} · ${durationText(ms)}`;
+ return edited === 0 ? head : `${head} · edited ${countOf(edited, "file", "files")}`;
+}
+
+/** `Repowise 3 calls · Claude opened 4 files, 2 named by Repowise first · edit landed in a file Repowise named`. */
+export function answerLine(t: { repowise: number; opened: number; named: number; editNamed: boolean }): string {
+ const parts = [t.repowise === 0 ? FLOW_COPY.noRepowise : `Repowise ${countOf(t.repowise, "call", "calls")}`];
+ const named = t.named > 0 ? `, ${formatNumber(t.named)} named by Repowise first` : "";
+ if (t.opened > 0) parts.push(`Claude opened ${countOf(t.opened, "file", "files")}${named}`);
+ if (t.editNamed) parts.push(FLOW_COPY.editNamed);
+ return parts.join(" · ");
+}
+
+/** `12 direct importers; Claude opened 2`. */
+export function importersLine(total: number, opened: number): string {
+ return `${countOf(total, "direct importer", "direct importers")}; Claude opened ${opened === 0 ? "none" : formatNumber(opened)}`;
+}
+
+/** `not opened, usually changes with it (co-change score): tests/queries/tests.py 0.80, sql/query.py 0.51`. */
+export function cochangeLine(partners: ReadonlyArray<{ path: string; score: number }>): string {
+ return `not opened, usually changes with it (co-change score): ${partners.map((p) => `${p.path} ${p.score.toFixed(2)}`).join(", ")}`;
+}
+
+/** `17 test files reach query.py (inferred); none run`. */
+export function testsReachLine(total: number, basis: "measured" | "inferred", run: number, file: string): string {
+ return `${countOf(total, "test file", "test files")} reach ${file} (${basis}); ${run === 0 ? "none" : formatNumber(run)} run`;
+}
+
+/** `this turn introduced 1 finding: complex method in query.py`. */
+export function introducedLine(n: number, first: { biomarker: string; path: string } | null): string {
+ const what = first === null ? "" : `: ${first.biomarker.replace(/_/g, " ")} in ${first.path.split("/").at(-1)}`;
+ return `this turn introduced ${countOf(n, "finding", "findings")}${what}`;
+}
+
+export const HEALTH_PARTLY = "health compared in part only; no new findings in the part compared";
+
+/** What the index knows of a file: `hotspot · 131 files use it · recent owner author_two 29 %`. */
+export function knowsParts(k: { hotspot: boolean | null; callerFiles: number | null; recentOwner: { name: string; share: number } | null }): string[] {
+ const parts: string[] = [];
+ if (k.hotspot === true) parts.push(FLOW_COPY.hotspot);
+ if (k.callerFiles !== null && k.callerFiles > 0) parts.push(countOf(k.callerFiles, "file uses it", "files use it"));
+ if (k.recentOwner !== null) parts.push(`recent owner ${k.recentOwner.name} ${Math.round(k.recentOwner.share * 100)} %`);
+ return parts;
+}
+
+export function moreFiles(n: number): string {
+ return `+${formatNumber(n)} more`;
+}
+
+export const CONTEXT_LABEL = { repowise: "Repowise", read: "file reads", search: "search", shell: "shell", other: "other" } as const;
+
+/** `Repowise 7.4 KB`. */
+export function contextPart(kind: keyof typeof CONTEXT_LABEL, bytes: number): string {
+ return `${CONTEXT_LABEL[kind]} ${sizeText(bytes)}`;
+}
+
+export function firstEditText(ms: number): string {
+ return `first edit after ${durationText(ms)}`;
+}
+
+/** An earlier turn in one line: `Turn 2 · 41 s · 2 Repowise calls · 3 files read · 0 edited`, saying when it stopped. */
+export function turnFooter(turn: number, ms: number | null, t: { repowise: number; reads: number; edits: number }, end: EndWord | null = "answer"): string {
+ 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`;
+}
+
+export function earlierLine(t: { turns: number; repowise: number; reads: number; edits: number }): string {
+ 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`;
+}
+
+export function hiddenSteps(n: number): string {
+ return `${countOf(n, "earlier call", "earlier calls")} hidden · j / k step through calls`;
+}
+
+export function laterSteps(n: number): string {
+ return `${countOf(n, "later call", "later calls")} below · j / k step through calls`;
+}
+
+export function droppedSteps(n: number): string {
+ return `${countOf(n, "earlier step", "earlier steps")} of this turn not kept`;
+}
+
+const INSIDE_UNITS: Record<string, [string, string]> = {
+ targets: ["target", "targets"],
+ docs: ["documentation page", "documentation pages"],
+ symbols: ["symbol", "symbols"],
+ callers: ["caller", "callers"],
+ callees: ["callee", "callees"],
+ decisions: ["decision", "decisions"],
+ hotspots: ["hotspot", "hotspots"],
+ dependents: ["direct dependent", "direct dependents"],
+ coChange: ["co-change partner", "co-change partners"],
+ contributors: ["contributor", "contributors"],
+ citations: ["cited file", "cited files"],
+ bodies: ["symbol body", "symbol bodies"],
+ rationale: ["rationale comment", "rationale comments"],
+ guesses: ["best guess", "best guesses"],
+ commits: ["commit", "commits"],
+ results: ["result", "results"],
+ lines: ["line", "lines"],
+};
+
+/** `40 of 180 symbols`, `12 direct dependents`; a key the reply named, as it named it. */
+export function insideFact(f: ReplyFact): string {
+ const [one, many] = INSIDE_UNITS[f.what] ?? [f.what.replace(/_/g, " "), f.what.replace(/_/g, " ")];
+ return f.of === undefined ? countOf(f.n, one, many) : `${formatNumber(f.n)} of ${countOf(f.of, one, many)}`;
+}
+
+/** How fresh the index the reply came from was: the local server's word, else the index's age. */
+export function freshnessText(b: Pick<Behind, "indexBehind" | "ageDays">): string | null {
+ if (b.indexBehind !== null) return b.indexBehind ? "index behind HEAD" : "index current";
+ return b.ageDays === null ? null : `index ${countOf(b.ageDays, "day", "days")} old`;
+}
+
+const ageText = (days: number): string => `index ${countOf(days, "day", "days")} old`;
+const when = (on: boolean, text: string): string | null => (on ? 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. */
+const BEHIND: ReadonlyArray<(b: Behind, bytes: number | null) => string | null> = [
+ (b) => named(b.commit, (c) => `indexed at ${c}`),
+ (b) => named(b.ageDays, ageText),
+ (b) => named(b.verified, (v) => (v ? "verified against the code" : "not verified")),
+ (b) => when(b.complete === false, "partial: the server capped it"),
+ (b) => named(b.confidence, (c) => `confidence ${c}`),
+ (b) => named(b.grounding, (g) => `grounding ${g.replace(/_/g, " ")}`),
+ (b) => named(b.retrieval, (r) => `retrieval ${r}`),
+ (b, bytes) => named(b.budget, (budget) => `reply ${bytes === null ? countOf(budget.used, "character", "characters") : sizeText(bytes)} (cap ${countOf(budget.limit, "character", "characters")})`),
+ (b) => named(b.omittedTokens, (t) => `${countOf(t, "token", "tokens")} left out, restorable`),
+ (b) => named(b.degraded, (d) => `degraded: ${d}`),
+ (b) => when(b.semantic === false, "semantic search off"),
+];
+
+export function behindParts(b: Behind, bytes: number | null = null): string[] {
+ return BEHIND.map((part) => part(b, bytes)).filter((p): p is string => p !== null);
+}
+
diff --git a/packages/claude-mod/src/views/elements.ts b/packages/claude-mod/src/views/elements.ts
index 1f7c238b4..93769c483 100644
--- a/packages/claude-mod/src/views/elements.ts
+++ b/packages/claude-mod/src/views/elements.ts
@@ -6,6 +6,7 @@
export interface TextProps {
dimColor?: boolean;
+ italic?: boolean;
wrap?: "truncate-end";
/** A theme key (`success`, `warning`, `error`: the terminal's own colors for health) or a hex color. */
color?: string;
@@ -21,7 +22,8 @@ export interface BoxProps {
export interface ButtonProps {
key: string;
label: string;
- hotkey: string;
+ /** Absent: a row pressed through the focus, with no key of its own. */
+ hotkey?: string;
/** Drawn as `1: label`, the way a survey's rows read. */
plain: true;
/** Dim at rest, full strength under the focus: a tab not shown. */
diff --git a/packages/claude-mod/src/views/flow.ts b/packages/claude-mod/src/views/flow.ts
new file mode 100644
index 000000000..e820b2fe3
--- /dev/null
+++ b/packages/claude-mod/src/views/flow.ts
@@ -0,0 +1,468 @@
+/**
+ * The Flow tab: a dashboard of the turn built from what only Lens sees. The
+ * owl and the turn's status; what each edit reaches that Claude did not look
+ * at (before you accept); the files it worked from and how it came to them
+ * (working set); what filled its context (a bar of measured bytes); and the
+ * Repowise calls, one line each, detail on press. Each section draws only
+ * when it has something to say. Readable text keeps the terminal's own
+ * foreground or its dim; only marks take an accent, and nothing sets a
+ * background. Pure: the clock, the width, the rows, the file cards and the
+ * turn's review come in on `FlowViewInput`.
+ */
+
+import { fit } from "../format";
+import { inFlight, isWorking, openable, pathKey, turnTotals, type Activity, type FlowState, type FlowTurn } from "../model/flow";
+import type { ChangeRisk } from "../model/review";
+import type { FileContext, Mode } from "../model/session";
+import {
+ CONTEXT_KINDS,
+ answeredBeforeEdit,
+ beforeAccept,
+ contextBytes,
+ firstEditMs,
+ workingSet,
+ type ContextKind,
+ type Gaps,
+ type Via,
+ type WorkingFile,
+} from "../model/turnFacts";
+import {
+ FLOW_COPY,
+ HEALTH_PARTLY,
+ answerLine,
+ behindParts,
+ clockText,
+ cochangeLine,
+ contextPart,
+ droppedSteps,
+ durationText,
+ earlierLine,
+ firstEditText,
+ freshnessText,
+ hiddenSteps,
+ importersLine,
+ insideFact,
+ introducedLine,
+ knowsParts,
+ laterSteps,
+ moreFiles,
+ statusLine,
+ testsReachLine,
+ turnFooter,
+} from "./copy";
+import { box, button, text, type Node, type TextProps } from "./elements";
+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_NEXT = "lens-flow-next";
+export const FLOW_PREV = "lens-flow-prev";
+/** How long the owl stays happy after a turn ends. */
+export const HAPPY_MS = 3_000;
+/** Below this width the working set drops what the index knows. */
+export const NARROW = 80;
+const MIN_BODY = 3;
+/** The quiet mark beside the call Claude is waiting on. */
+export const ACTIVE_MARK = "▸";
+const GUTTER = 2;
+const CLOCK_W = 6;
+/** The label column of an open call's detail. */
+const DETAIL_W = 20;
+const DETAIL_INDENT = GUTTER + CLOCK_W;
+/** The empty state's widest line. */
+const EMPTY_W = 70;
+/** Working-set rows drawn before `+N more`. */
+const WORKING_ROWS = 6;
+const FILE_W = 44;
+const KIND_W = 8;
+const VIA_W = 13;
+const BAR_W = 60;
+/** Facts from a reply drawn on a call's line. */
+const BUILT_FROM = 2;
+/** Columns a call's target keeps before its facts are cut. */
+const TARGET_MIN = 28;
+const SEP = " · ";
+const EXCERPT_LINE = 160;
+
+export interface FlowViewInput {
+ columns: number;
+ /** Rows the tab body may take. */
+ rows: number;
+ now: number;
+ /** Reduced motion: the owl holds still. */
+ still: boolean;
+ mode: Mode | null;
+ /** File cards from the index, by repo-relative path. */
+ contexts: Readonly<Record<string, FileContext>>;
+ /** The change review of this turn, when one ran. */
+ review: ChangeRisk | null;
+ /** The terminal's theme is light: accents come from the light ramp. Dark when unknown. */
+ light?: boolean;
+}
+
+/** The Button key of an openable row. */
+export const rowKey = (id: string): string => `${FLOW_KEY}-${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]> {
+ return [[FLOW_NEXT, null], [FLOW_PREV, null], ...openable(state).map((id): [string, string] => [rowKey(id), id])];
+}
+
+/** A run of text in a row; `flex` is the one cut to fit; `press` makes it a Button. Never a background. */
+interface Seg {
+ t: string;
+ color?: string;
+ dim?: boolean;
+ flex?: boolean;
+ press?: string;
+}
+
+/** One drawn line, the call it belongs to, and its height when not one row. */
+interface Line {
+ node: Node;
+ id?: string;
+ height?: number;
+}
+
+const width = (segs: readonly Seg[]): number => segs.reduce((n, s) => n + s.t.length, 0);
+
+function segNode(s: Seg): Node {
+ if (s.press !== undefined) return { type: "Button", props: { key: s.press, label: s.t, plain: true } };
+ const props: TextProps = {};
+ if (s.color !== undefined) props.color = s.color;
+ if (s.dim === true) props.dimColor = true;
+ return text(s.t, props);
+}
+
+/** Segments fitted to `columns` (the flex one cut), and `right` pushed to the right edge. */
+function row(segs: Seg[], columns: number, right: Seg[] = []): Node {
+ 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));
+ const gap = right.length > 0 ? Math.max(2, columns - width(fitted) - width(right)) : 0;
+ const all = gap > 0 ? [...fitted, { t: " ".repeat(gap) }, ...right] : fitted;
+ return box({ flexDirection: "row" }, all.filter((s) => s.t !== "").map(segNode));
+}
+
+const dimLine = (t: string, columns: number): Node => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" });
+const pad = (n: number): Seg => ({ t: " ".repeat(n) });
+
+/** Words in lines of at most `columns`. */
+function wrapWords(words: string, columns: number): string[] {
+ return packRows(words.split(" "), (w) => w.length, Math.max(1, columns), 1).map((r) => r.join(" "));
+}
+
+/** A dim caption over a section's lines; nothing at all when the section has none. */
+function section(caption: string, lines: Node[]): Node[] {
+ return lines.length === 0 ? [] : [text(caption, { dimColor: true }), ...lines];
+}
+
+// The owl and the header.
+
+function owlState(state: FlowState, now: number): OwlState {
+ const last = state.turns.at(-1);
+ if (last === undefined) return "asleep";
+ if (isWorking(state)) return inFlight(state) === null ? "watching" : "asking";
+ if (last.end === "stopped" || last.end === "failed") return "stopped";
+ return last.endedAt !== null && now - last.endedAt < HAPPY_MS ? "happy" : "asleep";
+}
+
+/** `Done · 41 s · edited 1 file` (with a thistle after an answer), or `Working · 0:42`. */
+function statusSegs(turn: FlowTurn, now: number, theme: FlowTheme): Seg[] {
+ const edited = turnTotals(turn).edits;
+ if (turn.endedAt === null) return [{ t: statusLine(null, now - turn.startedAt, edited) }];
+ const end = turn.end ?? "answer";
+ const line: Seg = { t: statusLine(end, turn.durationMs ?? 0, edited) };
+ return end === "answer" ? [line, { t: ` ${THISTLE}`, color: theme.plum }] : [line];
+}
+
+function notice(mode: Mode | null): string | null {
+ return mode === "no-index" || mode === "no-cli" ? FLOW_COPY.notConnected : null;
+}
+
+/**
+ * The header: the owl and the status on one line, then the answer at full
+ * strength, then the user's own words, dim. Empty, the owl asleep and what
+ * the tab will show.
+ */
+function header(state: FlowState, v: FlowViewInput, theme: FlowTheme): Node[] {
+ const turn = state.turns.at(-1);
+ const st = owlState(state, v.now);
+ const face = box({ flexDirection: "row" }, owl(st, owlEyes(st, v.now, v.still), theme.amber));
+ const room = v.columns - OWL_WIDTH - 1;
+ const said = notice(v.mode);
+ const tail = said === null ? [] : [dimLine(said, v.columns)];
+ if (turn === undefined) {
+ const [first = "", ...rest] = wrapWords(FLOW_COPY.empty, Math.min(EMPTY_W, room));
+ return [box({ flexDirection: "row", columnGap: 1 }, [face, text(first)]), ...rest.map((l) => text(`${" ".repeat(OWL_WIDTH + 1)}${l}`)), ...tail];
+ }
+ const prompt = turn.prompt.replace(/\s+/g, " ").trim();
+ return [
+ box({ flexDirection: "row", columnGap: 1 }, [face, row(statusSegs(turn, v.now, theme), room)]),
+ text(fit(answerLine(turnTotals(turn)), v.columns), { wrap: "truncate-end" }),
+ ...(prompt === "" ? [] : [dimLine(`"${prompt}"`, v.columns)]),
+ ...tail,
+ ];
+}
+
+// Before you accept.
+
+const fileName = (path: string): string => path.split("/").at(-1) ?? path;
+
+function gapLines(g: Gaps): string[] {
+ const out: string[] = [];
+ if (g.importers !== null) out.push(importersLine(g.importers.total, g.importers.opened));
+ if (g.cochange.length > 0) out.push(cochangeLine(g.cochange));
+ if (g.tests !== null) out.push(testsReachLine(g.tests.total, g.tests.basis, g.tests.run, fileName(g.path)));
+ return out;
+}
+
+/** The turn's health from its change review: what it introduced, or that it was compared in part only. */
+function healthLines(risk: ChangeRisk | null): string[] {
+ const hd = risk?.health_delta;
+ if (hd === undefined) return [];
+ if (hd.introduced > 0) return [introducedLine(hd.introduced, hd.top_findings.find((f) => f.change === "introduced") ?? null)];
+ return hd.status === "partial" ? [HEALTH_PARTLY] : [];
+}
+
+function beforeAcceptLines(state: FlowState, turn: FlowTurn, v: FlowViewInput): Node[] {
+ const files = beforeAccept(state, turn).flatMap((g) => [
+ row([pad(2), { t: g.path, flex: true }, { t: ` ${FLOW_COPY.asOfIndex}`, dim: true }], v.columns),
+ ...gapLines(g).map((l) => dimLine(` ${l}`, v.columns)),
+ ]);
+ const health = healthLines(v.review).map((l) => text(fit(` ${l}`, v.columns)));
+ return section(FLOW_COPY.beforeAccept, [...files, ...health]);
+}
+
+// The working set.
+
+function viaSeg(via: Via, theme: FlowTheme): Seg {
+ if (via.kind === "repowise") return { t: via.tool.padEnd(VIA_W), color: theme.plum };
+ return { t: (via.kind === "search" ? FLOW_COPY.search : FLOW_COPY.direct).padEnd(VIA_W), dim: true };
+}
+
+interface TableContext {
+ cards: ReadonlyMap<string, FileContext>;
+ columns: number;
+ fileW: number;
+ theme: FlowTheme;
+}
+
+function workingRow(f: WorkingFile, t: TableContext): Node {
+ const card = t.cards.get(pathKey(f.path));
+ const knows = t.columns < NARROW || card === undefined ? "" : knowsParts(card).join(SEP);
+ const kind: Seg = { 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);
+}
+
+function workingLines(state: FlowState, turn: FlowTurn, v: FlowViewInput, theme: FlowTheme): Node[] {
+ const files = workingSet(state, turn);
+ const longest = Math.max(0, ...files.map((f) => f.path.length));
+ const t: TableContext = {
+ cards: new Map(Object.entries(v.contexts).map(([p, c]) => [pathKey(p), c])),
+ columns: v.columns,
+ fileW: Math.min(FILE_W, longest, Math.max(8, v.columns - 2 - KIND_W - VIA_W - 4)),
+ theme,
+ };
+ const rows = files.slice(0, WORKING_ROWS).map((f) => workingRow(f, t));
+ const more = files.length > WORKING_ROWS ? [dimLine(` ${moreFiles(files.length - WORKING_ROWS)}`, v.columns)] : [];
+ return section(`${FLOW_COPY.workingSet} · ${FLOW_COPY.asOfIndex}`, [...rows, ...more]);
+}
+
+// What filled Claude's context.
+
+/** One shade per kind, so the bar reads without color on any ground; Repowise's carries the plum mark. */
+const SHADE: Record<ContextKind, string> = { repowise: "█", read: "▓", search: "▒", shell: "░", other: "·" };
+
+/** Cells per kind, at least one for any that has bytes, summing to about `cells`. */
+function cellsOf(bytes: Record<ContextKind, number>, total: number, cells: number): Array<[ContextKind, number]> {
+ return CONTEXT_KINDS.filter((k) => bytes[k] > 0).map((k): [ContextKind, number] => [k, Math.max(1, Math.round((bytes[k] / total) * cells))]);
+}
+
+function shadeSeg(kind: ContextKind, n: number, theme: FlowTheme): Seg {
+ const t = SHADE[kind].repeat(n);
+ return kind === "repowise" ? { t, color: theme.plum } : { t };
+}
+
+function contextLines(turn: FlowTurn, columns: number, theme: FlowTheme): Node[] {
+ const bytes = contextBytes(turn);
+ const total = CONTEXT_KINDS.reduce((n, k) => n + bytes[k], 0);
+ if (total === 0) return [];
+ const cells = cellsOf(bytes, total, Math.min(BAR_W, columns - 4));
+ const bar = row([pad(2), ...cells.map(([k, n]) => shadeSeg(k, n, theme))], columns);
+ const legend = cells.map(([k]) => `${SHADE[k]} ${contextPart(k, bytes[k])}`);
+ const first = firstEditMs(turn);
+ const parts = first === null ? legend : [...legend, firstEditText(first)];
+ const lines = packRows(parts, (p) => p.length, Math.max(10, columns - 2), 2).map((r) => dimLine(` ${r.join(" ")}`, columns));
+ return section(FLOW_COPY.context, [bar, ...lines]);
+}
+
+// The Repowise calls.
+
+interface CallContext {
+ turn: FlowTurn;
+ columns: number;
+ /** The call Claude is waiting on. */
+ active: string | null;
+ open: string | null;
+ theme: FlowTheme;
+ /** Calls that asked about a file Claude had already edited. */
+ beforeEdit: ReadonlySet<string>;
+ /** Files Claude opened after each Repowise reply named them, by that reply's id. */
+ opened: ReadonlyMap<string, string[]>;
+}
+
+function lead(a: Activity, ctx: CallContext): Seg[] {
+ const mark: Seg = 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 }];
+}
+
+/** What a reply was built from: quietly, when it predates an edit; then its first facts and how fresh the index was. */
+function builtFrom(a: Activity, ctx: CallContext): string[] {
+ 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])];
+}
+
+function rightOf(a: Activity, ctx: CallContext): string {
+ 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(SEP);
+}
+
+function callLine(a: Activity, ctx: CallContext): Line {
+ const what = a.args[0]?.[1] ?? "";
+ const sub: Seg[] = a.agentId === null ? [] : [{ t: ` ${FLOW_COPY.subagent}`, dim: true }];
+ const segs: Seg[] = [...lead(a, ctx), { t: a.tool, press: rowKey(a.id) }, pad(2), { t: what, flex: true }, ...sub];
+ // The target keeps its room; the facts at the right edge give way first.
+ 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 };
+}
+
+function labeled(label: string, body: string, ctx: CallContext, id: string): Line {
+ return { node: row([pad(DETAIL_INDENT), { t: label.padEnd(DETAIL_W), dim: true }, { t: body, flex: true }], ctx.columns), id };
+}
+
+/** Parts joined with ` · `, wrapped onto as many lines as they need, the label on the first. */
+function wrapped(label: string, parts: string[], ctx: CallContext, id: string): Line[] {
+ const room = Math.max(10, ctx.columns - DETAIL_INDENT - DETAIL_W);
+ return packRows(parts, (p) => p.length, room, SEP.length).map((r, i) => labeled(i === 0 ? label : "", r.join(SEP), ctx, id));
+}
+
+/** A reply's account of itself and its first characters. */
+function replyDetail(a: Activity, ctx: CallContext): Line[] {
+ const reply = a.reply;
+ if (reply === null) return [];
+ const excerpt = reply.excerpt === "" ? [] : [labeled(FLOW_COPY.excerpt, reply.excerpt.replace(/\s+/g, " ").slice(0, EXCERPT_LINE), ctx, a.id)];
+ 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];
+}
+
+/** An open call's detail: how it was answered, its first characters, and what Claude opened after. */
+function detailLines(a: Activity, ctx: CallContext): Line[] {
+ 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)];
+}
+
+/** Files opened after a reply named them, by the reply's id, in the order opened. */
+function openedAfter(state: FlowState): Map<string, string[]> {
+ const out = new Map<string, string[]>();
+ for (const a of state.turns.flatMap((t) => t.activities)) {
+ const by = a.namedBy?.id;
+ const path = a.paths[0];
+ if (by === undefined || path === undefined) continue;
+ const list = out.get(by) ?? [];
+ if (!list.includes(path)) list.push(path);
+ out.set(by, list);
+ }
+ return out;
+}
+
+const isCall = (a: Activity): boolean => a.kind === "repowise";
+
+function callLines(state: FlowState, turn: FlowTurn, v: FlowViewInput, theme: FlowTheme): Line[] {
+ const ctx: CallContext = {
+ turn,
+ columns: v.columns,
+ active: isWorking(state) ? (inFlight(state)?.id ?? null) : null,
+ open: state.open,
+ theme,
+ beforeEdit: answeredBeforeEdit(state),
+ opened: openedAfter(state),
+ };
+ const calls = turn.activities.filter(isCall).flatMap((a) => [callLine(a, ctx), ...detailLines(a, ctx)]);
+ const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine(` ${droppedSteps(turn.dropped)}`, v.columns) }] : [];
+ return [...dropped, ...calls];
+}
+
+const heightOf = (l: Line): number => l.height ?? 1;
+const total = (lines: readonly Line[]): number => lines.reduce((n, l) => n + heightOf(l), 0);
+
+/** Where a window of `room` starts: one line above the open row, else so the newest fit. */
+function windowStart(lines: Line[], room: number, open: string | null): number {
+ const at = open === null ? -1 : lines.findIndex((l) => l.id === open);
+ const floor = at < 0 ? lines.length - 1 : Math.max(0, at - 1);
+ let start = 0;
+ while (start < floor && total(lines.slice(start)) > room) start++;
+ return start;
+}
+
+/** Calls in `lines` with no line in `shown`. */
+function stepsOutside(lines: Line[], shown: ReadonlySet<string | undefined>): number {
+ return new Set(lines.map((l) => l.id).filter((id) => !shown.has(id))).size;
+}
+
+/** The lines that fit in `room`, with a count of the calls above, and below, that do not. */
+function windowed(lines: Line[], room: number, open: string | null): Line[] {
+ if (total(lines) <= room) return lines;
+ const start = windowStart(lines, room - 2, open);
+ let end = lines.length;
+ while (end > start + 1 && total(lines.slice(start, end)) > room - 2) end--;
+ const shown = new Set(lines.slice(start, end).map((l) => l.id));
+ const above = stepsOutside(lines.slice(0, start), shown);
+ const below = stepsOutside(lines.slice(end), shown);
+ const note = (n: number, say: (n: number) => string): Line[] => (n === 0 ? [] : [{ node: dimLine(say(n), Number.POSITIVE_INFINITY) }]);
+ return [...note(above, hiddenSteps), ...lines.slice(start, end), ...note(below, laterSteps)];
+}
+
+// Earlier turns.
+
+
+/** Earlier turns, newest first, one line each; then the folded ones. */
+function earlierTurns(state: FlowState, columns: number): Node[] {
+ const out = state.turns
+ .slice(0, -1)
+ .reverse()
+ .map((t) => dimLine(` ${turnFooter(t.seq, t.durationMs, turnTotals(t), t.end)}`, columns));
+ if (state.earlier.turns > 0) out.push(dimLine(` ${earlierLine(state.earlier)}`, columns));
+ return out;
+}
+
+function navRow(state: FlowState): Node[] {
+ if (openable(state).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)])];
+}
+
+/** The fixed sections of the latest turn. */
+function dashboard(state: FlowState, turn: FlowTurn, v: FlowViewInput, theme: FlowTheme): Node[] {
+ return [...beforeAcceptLines(state, turn, v), ...workingLines(state, turn, v, theme), ...contextLines(turn, v.columns, theme)];
+}
+
+/** Under a turn that ended with an answer, the hills reflected; quiet otherwise. */
+function closing(turn: FlowTurn | undefined, columns: number): Node[] {
+ return turn !== undefined && turn.end === "answer" ? [text(loch(columns), { dimColor: true })] : [];
+}
+
+export function flowView(state: FlowState, v: FlowViewInput): Node {
+ const theme = flowTheme(v.light === true);
+ const head = [text(hills(v.columns), { color: theme.plum }), ...header(state, v, theme)];
+ const turn = state.turns.at(-1);
+ const fixed = turn === undefined ? [] : dashboard(state, turn, v, theme);
+ const after = [...closing(turn, v.columns), ...earlierTurns(state, v.columns), ...navRow(state)];
+ 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]);
+}
diff --git a/packages/claude-mod/src/views/map.ts b/packages/claude-mod/src/views/map.ts
index 24ae3d03a..1ad5714f5 100644
--- a/packages/claude-mod/src/views/map.ts
+++ b/packages/claude-mod/src/views/map.ts
@@ -1,16 +1,20 @@
/**
- * The living map: a squarified treemap of the health-map feed, sized by lines
- * of code and grouped by folder, rasterized into terminal cells. Each cell
- * holds two map pixels as an upper half block (top pixel the glyph, bottom
- * pixel the background), so the pixel grid is `columns x rows * 2`, near square.
+ * The map: a squarified treemap of the health-map feed, sized by lines of
+ * code and grouped by folder, rasterized into terminal cells. Each cell holds
+ * two map pixels as a half block, so the pixel grid is `columns x rows * 2`,
+ * near square.
*
- * Pure: the layout, its base pixels and the cell encoding. views/overlay.ts
- * paints Claude's marks on top; register.ts blits the animated frames.
+ * By default a ghost map: every file a quiet tile in two near-ground tones of
+ * the theme's ramp, so the turn's marks (views/overlay.ts) are the only
+ * colour. Health colours are a toggle. Where files are too many for a pixel
+ * each, folders are drawn as tiles instead of per-file shimmer. Empty ground
+ * is the terminal's own background. Pure.
*/
import { hierarchy, treemap, treemapSquarify, type HierarchyRectangularNode } from "d3-hierarchy";
import { bandForScore, type HealthFileMetric } from "@repowise-dev/types/health";
-import { BRAND, DARK, DARK_CANVAS, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
+import { BRAND, DARK, DARK_CANVAS, DARK_CANVAS_BAND, LIGHT } from "@repowise-dev/ui/brand";
+import type { ThemeName } from "./theme";
export type MapFile = Pick<HealthFileMetric, "file_path" | "score" | "nloc">;
@@ -46,6 +50,29 @@ export interface MapLabel {
text: string;
}
+/** A name written on the map in its own color, on the terminal's background. */
+export interface NameLabel extends MapLabel {
+ color: number;
+}
+
+/** How the map is drawn: the theme's ramp, and health colours on or off. */
+export interface MapStyle {
+ theme: ThemeName;
+ health: boolean;
+}
+
+/** The ghost tiles, folder names, and the turn's marks, per theme. */
+export interface MapPalette {
+ tileA: number;
+ tileB: number;
+ folder: number;
+ hit: number;
+ read: number;
+ named: number;
+ importer: number;
+ edit: number;
+}
+
export interface MapLayout {
columns: number;
rows: number;
@@ -57,22 +84,68 @@ export interface MapLayout {
files: PlacedFile[];
/** Indices into `files` of those that own at least one pixel. */
drawn: number[];
- /** Drawn file by repo-relative path (lowercase where paths are case-insensitive). */
+ /** Every placed file by repo-relative path (lowercased where paths are case-insensitive), drawn or not: a lit one too small for a pixel still lights a cell. */
index: Map<string, number>;
+ /** The same, always lowercased: for paths that arrive lowercased (the files a Repowise reply named). */
+ lower: Map<string, number>;
caseInsensitive: boolean;
labels: MapLabel[];
base: Uint32Array;
+ style: MapStyle;
+ /** Too many files for a pixel each: folders are drawn as tiles. */
+ dense: boolean;
+ /** Every folder below the groups, parents first, as painted. */
+ folders: FolderTile[];
}
const UPPER_HALF = 0x2580;
+const LOWER_HALF = 0x2584;
+const SPACE = 0x20;
const hex = (s: string): number => parseInt(s.slice(1), 16);
-export const ACCENT = hex(BRAND.accent);
-/** The canvas ground and gutters: painted, never the terminal's own background. */
+/**
+ * The empty ground between tiles, as a pixel value: overlay marks blend with
+ * it as a fixed dark, and the cell encoding draws it as the terminal's own
+ * background, so the map blends into the pane.
+ */
export const GROUND = hex(DARK.bgRoot);
+/** A Raster color: the terminal's own default (foreground or background). */
+export const TERMINAL_DEFAULT = 0x01000000;
export const LABEL_FG = hex(DARK.textSecondary);
const NEUTRAL = hex(DARK_CANVAS.nodeNeutral);
const BLACK = 0x000000;
+/**
+ * Measured on black and on the dock's ~#1f1f1f: dark tiles 1.4 to 1.6:1 (a
+ * quiet plan), marks 2.4:1 (a search's glow) to 9:1 (the edit); on white,
+ * light tiles 1.3 to 1.4:1 and marks 1.8 to 8.6:1.
+ */
+export const MAP_PALETTES: Record<ThemeName, MapPalette> = {
+ dark: {
+ tileA: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.12),
+ tileB: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.22),
+ folder: hex(DARK.textTertiary),
+ hit: mix(hex(DARK.bgElevated), hex(DARK.textSecondary), 0.32),
+ read: hex(DARK.textSecondary),
+ named: mix(hex(DARK.accentSecondary), hex(DARK.bgRoot), 0.45),
+ importer: hex(DARK.accentSecondary),
+ edit: hex(BRAND.accent),
+ },
+ light: {
+ tileA: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.08),
+ tileB: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.16),
+ folder: hex(LIGHT.textTertiary),
+ hit: mix(hex(LIGHT.bgInset), hex(LIGHT.textSecondary), 0.3),
+ read: hex(LIGHT.textSecondary),
+ named: mix(hex(LIGHT.accentSecondary), hex(LIGHT.bgRoot), 0.55),
+ importer: hex(LIGHT.accentSecondary),
+ edit: hex(BRAND.accentTextLight),
+ },
+};
+
+export const DEFAULT_STYLE: MapStyle = { theme: "dark", health: false };
+/** Fewer files than this share own a pixel: the map draws folders, not files. */
+const DENSE_SHARE = 0.6;
+
/** A folder holding more than this share of the lines is split into its subfolders. */
const SPLIT_SHARE = 0.25;
const MAX_SPLITS = 8;
@@ -146,17 +219,42 @@ interface Datum {
name: string;
file?: MapFile;
children?: Datum[];
+ /** Subfolders by name, while the tree is built. */
+ kids?: Map<string, Datum>;
+}
+
+const folderDatum = (name: string): Datum => ({ name, children: [], kids: new Map() });
+
+/** Files the group holds, under nested folders from the group's own folder down. */
+function insertFile(group: Datum, key: string, file: MapFile): void {
+ const rel = key === "" ? file.file_path : file.file_path.slice(key.length + 1);
+ let node = group;
+ for (const dir of rel.split("/").slice(0, -1)) {
+ let next = node.kids?.get(dir);
+ if (next === undefined) {
+ next = folderDatum(dir);
+ node.kids?.set(dir, next);
+ node.children?.push(next);
+ }
+ node = next;
+ }
+ node.children?.push({ name: file.file_path, file });
}
-/** The two-level tree (groups, then files), laid out by d3's squarified treemap. */
+/**
+ * The tree (groups, then each folder inside them, then files), laid out by
+ * d3's squarified treemap, so every folder is one rectangle.
+ */
function treemapOf(files: readonly MapFile[], width: number, height: number): HierarchyRectangularNode<Datum> {
const keys = groupKeys(files);
- const groups = new Map<string, Datum[]>();
+ const groups = new Map<string, Datum>();
files.forEach((file, i) => {
const key = keys[i] ?? "";
- groups.set(key, [...(groups.get(key) ?? []), { name: file.file_path, file }]);
+ const group = groups.get(key) ?? folderDatum(key);
+ groups.set(key, group);
+ insertFile(group, key, file);
});
- const data: Datum = { name: "", children: [...groups].map(([name, children]) => ({ name, children })) };
+ const data: Datum = { name: "", children: [...groups.values()] };
const root = hierarchy(data)
.sum((d) => d.file?.nloc ?? 0)
.sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));
@@ -196,8 +294,41 @@ function placeFile(leaf: HierarchyRectangularNode<Datum>, group: number, inner:
};
}
-function paintFile(base: Uint32Array, width: number, f: PlacedFile): void {
- const fill = colorForScore(f.score);
+/** A file's tile: its health band, or one of the two ghost tones, alternating. */
+function tileFor(f: PlacedFile, i: number, style: MapStyle): number {
+ const pal = MAP_PALETTES[style.theme];
+ if (style.health) return colorForScore(f.score);
+ return i % 2 === 0 ? pal.tileA : pal.tileB;
+}
+
+/** A rectangle of pixels in one ghost tone. */
+function paintBox(base: Uint32Array, width: number, box: { x0: number; y0: number; x1: number; y1: number }, fill: number): void {
+ for (let y = box.y0; y < box.y1; y++) base.fill(fill, y * width + box.x0, y * width + box.x1);
+}
+
+/** A folder inside a group: its pixels (within the group's interior) and its tone, alternating among its siblings. */
+export interface FolderTile {
+ x0: number;
+ y0: number;
+ x1: number;
+ y1: number;
+ tone: 0 | 1;
+}
+
+/** Every folder below the groups, parents before children, so the deepest folder big enough to show wins. */
+function folderTiles(group: HierarchyRectangularNode<Datum>, inner: ReturnType<typeof groupInterior>): FolderTile[] {
+ const out: FolderTile[] = [];
+ for (const node of group.descendants()) {
+ if (node === group || node.children === undefined) continue;
+ const tone = ((node.parent?.children ?? []).indexOf(node) % 2) as 0 | 1;
+ const [x0, x1] = pixelSpan(node.x0, node.x1);
+ const [y0, y1] = pixelSpan(node.y0, node.y1);
+ out.push({ x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1), tone });
+ }
+ return out;
+}
+
+function paintFile(base: Uint32Array, width: number, f: PlacedFile, fill: number): void {
const edge = mix(fill, BLACK, 0.3);
const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;
const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;
@@ -215,12 +346,18 @@ export function labelText(key: string, width: number): string | null {
return text !== undefined && /^[\x20-\x7e]+$/.test(text) ? text : null;
}
+/** Folder names only where a group is big enough to read as a region, and at most a few: never noisy. */
+const LABEL_MIN_COLS = 12;
+const LABEL_MIN_ROWS = 3;
+const MAX_LABELS = 8;
+
function labelFor(g: MapGroup, columns: number, rows: number): MapLabel | null {
const col = Math.ceil(g.rect.x);
const row = Math.ceil(g.rect.y / 2);
const width = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;
const height = Math.floor((g.rect.y + g.rect.h) / 2) - row;
- if (g.key === "" || height < 2 || row >= rows) return null;
+ const small = height < LABEL_MIN_ROWS || width < LABEL_MIN_COLS;
+ if (g.key === "" || small || row >= rows) return null;
const text = labelText(g.key, width);
return text === null ? null : { row, col, text };
}
@@ -230,15 +367,47 @@ function labelsFor(groups: readonly MapGroup[], columns: number, rows: number):
return [...groups]
.sort((a, b) => b.nloc - a.nloc)
.map((g) => labelFor(g, columns, rows))
- .filter((l): l is MapLabel => l !== null);
+ .filter((l): l is MapLabel => l !== null)
+ .slice(0, MAX_LABELS);
+}
+
+/**
+ * The base pixels: ghost folder tones under everything (no holes where files
+ * are too small), then each file's tile, unless the map is dense, where the
+ * folder tones alone are drawn.
+ */
+function paintBase(
+ map: { width: number; height: number; groups: MapGroup[]; folders: FolderTile[]; files: PlacedFile[]; drawn: number[] },
+ style: MapStyle,
+ dense: boolean,
+): Uint32Array {
+ const { width, height } = map;
+ const base = new Uint32Array(width * height).fill(GROUND);
+ const pal = MAP_PALETTES[style.theme];
+ const tone = (t: number) => (t === 0 ? pal.tileB : pal.tileA);
+ if (!style.health) map.groups.forEach((g, i) => paintBox(base, width, groupInterior(g.rect, width, height), tone(i % 2)));
+ if (!style.health) for (const f of map.folders) paintBox(base, width, f, tone(1 - f.tone));
+ if (dense && !style.health) return base;
+ for (const i of map.drawn) paintFile(base, width, map.files[i] as PlacedFile, tileFor(map.files[i] as PlacedFile, i, style));
+ return base;
}
/**
* Lays the feed out on a `columns x rows` cell canvas. Deterministic: ties
* break on path. Files too small for a whole pixel at this size are placed but
- * not drawn; the legend counts only what is drawn.
+ * not drawn; the scope line counts only what is drawn.
*/
-export function layoutMap(feed: readonly MapFile[], columns: number, rows: number, caseInsensitive: boolean): MapLayout {
+/** The canvas a layout is for: its size in cells, how paths compare, and how it is drawn. */
+export interface MapCanvas {
+ columns: number;
+ rows: number;
+ caseInsensitive: boolean;
+ style?: MapStyle;
+}
+
+export function layoutMap(feed: readonly MapFile[], canvas: MapCanvas): MapLayout {
+ const { columns, rows, caseInsensitive } = canvas;
+ const style = canvas.style ?? DEFAULT_STYLE;
const width = columns;
const height = rows * 2;
const root = treemapOf(
@@ -248,21 +417,34 @@ export function layoutMap(feed: readonly MapFile[], columns: number, rows: numbe
);
const groups: MapGroup[] = [];
const files: PlacedFile[] = [];
+ const folders: FolderTile[] = [];
for (const node of root.children ?? []) {
const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;
const inner = groupInterior(rectOf(node), width, height);
- for (const leaf of node.children ?? []) files.push(placeFile(leaf, group, inner));
+ for (const leaf of node.leaves()) files.push(placeFile(leaf, group, inner));
+ folders.push(...folderTiles(node, inner));
}
- const base = new Uint32Array(width * height).fill(GROUND);
const drawn: number[] = [];
const index = new Map<string, number>();
+ const lower = new Map<string, number>();
files.forEach((f, i) => {
- if (f.px1 <= f.px0 || f.py1 <= f.py0) return;
- drawn.push(i);
index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);
- paintFile(base, width, f);
+ lower.set(f.path.toLowerCase(), i);
+ if (f.px1 > f.px0 && f.py1 > f.py0) drawn.push(i);
});
- return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base };
+ const dense = drawn.length < files.length * DENSE_SHARE;
+ const base = paintBase({ width, height, groups, folders, files, drawn }, style, dense);
+ return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base, style, dense, lower, folders };
+}
+
+/**
+ * One cell holding a top and a bottom pixel. A ground half is the terminal's
+ * own background: the other half drawn as the glyph (upper or lower half block).
+ */
+export function halfCell(top: number, bottom: number): [number, number, number] {
+ 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];
}
/** True when a mark covers either pixel of any of the label's cells: then the whole label gives way. */
@@ -274,27 +456,41 @@ function labelCovered(label: MapLabel, marked: Uint8Array | undefined, width: nu
return false;
}
+/** The background a label's cell keeps: the tile under it, or the terminal's own. */
+const cellGround = (pixel: number | undefined): number => (pixel === undefined || pixel === GROUND ? TERMINAL_DEFAULT : pixel);
+
+function writeText(words: Uint32Array, layout: MapLayout, label: MapLabel, colors: (col: number) => [number, number]): void {
+ for (let k = 0; k < label.text.length && label.col + k < layout.columns; k++) {
+ const col = label.col + k;
+ words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);
+ }
+}
+
+/** Folder names, faint, on the tile they name; a mark under any of a name's cells hides the whole name. */
+function writeFolderLabels(words: Uint32Array, layout: MapLayout, pixels: Uint32Array, marked: Uint8Array | undefined): void {
+ const fg = layout.style.health ? LABEL_FG : MAP_PALETTES[layout.style.theme].folder;
+ for (const label of layout.labels) {
+ if (labelCovered(label, marked, layout.width)) continue;
+ writeText(words, layout, label, (col) => [fg, cellGround(pixels[2 * label.row * layout.width + col])]);
+ }
+}
+
/**
* Packs pixels into the Raster's `cells`: base64 of little-endian u32 triplets
- * `[codePoint, fg, bg]`, two pixels per cell. Labels sit on cells no mark
- * covers. Uint32Array is little-endian on every platform Claude Code runs on.
+ * `[codePoint, fg, bg]`, two pixels per cell. Folder names sit on cells no
+ * mark covers; the names of lit files are cut out of the tiles onto the
+ * terminal's background. Uint32Array is little-endian on every platform
+ * Claude Code runs on.
*/
-export function encodeCells(layout: MapLayout, pixels: Uint32Array, marked?: Uint8Array): string {
+export function encodeCells(layout: MapLayout, pixels: Uint32Array, marked?: Uint8Array, names: readonly NameLabel[] = []): string {
const { columns, rows, width } = layout;
const words = new Uint32Array(columns * rows * 3);
for (let i = 0; i < columns * rows; i++) {
const r = Math.floor(i / columns);
const c = i % columns;
- words[i * 3] = UPPER_HALF;
- words[i * 3 + 1] = pixels[2 * r * width + c] ?? GROUND;
- words[i * 3 + 2] = pixels[(2 * r + 1) * width + c] ?? GROUND;
- }
- for (const label of layout.labels) {
- if (labelCovered(label, marked, width)) continue;
- for (let k = 0; k < label.text.length && label.col + k < columns; k++) {
- const o = (label.row * columns + label.col + k) * 3;
- words.set([label.text.charCodeAt(k), LABEL_FG, GROUND], o);
- }
+ words.set(halfCell(pixels[2 * r * width + c] ?? GROUND, pixels[(2 * r + 1) * width + c] ?? GROUND), i * 3);
}
+ writeFolderLabels(words, layout, pixels, marked);
+ for (const name of names) writeText(words, layout, name, () => [name.color, TERMINAL_DEFAULT]);
return (new Uint8Array(words.buffer) as Uint8Array & { toBase64(): string }).toBase64();
}
diff --git a/packages/claude-mod/src/views/mapPane.ts b/packages/claude-mod/src/views/mapPane.ts
index 8e3d409bf..689bdec01 100644
--- a/packages/claude-mod/src/views/mapPane.ts
+++ b/packages/claude-mod/src/views/mapPane.ts
@@ -1,29 +1,51 @@
/**
- * The map pane: the Raster and, outside it, the legend (bands with words,
- * Claude's marks, what the trail and the edit reached, and the scope).
+ * The map pane: the Raster, then outside it the story strip (what the turn
+ * searched, opened, edited and reaches; it is the map's legend), the health
+ * legend when health colours are on, the scope, and the health toggle.
+ * The rows under the map are reserved whatever they hold, so the map's height
+ * never moves under a blit.
*/
import { HEALTH_BAND_LABEL, HEALTH_BAND_ORDER } from "@repowise-dev/types/health";
-import { BRAND, DARK_CANVAS, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
+import { DARK_CANVAS, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
import { fit } from "../format";
-import { MAP_COPY, SCOPE_REST, callersLine, indexedPart, readsLine, scopeParts, type ScopeFacts } from "./copy";
-import { box, raster, text, type Node } from "./elements";
-import type { MapLayout } from "./map";
-import { EDIT_TINT, type ResolvedOverlay } from "./overlay";
+import type { Reach, Story } from "../model/story";
+import {
+ MAP_COPY,
+ REACHES_FAILED,
+ SCOPE_REST,
+ STORY_COPY,
+ indexedPart,
+ linesPart,
+ namedByPart,
+ reachesPart,
+ reachesPending,
+ scopeParts,
+ searchedPart,
+ type ScopeFacts,
+} from "./copy";
+import { box, button, raster, text, type Node } from "./elements";
+import { MAP_PALETTES, type MapLayout, type MapStyle } from "./map";
export const MAP_KEY = "lens-map";
+export const HEALTH_KEY = "lens-map-health";
const MAX_COLUMNS = 512;
const MAX_ROWS = 256;
const MIN_ROWS = 4;
const GAP = 2;
const SEP = " · ";
-/** Rows of facts under the swatches: reads, the edit, and the scope over at most two. */
-const FACT_ROWS = 4;
+/** The story strip's four rows, the scope's two, and the toggle's one. */
+const STORY_ROWS = 4;
+const SCOPE_ROWS = 2;
+const TOGGLE_ROWS = 1;
+const HEAD = 10;
+/** Importers named on the REACHES row before `+N`. */
+const REACH_NAMES = 3;
/** An inline pane grows with its tree, so it asks for a height that keeps the map squat. */
const INLINE_ROWS_PER_COLUMN = 1 / 6;
const INLINE_MAX_ROWS = 20;
-interface Swatch {
+export interface Swatch {
glyph: string;
color: string;
label: string;
@@ -35,10 +57,6 @@ const BAND_SWATCHES: readonly Swatch[] = [
...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 },
];
-const READ: Swatch = { glyph: "□", color: BRAND.accent, label: MAP_COPY.read };
-const EDITED: Swatch = { glyph: "◆", color: hexOf(EDIT_TINT), label: MAP_COPY.edited };
-const IMPORTER: Swatch = { glyph: "·", color: BRAND.accent, label: MAP_COPY.importer };
-const MATCH: Swatch = { glyph: "▪", color: BRAND.accent, label: MAP_COPY.match };
/** Greedy rows: items in order, a new row whenever the next would pass `columns`. */
export function packRows<T>(items: readonly T[], width: (item: T) => number, columns: number, gap: number): T[][] {
@@ -58,12 +76,12 @@ export function packRows<T>(items: readonly T[], width: (item: T) => number, col
return rows;
}
-const swatchWidth = (s: Swatch): number => s.label.length + 2;
+export const swatchWidth = (s: Swatch): number => s.label.length + 2;
-/** Legend rows at this width, reserved whatever the marks: the map's height must not move under a blit. */
-export function legendRows(columns: number): number {
- const swatchRows = (items: readonly Swatch[]) => packRows(items, swatchWidth, columns, GAP).length;
- return swatchRows(BAND_SWATCHES) + swatchRows([READ, EDITED, IMPORTER, MATCH]) + FACT_ROWS;
+/** Rows under the map at this width, reserved whatever they hold: the map's height must not move under a blit. */
+export function legendRows(columns: number, health = false): number {
+ const bands = health ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;
+ return STORY_ROWS + bands + SCOPE_ROWS + TOGGLE_ROWS;
}
export interface PaneSize {
@@ -73,16 +91,17 @@ export interface PaneSize {
}
/** The Raster's cell size for a pane: full width, and the height the pane gives (dock) or a squat share (inline). */
-export function mapSize(pane: PaneSize): { columns: number; rows: number } {
+export function mapSize(pane: PaneSize, health = false): { columns: number; rows: number } {
const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));
const wanted =
pane.placement === "dock"
- ? pane.bodyRows - legendRows(columns)
+ ? pane.bodyRows - legendRows(columns, health)
: Math.min(INLINE_MAX_ROWS, Math.round(columns * INLINE_ROWS_PER_COLUMN));
return { columns, rows: Math.max(MIN_ROWS, Math.min(MAX_ROWS, wanted)) };
}
-function swatchRows(items: readonly Swatch[], columns: number): Node[] {
+/** Legend swatches, a glyph in its color and a dim word, packed into rows of `columns`. */
+export function swatchRows(items: readonly Swatch[], columns: number): Node[] {
return packRows(items, swatchWidth, columns, GAP).map((row) =>
box(
{ flexDirection: "row", columnGap: GAP },
@@ -91,13 +110,6 @@ function swatchRows(items: readonly Swatch[], columns: number): Node[] {
);
}
-function marksOf(resolved: ResolvedOverlay): Swatch[] {
- const marks = [READ, EDITED];
- if (resolved.overlay.callers.length > 0) marks.push(IMPORTER);
- if (resolved.overlay.hits.length > 0) marks.push(MATCH);
- return marks;
-}
-
/**
* Scope parts joined with ` · `, wrapped onto at most two rows. When they
* need more, the parts that do not change the reading leave first (the "rest"
@@ -115,26 +127,83 @@ function scopeRows(scope: ScopeFacts, columns: number): string[] {
.map((row) => row.join(SEP));
}
-function factRows(resolved: ResolvedOverlay, scope: ScopeFacts, columns: number): string[] {
- const facts: string[] = [];
- const reads = readsLine(resolved.reads, resolved.matched, columns);
- if (reads !== null) facts.push(reads);
- if (resolved.edit !== null) facts.push(callersLine(resolved.edit.name, resolved.edit.callers, resolved.edit.notDrawn, columns));
- return [...facts, ...scopeRows(scope, columns)];
+/** One piece of a story row, in a color or the terminal's own. */
+interface Seg {
+ text: string;
+ color?: string;
+}
+
+/** A story row: the dim head, then its pieces, cut to fit `columns`. */
+function storyRow(head: string, segs: readonly Seg[], columns: number): Node {
+ let room = Math.max(0, columns - HEAD);
+ const parts: Node[] = [text(head.padEnd(HEAD), { dimColor: true })];
+ for (const s of segs) {
+ if (room <= 0) break;
+ const shown = fit(s.text, room);
+ room -= shown.length;
+ parts.push(text(shown, s.color === undefined ? {} : { color: s.color }));
+ }
+ return box({ flexDirection: "row" }, parts);
+}
+
+function reachSegs(reach: Reach, plum: string): Seg[] {
+ if (reach.callers.status === "loading") return [{ text: reachesPending(reach.edit.slice(reach.edit.lastIndexOf("/") + 1)) }];
+ if (reach.callers.status === "failed") return [{ text: REACHES_FAILED }];
+ const paths = [...reach.callers.paths].sort((a, b) => Number(reach.opened.has(b.toLowerCase())) - Number(reach.opened.has(a.toLowerCase())));
+ const names = paths.slice(0, REACH_NAMES).map((p) => ({ name: p.slice(p.lastIndexOf("/") + 1), opened: reach.opened.has(p.toLowerCase()) }));
+ return [{ text: reachesPart(paths.length, names), color: plum }];
+}
+
+function searchedSegs(story: Story): Seg[] {
+ return story.searched.length === 0 ? [] : [{ text: story.searched.map((s) => searchedPart(s.pattern, s.hits)).join(SEP) }];
+}
+
+/** The opened files, then the first one a Repowise reply named, in plum. */
+function openedSegs(story: Story, plum: string): Seg[] {
+ if (story.opened.length === 0) return [];
+ const named = story.opened.find((o) => o.namedBy !== null);
+ const names = { text: story.opened.map((o) => o.name).join(SEP) };
+ return named === undefined ? [names] : [names, { text: ` ${namedByPart(named.name, named.namedBy as string)}`, color: plum }];
+}
+
+function editedSegs(story: Story, amber: string): Seg[] {
+ return story.edited.map((e, i) => ({ text: `${i === 0 ? "" : SEP}◉ ${e.name}${linesPart(e.lines)}`, color: amber }));
+}
+
+/** The story strip: a row for each of searched, opened, edited and reaches, only once it has something to say. */
+export function storyView(story: Story, reach: Reach | null, style: MapStyle, columns: number): Node[] {
+ const pal = MAP_PALETTES[style.theme];
+ const rows: [string, Seg[]][] = [
+ [STORY_COPY.searched, searchedSegs(story)],
+ [STORY_COPY.opened, openedSegs(story, hexOf(pal.importer))],
+ [STORY_COPY.edited, editedSegs(story, hexOf(pal.edit))],
+ [STORY_COPY.reaches, reach === null ? [] : reachSegs(reach, hexOf(pal.importer))],
+ ];
+ return rows.filter(([, segs]) => segs.length > 0).map(([head, segs]) => storyRow(head, segs, columns));
+}
+
+export interface MapPaneParts {
+ story: Story;
+ reach: Reach | null;
+ scope: ScopeFacts;
}
-export function legendView(resolved: ResolvedOverlay, scope: ScopeFacts, columns: number): Node[] {
+/** Everything under the drawing: the story (or a quiet line), the health legend when on, the scope, and the toggle. */
+export function legendView(parts: MapPaneParts, style: MapStyle, columns: number): Node[] {
+ const story = storyView(parts.story, parts.reach, style, columns);
+ const quiet = story.length === 0 ? [text(fit(MAP_COPY.quiet, columns), { dimColor: true, wrap: "truncate-end" })] : story;
return [
- ...swatchRows(BAND_SWATCHES, columns),
- ...swatchRows(marksOf(resolved), columns),
- ...factRows(resolved, scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),
+ ...quiet,
+ ...(style.health ? swatchRows(BAND_SWATCHES, columns) : []),
+ ...scopeRows(parts.scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),
+ button(HEALTH_KEY, "h", style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff, true),
];
}
-export function mapPaneView(layout: MapLayout, cells: string, resolved: ResolvedOverlay, scope: ScopeFacts): Node {
+export function mapPaneView(layout: MapLayout, cells: string, parts: MapPaneParts): Node {
return box({ key: "lens-map-pane", flexDirection: "column" }, [
raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),
- ...legendView(resolved, scope, layout.columns),
+ ...legendView(parts, layout.style, layout.columns),
]);
}
diff --git a/packages/claude-mod/src/views/mapSvg.ts b/packages/claude-mod/src/views/mapSvg.ts
index 65eb91d9b..f6198c2f8 100644
--- a/packages/claude-mod/src/views/mapSvg.ts
+++ b/packages/claude-mod/src/views/mapSvg.ts
@@ -6,11 +6,11 @@
*/
import { fit } from "../format";
-import { MAP_COPY, mapAlt, type ScopeFacts } from "./copy";
+import { MAP_COPY, mapAlt } from "./copy";
import { box, svg, text, type Node } from "./elements";
-import { GROUND, LABEL_FG, type MapLayout } from "./map";
-import { legendView } from "./mapPane";
-import { framePixels, type ResolvedOverlay } from "./overlay";
+import { GROUND, LABEL_FG, MAP_PALETTES, TERMINAL_DEFAULT, type MapLabel, type MapLayout } from "./map";
+import { legendView, type MapPaneParts } from "./mapPane";
+import { framePixels, type Overlay } from "./overlay";
/** The Svg element's own limit. */
export const SVG_CHARS = 131_072;
@@ -26,10 +26,21 @@ export function desktopSize(size: { columns: number; rows: number }): { columns:
return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };
}
+// A label sits on its cell: one unit across, two down.
+const textAt = (l: MapLabel, fill: number): string => `<text x="${l.col}" y="${2 * l.row + 1.6}" fill="${color(fill)}">${escape(l.text)}</text>`;
+
+/** Folder names, faint (as on the terminal), then the lit files' names; the terminal's own foreground becomes the mist. */
+function svgLabels(layout: MapLayout, overlay: Overlay): string {
+ const pal = MAP_PALETTES[layout.style.theme];
+ const folder = layout.style.health ? LABEL_FG : pal.folder;
+ const names = overlay.names.map((n) => textAt(n, n.color === TERMINAL_DEFAULT ? pal.read : n.color));
+ return [...layout.labels.map((l) => textAt(l, folder)), ...names].join("");
+}
+
/** The resting frame as SVG: per color, one path of horizontal runs (`M x y.5h n`). */
-export function mapSvg(layout: MapLayout, resolved: ResolvedOverlay): string {
+export function mapSvg(layout: MapLayout, overlay: Overlay): string {
const { width, height } = layout;
- const { pixels } = framePixels(layout, resolved.overlay);
+ const { pixels } = framePixels(layout, overlay);
const runs = new Map<number, string[]>();
for (let y = 0; y < height; y++) {
for (let x = 0; x < width; ) {
@@ -45,24 +56,19 @@ export function mapSvg(layout: MapLayout, resolved: ResolvedOverlay): string {
}
}
const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");
- // A label sits on its cell: one unit across, two down.
- const labels = layout.labels
- .map((l) => `<text x="${l.col}" y="${2 * l.row + 1.6}">${escape(l.text)}</text>`)
- .join("");
return (
`<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges">` +
- `<rect width="${width}" height="${height}" fill="${color(GROUND)}"/>` +
`<g stroke-width="1" fill="none">${paths}</g>` +
- `<g font-family="monospace" font-size="1.7" fill="${color(LABEL_FG)}">${labels}</g></svg>`
+ `<g font-family="monospace" font-size="1.7">${svgLabels(layout, overlay)}</g></svg>`
);
}
/** The desktop pane: the drawing and the same legend as the terminal's; a drawing over the limit says so instead. */
-export function svgPaneView(layout: MapLayout, resolved: ResolvedOverlay, scope: ScopeFacts): Node {
- const source = mapSvg(layout, resolved);
+export function svgPaneView(layout: MapLayout, overlay: Overlay, parts: MapPaneParts): Node {
+ 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(resolved, scope, layout.columns)]);
+ return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(parts, layout.style, layout.columns)]);
}
diff --git a/packages/claude-mod/src/views/overlay.ts b/packages/claude-mod/src/views/overlay.ts
index e8c681ed2..480966743 100644
--- a/packages/claude-mod/src/views/overlay.ts
+++ b/packages/claude-mod/src/views/overlay.ts
@@ -1,101 +1,148 @@
/**
- * Claude's marks on the map, as pixel layers over the base: the dotted path
- * joining reads, search matches (a flash that settles to a faint tint), read
- * outlines, the edited file, and the ripple with its importers. Pure.
- *
- * Ceiling: a mark reads as its own shape only on files of at least 3x3 pixels;
- * smaller files show a mark as a solid orange (read) or pale orange (edited) dot.
+ * The turn lit on the map: each file Claude touched fills its whole tile in
+ * the colour of its role, never per-pixel specks. A search's matches glow
+ * faintly, files Repowise named take a deep plum, the edit's importers plum
+ * (rippling out from the edit), opened files mist, and the edit or Claude's
+ * current step amber. A lit file too small for a pixel still lights one full
+ * cell where it sits, so it is never lost. Opened and edited files keep their
+ * names, cut out of the tiles. Pure.
*/
-import { relativeTo } from "../model/events";
-import type { Callers, TrailState } from "../model/trail";
-import { ACCENT, GROUND, encodeCells, mix, type MapLayout, type PlacedFile } from "./map";
+import { cellSafe, fit } from "../format";
+import { MAP_PALETTES, TERMINAL_DEFAULT, encodeCells, mix, type MapLayout, type MapPalette, type NameLabel, type PlacedFile } from "./map";
-/** What the trail and the ripple mark, as indices into `layout.files`. */
-export interface Overlay {
- reads: number[];
- hits: number[];
- edited: number | null;
- callers: number[];
+/** What the turn lit, as repo-relative paths. */
+export interface Lit {
+ hits: readonly string[];
+ reads: readonly string[];
+ named: readonly string[];
+ importers: readonly string[];
+ /** Every file the turn edited, oldest first; `edit` is the latest. */
+ edits: readonly string[];
+ edit: string | null;
+ /** Claude's latest read or edit. */
+ current: string | null;
}
-/** The overlay plus the counts the legend states beside it. */
-export interface ResolvedOverlay {
- overlay: Overlay;
- reads: { count: number; capped: boolean; notDrawn: number };
- /** Files the latest search matched, drawn or not; null before any search. */
- matched: number | null;
- /** null while no edit has been seen. */
- edit: { name: string; callers: Callers | null; notDrawn: number } | null;
+export const NO_LIT: Lit = { hits: [], reads: [], named: [], importers: [], edits: [], edit: null, current: null };
+
+/** The lit files as indices into `layout.files`, and the names written beside them. */
+export interface Overlay {
+ hits: number[];
+ reads: number[];
+ named: number[];
+ importers: number[];
+ edit: number | null;
+ current: number | null;
+ names: NameLabel[];
}
/** One step of an animation, `t` from 0 to 1; t = 1 is the resting frame. */
export type Anim = { kind: "flash"; t: number } | { kind: "ripple"; t: number };
-export const EDIT_TINT = mix(ACCENT, 0xffffff, 0.45);
-const READ_DIM = 0.4;
-const PATH_AMOUNT = 0.85;
-const MATCH_FLASH = 0.85;
-const MATCH_REST = 0.25;
-const RING_AMOUNT = 0.5;
-const SMALL = 3;
-
-/** A drawn file for a repo-relative path. */
-function lookup(layout: MapLayout, rel: string): number | undefined {
- return layout.index.get(layout.caseInsensitive ? rel.toLowerCase() : rel);
-}
-
-/** A drawn file for an absolute path under `root`. */
-function locate(layout: MapLayout, abs: string, root: string): number | undefined {
- const rel = relativeTo(abs, root, layout.caseInsensitive);
- return rel === null ? undefined : lookup(layout, rel);
-}
-
-function split<T>(items: readonly T[], find: (item: T) => number | undefined): { found: number[]; missing: number } {
- const found: number[] = [];
- for (const item of items) {
- const i = find(item);
- if (i !== undefined) found.push(i);
+/** Animation lengths; frames go out every `FRAME_MS`, under the surface's 30 per second. */
+export const FRAME_MS = 40;
+export const FLASH_MS = 600;
+export const RIPPLE_MS = 1_200;
+const NAME_MAX = 18;
+/** How bright a fresh search's glow starts, toward the opened-file mist. */
+const FLASH_LIFT = 0.6;
+
+/** A path's key in `layout.index`: lowercased where paths are case-insensitive. */
+const keyOf = (layout: MapLayout, path: string): string => (layout.caseInsensitive ? path.toLowerCase() : path);
+
+function indices(layout: MapLayout, paths: readonly string[], lowered = false): number[] {
+ const out: number[] = [];
+ for (const p of paths) {
+ const i = lowered ? layout.lower.get(p) : layout.index.get(keyOf(layout, p));
+ if (i !== undefined) out.push(i);
}
- return { found, missing: items.length - found.length };
-}
-
-/**
- * Maps the trail's absolute paths onto drawn files under `repoRoot`. A path
- * outside the repo, outside the feed, or too small to draw is "not drawn".
- */
-export function resolveOverlay(layout: MapLayout, trail: TrailState, repoRoot: string): ResolvedOverlay {
- const reads = split(trail.reads, (p) => locate(layout, p, repoRoot));
- const hits = split(trail.hits, (p) => locate(layout, p, repoRoot)).found;
- const callers = split(trail.callers?.status === "ready" ? trail.callers.paths : [], (p) => lookup(layout, p));
- const edited = trail.edit === null ? null : (locate(layout, trail.edit, repoRoot) ?? null);
- const edit =
- trail.edit === null
- ? null
- : { name: trail.edit.slice(trail.edit.lastIndexOf("/") + 1), callers: trail.callers, notDrawn: callers.missing };
- return {
- overlay: { reads: reads.found, hits, edited, callers: callers.found },
- reads: { count: trail.reads.length, capped: trail.readsCapped, notDrawn: reads.missing },
- matched: trail.searches === 0 ? null : trail.hits.length,
- edit,
+ return out;
+}
+
+const one = (layout: MapLayout, path: string | null): number | null => (path === null ? null : (layout.index.get(keyOf(layout, path)) ?? null));
+
+/** Lit paths outside the drawn feed (beyond its cap, or not indexed). */
+export function notOnMap(layout: MapLayout, lit: Lit): number {
+ const all = new Set([...lit.hits, ...lit.reads, ...lit.importers, ...(lit.edit === null ? [] : [lit.edit])].map((p) => keyOf(layout, p)));
+ return [...all].filter((p) => !layout.index.has(p)).length;
+}
+
+/** The pixels a file lights: its own, or the one cell (two pixels) at its centre when it has none. */
+export function litPixels(layout: MapLayout, f: PlacedFile): { x0: number; y0: number; x1: number; y1: number } {
+ 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 row = Math.min(layout.rows - 1, Math.max(0, Math.floor((f.rect.y + f.rect.h / 2) / 2)));
+ return { x0: x, y0: row * 2, x1: x + 1, y1: row * 2 + 2 };
+}
+
+/** Rows a name may sit on, nearest first. */
+const ROW_TRIES = [0, 1, -1, 2, -2];
+
+const rowIn = (layout: MapLayout, row: number): boolean => row >= 0 && row < layout.rows;
+const spanIn = (layout: MapLayout, col: number, len: number): boolean => col >= 0 && col + len <= layout.columns;
+const inside = (layout: MapLayout, row: number, col: number, len: number): boolean => rowIn(layout, row) && spanIn(layout, col, len);
+
+/** Whether `len` cells from `col` on `row` are inside the map and a cell clear of other names. */
+function freeSpan(taken: ReadonlySet<number>, layout: MapLayout, at: { row: number; col: number }, len: number): boolean {
+ 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;
+}
+
+/** A name beside its tile, right of it or else left, on the nearest free row; null when there is no room. */
+function placeName(layout: MapLayout, taken: Set<number>, f: PlacedFile, color: number): NameLabel | null {
+ const text = fit(cellSafe(f.path.slice(f.path.lastIndexOf("/") + 1)), NAME_MAX);
+ const box = litPixels(layout, f);
+ const mid = Math.floor((box.y0 + box.y1 - 1) / 4);
+ const tries = ROW_TRIES.flatMap((dr) => [box.x1 + 1, box.x0 - text.length - 1].map((col) => ({ row: mid + dr, col })));
+ const at = tries.find((t) => freeSpan(taken, layout, t, text.length));
+ if (at === undefined) return null;
+ for (let c = at.col; c < at.col + text.length; c++) taken.add(at.row * layout.columns + c);
+ return { ...at, text, color };
+}
+
+/** Names for the edit and the current step (amber) first, then the opened files, newest first. */
+function namesFor(layout: MapLayout, o: Omit<Overlay, "names">): NameLabel[] {
+ const pal = MAP_PALETTES[layout.style.theme];
+ const order = [...new Set([o.edit, o.current, ...[...o.reads].reverse()].filter((i): i is number => i !== null))];
+ const taken = new Set<number>();
+ const hot = new Set([o.edit, o.current]);
+ return order
+ .map((i) => placeName(layout, taken, layout.files[i] as PlacedFile, hot.has(i) ? pal.edit : TERMINAL_DEFAULT))
+ .filter((n): n is NameLabel => n !== null);
+}
+
+/** The lit files on this layout, with their names placed. */
+export function resolveLit(layout: MapLayout, lit: Lit): Overlay {
+ const o = {
+ hits: indices(layout, lit.hits),
+ reads: indices(layout, lit.reads),
+ // Flow keeps the files a reply named lowercased.
+ named: indices(layout, lit.named, true),
+ importers: indices(layout, lit.importers),
+ edit: one(layout, lit.edit),
+ current: one(layout, lit.current),
};
+ return { ...o, names: namesFor(layout, o) };
}
-function center(f: PlacedFile): [number, number] {
- return [Math.floor((f.px0 + f.px1 - 1) / 2), Math.floor((f.py0 + f.py1 - 1) / 2)];
+function center(layout: MapLayout, f: PlacedFile): [number, number] {
+ const b = litPixels(layout, f);
+ return [Math.floor((b.x0 + b.x1 - 1) / 2), Math.floor((b.y0 + b.y1 - 1) / 2)];
}
-function distance(a: PlacedFile, b: PlacedFile): number {
- const [ax, ay] = center(a);
- const [bx, by] = center(b);
+function distance(layout: MapLayout, a: PlacedFile, b: PlacedFile): number {
+ const [ax, ay] = center(layout, a);
+ const [bx, by] = center(layout, b);
return Math.hypot(ax - bx, ay - by);
}
/** How far the ripple travels: just past its farthest importer; 0 when there is nothing to ripple to. */
export function rippleRadius(layout: MapLayout, overlay: Overlay): number {
- const origin = overlay.edited === null ? undefined : layout.files[overlay.edited];
- if (!origin || overlay.callers.length === 0) return 0;
- return Math.max(...overlay.callers.map((i) => distance(origin, layout.files[i] as PlacedFile))) + 3;
+ const origin = overlay.edit === null ? undefined : 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] as PlacedFile))) + 3;
}
interface Paint {
@@ -104,120 +151,63 @@ interface Paint {
marked: Uint8Array;
}
-function inside(layout: MapLayout, x: number, y: number): boolean {
- return x >= 0 && y >= 0 && x < layout.width && y < layout.height;
-}
-
-function set(p: Paint, x: number, y: number, color: number): void {
- if (!inside(p.layout, x, y)) return;
- const width = p.layout.width;
- p.px[y * width + x] = color;
- p.marked[y * width + x] = 1;
-}
-
-function fillFile(p: Paint, f: PlacedFile, color: (current: number) => number): void {
- const w = p.layout.width;
- for (let y = f.py0; y < f.py1; y++) for (let x = f.px0; x < f.px1; x++) set(p, x, y, color(p.px[y * w + x] ?? GROUND));
-}
-
-function outlineFile(p: Paint, f: PlacedFile, color: number): void {
- for (let x = f.px0; x < f.px1; x++) {
- set(p, x, f.py0, color);
- set(p, x, f.py1 - 1, color);
- }
- for (let y = f.py0; y < f.py1; y++) {
- set(p, f.px0, y, color);
- set(p, f.px1 - 1, y, color);
+function fillFile(p: Paint, f: PlacedFile, color: number): void {
+ const { width } = p.layout;
+ const b = litPixels(p.layout, f);
+ for (let y = b.y0; y < b.y1; y++) {
+ p.px.fill(color, y * width + b.x0, y * width + b.x1);
+ p.marked.fill(1, y * width + b.x0, y * width + b.x1);
}
}
-const isSmall = (f: PlacedFile): boolean => f.px1 - f.px0 < SMALL || f.py1 - f.py0 < SMALL;
-
-/** Every third pixel along the straight line between two consecutive reads. */
-function paintPath(p: Paint, overlay: Overlay): void {
- const files = p.layout.files;
- for (let k = 1; k < overlay.reads.length; k++) {
- const [ax, ay] = center(files[overlay.reads[k - 1] as number] as PlacedFile);
- const [bx, by] = center(files[overlay.reads[k] as number] as PlacedFile);
- const steps = Math.max(Math.abs(bx - ax), Math.abs(by - ay));
- for (let s = 1; s < steps; s += 3) {
- const x = Math.round(ax + ((bx - ax) * s) / steps);
- const y = Math.round(ay + ((by - ay) * s) / steps);
- set(p, x, y, mix(p.px[y * p.layout.width + x] ?? GROUND, ACCENT, PATH_AMOUNT));
- }
- }
+function fillAll(p: Paint, files: readonly number[], color: number): void {
+ for (const i of files) fillFile(p, p.layout.files[i] as PlacedFile, color);
}
-function paintHits(p: Paint, overlay: Overlay, amount: number): void {
- for (const i of overlay.hits) fillFile(p, p.layout.files[i] as PlacedFile, (c) => mix(c, ACCENT, amount));
-}
-
-/** A read: its interior dimmed so the orange outline holds against warm bands. */
-function paintReads(p: Paint, overlay: Overlay): void {
- for (const i of overlay.reads) {
- const f = p.layout.files[i] as PlacedFile;
- fillFile(p, f, (c) => mix(c, 0x000000, READ_DIM));
- outlineFile(p, f, ACCENT);
- }
-}
-
-/** The edited file: pale orange inside an orange outline (a small one is all pale, unlike a small read). */
-function paintEdited(p: Paint, f: PlacedFile): void {
- fillFile(p, f, () => EDIT_TINT);
- if (!isSmall(f)) outlineFile(p, f, ACCENT);
-}
-
-function paintRing(p: Paint, origin: PlacedFile, reach: number): void {
- const [ox, oy] = center(origin);
+/** The ripple's ring while it travels, in the importers' plum. */
+function paintRing(p: Paint, origin: PlacedFile, reach: number, color: number): void {
+ const [ox, oy] = center(p.layout, origin);
const { width, height } = p.layout;
for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {
for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width - 1, ox + reach); x++) {
const d = Math.hypot(x - ox, y - oy);
- if (d <= reach && d > reach - 2) set(p, x, y, mix(p.px[y * width + x] ?? GROUND, ACCENT, RING_AMOUNT));
+ if (d <= reach && d > reach - 2) p.px[y * width + x] = mix(p.px[y * width + x] as number, color, 0.5);
}
}
}
-/** An importer: an orange pixel with a dark one beside it in the same cell, so it holds on any band. */
-function paintCallers(p: Paint, overlay: Overlay, origin: PlacedFile | undefined, reach: number): void {
- for (const i of overlay.callers) {
- const f = p.layout.files[i] as PlacedFile;
- if (origin !== undefined && distance(origin, f) > reach) continue;
- const [x, y] = center(f);
- set(p, x, y, ACCENT);
- set(p, x, y ^ 1, GROUND);
- }
+function hitColor(pal: MapPalette, anim: Anim | undefined): number {
+ return anim?.kind === "flash" ? mix(pal.hit, pal.read, FLASH_LIFT * (1 - anim.t)) : pal.hit;
}
-function matchAmount(anim: Anim | undefined): number {
- return anim?.kind === "flash" ? MATCH_REST + (MATCH_FLASH - MATCH_REST) * (1 - anim.t) : MATCH_REST;
+/** Importers the ripple has reached; all of them at rest. */
+function reached(layout: MapLayout, overlay: Overlay, reach: number): number[] {
+ const origin = overlay.edit === null ? undefined : layout.files[overlay.edit];
+ if (origin === undefined || reach === Infinity) return overlay.importers;
+ return overlay.importers.filter((i) => distance(layout, origin, layout.files[i] as PlacedFile) <= reach);
}
function rippleReach(layout: MapLayout, overlay: Overlay, anim: Anim | undefined): number {
return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;
}
-/** Map pixels for one frame: the base map with the trail, the edit and the ripple painted on. */
+/** Map pixels for one frame: the base with the turn's roles filled in, weakest first so the strongest shows. */
export function framePixels(layout: MapLayout, overlay: Overlay, anim?: Anim): { pixels: Uint32Array; marked: Uint8Array } {
const p: Paint = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };
- const origin = overlay.edited === null ? undefined : layout.files[overlay.edited];
+ const pal = MAP_PALETTES[layout.style.theme];
const reach = rippleReach(layout, overlay, anim);
- paintPath(p, overlay);
- paintHits(p, overlay, matchAmount(anim));
- paintReads(p, overlay);
- if (origin !== undefined) paintEdited(p, origin);
- if (origin !== undefined && reach < Infinity) paintRing(p, origin, reach);
- paintCallers(p, overlay, origin, reach);
+ fillAll(p, overlay.hits, hitColor(pal, anim));
+ fillAll(p, overlay.named, pal.named);
+ fillAll(p, reached(layout, overlay, reach), pal.importer);
+ fillAll(p, overlay.reads, pal.read);
+ fillAll(p, [overlay.edit, overlay.current].filter((i): i is number => i !== null), pal.edit);
+ const origin = overlay.edit === null ? undefined : layout.files[overlay.edit];
+ if (origin !== undefined && reach < Infinity) paintRing(p, origin, reach, pal.importer);
return { pixels: p.px, marked: p.marked };
}
/** One frame's cells: the resting frame without `anim`. */
export function frameCells(layout: MapLayout, overlay: Overlay, anim?: Anim): string {
const { pixels, marked } = framePixels(layout, overlay, anim);
- return encodeCells(layout, pixels, marked);
+ return encodeCells(layout, pixels, marked, overlay.names);
}
-
-/** Animation lengths; frames go out every `FRAME_MS`, under the surface's 30 per second. */
-export const FRAME_MS = 40;
-export const FLASH_MS = 600;
-export const RIPPLE_MS = 1_200;
diff --git a/packages/claude-mod/src/views/owl.ts b/packages/claude-mod/src/views/owl.ts
new file mode 100644
index 000000000..79de33418
--- /dev/null
+++ b/packages/claude-mod/src/views/owl.ts
@@ -0,0 +1,48 @@
+/**
+ * The Repowise owl on one line, after the CLI mascot's mini form `{◉ ◉}`
+ * (packages/cli/src/repowise/cli/ui/mascot.py): `{◉,◉}`. It says what is
+ * happening through its eyes alone, calmly. The strokes take the terminal's
+ * own foreground; open eyes are amber. Every glyph is one cell wide (none is
+ * East Asian wide; `─`, `◐` and `•` are ambiguous width, one cell outside
+ * CJK locales, as the CLI's own owl already assumes).
+ */
+
+import { text, type Node } from "./elements";
+
+export const EYES = { open: "◉", shut: "─", side: "◐", happy: "^", still: "•" } as const;
+
+/** A slow blink: open for nine frames, shut for one. */
+const BLINK: readonly string[] = [...Array<string>(9).fill(EYES.open), EYES.shut];
+export const BLINK_MS = 250;
+
+/**
+ * Asleep at rest, watching (a slow blink) while Claude works, looking aside
+ * while a Repowise call is in flight, happy for a moment after an answer,
+ * neutral after a turn that stopped or did not finish.
+ */
+export type OwlState = "asleep" | "watching" | "asking" | "happy" | "stopped";
+
+const EYES_OF: Record<Exclude<OwlState, "watching">, string> = {
+ asleep: EYES.shut,
+ asking: EYES.side,
+ happy: EYES.happy,
+ stopped: EYES.still,
+};
+
+/** The eyes for a state at `now`; `still` (reduced motion) holds them open. */
+export function owlEyes(state: OwlState, now: number, still: boolean): string {
+ if (state !== "watching") return EYES_OF[state];
+ return still ? EYES.open : (BLINK[Math.floor(now / BLINK_MS) % BLINK.length] as string);
+}
+
+export const OWL_WIDTH = 5;
+
+/**
+ * `{◉,◉}`: strokes in the terminal's foreground, eyes in `amber` while open.
+ * Asleep, the whole owl is dim.
+ */
+export function owl(state: OwlState, eyes: string, amber: string): Node[] {
+ if (state === "asleep") return [text(`{${eyes},${eyes}}`, { dimColor: true })];
+ const eye = (): Node => (eyes === EYES.shut || eyes === EYES.still ? text(eyes) : text(eyes, { color: amber }));
+ return [text("{"), eye(), text(","), eye(), text("}")];
+}
diff --git a/packages/claude-mod/src/views/pane.ts b/packages/claude-mod/src/views/pane.ts
index 3a430cde4..495a145f5 100644
--- a/packages/claude-mod/src/views/pane.ts
+++ b/packages/claude-mod/src/views/pane.ts
@@ -1,11 +1,11 @@
/**
- * The `/lens` pane around the map: a row of tabs (Map, Ask, Recap), the Ask
- * field with the last reply, and the session recap. Every recap figure is
+ * The `/lens` pane: a row of tabs (Flow, Map, Ask, Recap), the Ask field (its own tab,
+ * bar) with the last reply, and the session recap. Every recap figure is
* read from the session model as it stands; nothing is re-derived.
*/
import { fit } from "../format";
-import type { PaneTab } from "../model/ask";
+import { TAB_BAR, type BarTab, type PaneTab } from "../model/ask";
import { testsToRun, type ChangeRisk } from "../model/review";
import { surfacedDecisions, type SessionState } from "../model/session";
import { replyMarkdown } from "./answer";
@@ -25,18 +25,21 @@ import {
import { box, button, input, markdown, text, type Node } from "./elements";
import { health, overlap } from "./review";
-export const TABS: readonly PaneTab[] = ["map", "ask", "recap"];
-/** Button keys of the tabs; register.ts maps each to its tab. */
-export const TAB_PRESS: Record<PaneTab, string> = { map: "lens-tab-map", ask: "lens-tab-ask", recap: "lens-tab-recap" };
+/** The tab bar as shown: Flow leaves it when its toggle is off. */
+export function tabBar(flowOn: boolean): readonly BarTab[] {
+ return flowOn ? TAB_BAR : TAB_BAR.filter((t) => t !== "flow");
+}
+/** A tab's Button key; register.ts maps each to its tab. */
+export const tabPress = (tab: BarTab): string => `lens-tab-${tab}`;
export const ASK_KEY = "lens-ask";
/** Rows the tab row takes above each tab's body. */
export const TAB_ROWS = 1;
-/** `1: Map 2: Ask 3: Recap`, the shown one at full strength. */
-export function tabsView(current: PaneTab): Node {
+/** `1: Flow 2: Map 3: Ask 4: Recap`, the shown one at full strength. */
+export function tabsView(current: PaneTab, tabs: readonly BarTab[] = TAB_BAR): Node {
return box(
{ key: "lens-tabs", flexDirection: "row", columnGap: 2 },
- TABS.map((tab, i) => button(TAB_PRESS[tab], String(i + 1), PANE_COPY.tabs[tab], tab !== current)),
+ tabs.map((tab, i) => button(tabPress(tab), String(i + 1), PANE_COPY.tabs[tab], tab !== current)),
);
}
@@ -139,6 +142,6 @@ export function recapView(state: SessionState, touched: TrailCounts, columns: nu
}
/** The pane: the tabs, then the shown tab's body. */
-export function paneView(tab: PaneTab, body: Node): Node {
- return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab), body]);
+export function paneView(tab: PaneTab, body: Node, tabs: readonly BarTab[] = TAB_BAR): Node {
+ return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab, tabs), body]);
}
diff --git a/packages/claude-mod/src/views/theme.ts b/packages/claude-mod/src/views/theme.ts
new file mode 100644
index 000000000..85aec5ee8
--- /dev/null
+++ b/packages/claude-mod/src/views/theme.ts
@@ -0,0 +1,53 @@
+/**
+ * Flow's two accents, from the brand tokens, and its motifs. Terminals run
+ * their own colors (mostly dark, some light), so readable text keeps the
+ * terminal's foreground or its dim, never a fixed color, and nothing sets a
+ * background. The accents are marks only: plum for decoration and Repowise's
+ * marks, amber for Claude's attention, each from the ramp of the terminal's
+ * theme (dark unless the session says light). Health colors never appear here.
+ * The motifs are fixed shapes that carry no data.
+ */
+
+import { BRAND, DARK, LIGHT } from "@repowise-dev/ui/brand";
+
+export interface FlowTheme {
+ /** Heather plum: the hills, Repowise's marks, the thistle. */
+ plum: string;
+ /** Claude's attention: the call in flight, the owl's eyes. */
+ amber: string;
+}
+
+const DARK_THEME: FlowTheme = { plum: DARK.accentSecondary, amber: BRAND.accent };
+/** On a light ground the deeper plum, and the amber darkened for contrast. */
+const LIGHT_THEME: FlowTheme = { plum: LIGHT.accentSecondary, amber: BRAND.accentTextLight };
+
+export function flowTheme(light: boolean): FlowTheme {
+ return light ? LIGHT_THEME : DARK_THEME;
+}
+
+/** Claude Code's `theme` setting, as the two ramps Lens draws with: light for any light theme, else dark. */
+export type ThemeName = "dark" | "light";
+
+export function themeOf(value: unknown): ThemeName {
+ return typeof value === "string" && value.startsWith("light") ? "light" : "dark";
+}
+
+/** One period of the hills along the pane's top. */
+const HILLS = "▁▂▃▅▃▂▁▁▂▃▂▁▁▁▂▃▄▃▂▁";
+/** The hills mirrored in the water: lower shapes read as a flat shore, higher as reflections. */
+const MIRROR: Record<string, string> = { "▁": " ", "▂": "▔", "▃": "▔", "▄": "▀", "▅": "▀" };
+
+export const THISTLE = "⚘";
+
+function repeat(pattern: string, columns: number): string {
+ return pattern.repeat(Math.ceil(Math.max(0, columns) / pattern.length)).slice(0, Math.max(0, columns));
+}
+
+export function hills(columns: number): string {
+ return repeat(HILLS, columns);
+}
+
+/** The hills reflected, under a finished turn. */
+export function loch(columns: number): string {
+ return [...hills(columns)].map((c) => MIRROR[c] ?? " ").join("");
+}
diff --git a/packages/claude-mod/test/animator.test.ts b/packages/claude-mod/test/animator.test.ts
new file mode 100644
index 000000000..0696607fd
--- /dev/null
+++ b/packages/claude-mod/test/animator.test.ts
@@ -0,0 +1,42 @@
+// The pane's one animator: frames go through the closures of the latest hook
+// (never a `$` kept from the hook that started it), and a frame that throws
+// stops the animation without leaving the timer.
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { Animator, type AnimIO } from "../src/animator";
+
+function io(name: string, seen: string[]): AnimIO {
+ return {
+ redraw: () => seen.push(`${name}:redraw`),
+ debug: (m) => seen.push(`${name}:debug:${m}`),
+ blit: async (key) => {
+ seen.push(`${name}:blit:${key}`);
+ return {};
+ },
+ };
+}
+
+beforeEach(() => vi.useFakeTimers());
+afterEach(() => vi.useRealTimers());
+
+describe("Animator", () => {
+ it("blits through the closures of the latest hook", async () => {
+ const seen: string[] = [];
+ const a = new Animator();
+ a.play(io("first", seen), "rays", 1_000, () => ({ key: "k", cells: "", columns: 1, rows: 1 }));
+ a.use(io("later", seen));
+ await vi.advanceTimersByTimeAsync(45);
+ expect(seen).toEqual(["first:redraw", "later:blit:k"]);
+ a.end();
+ });
+
+ it("a frame that throws stops the animation and is logged, not thrown from the timer", async () => {
+ const seen: string[] = [];
+ const a = new Animator();
+ a.play(io("hook", seen), "rays", 1_000, () => {
+ throw new Error("bad frame");
+ }, false);
+ await vi.advanceTimersByTimeAsync(100);
+ expect(seen).toEqual(["hook:debug:animation failed: Error: bad frame"]);
+ expect(a.progress(Date.now())).toBeUndefined();
+ });
+});
diff --git a/packages/claude-mod/test/fixtures/flow/blast_query.json b/packages/claude-mod/test/fixtures/flow/blast_query.json
new file mode 100644
index 000000000..e14f1ac79
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/blast_query.json
@@ -0,0 +1 @@
+{"direct_risks":[{"path":"django/db/models/query.py","structural_score":0.0084,"risk_score":0.0084,"temporal_hotspot":3.3175,"churn_percentile":0.9964,"is_hotspot":true,"centrality":0.001948}],"transitive_affected":[{"path":"django/contrib/contenttypes/fields.py","depth":1},{"path":"django/contrib/contenttypes/prefetch.py","depth":1},{"path":"django/db/models/__init__.py","depth":1},{"path":"django/db/models/base.py","depth":1},{"path":"django/db/models/fields/related_descriptors.py","depth":1},{"path":"django/db/models/manager.py","depth":1},{"path":"django/db/models/sql/query.py","depth":1},{"path":"tests/basic/tests.py","depth":1},{"path":"tests/model_forms/tests.py","depth":1},{"path":"tests/prefetch_related/models.py","depth":1},{"path":"tests/prefetch_related/tests.py","depth":1},{"path":"tests/raw_query/tests.py","depth":1}],"cochange_warnings":[{"changed":"django/db/models/query.py","missing_partner":"tests/queries/tests.py","score":0.8024},{"changed":"django/db/models/query.py","missing_partner":"django/db/models/sql/query.py","score":0.5127},{"changed":"django/db/models/query.py","missing_partner":"django/db/models/sql/compiler.py","score":0.4635},{"changed":"django/db/models/query.py","missing_partner":"docs/internals/deprecation.txt","score":0.4385},{"changed":"django/db/models/query.py","missing_partner":"tests/queries/test_qs_combinators.py","score":0.4262},{"changed":"django/db/models/query.py","missing_partner":"tests/defer/tests.py","score":0.416},{"changed":"django/db/models/query.py","missing_partner":"tests/bulk_create/tests.py","score":0.4085},{"changed":"django/db/models/query.py","missing_partner":"docs/releases/6.2.txt","score":0.3588},{"changed":"django/db/models/query.py","missing_partner":"django/contrib/contenttypes/fields.py","score":0.3245},{"changed":"django/db/models/query.py","missing_partner":"tests/composite_pk/tests.py","score":0.3153},{"changed":"django/db/models/query.py","missing_partner":"docs/ref/models/querysets.txt","score":0.2858},{"changed":"django/db/models/query.py","missing_partner":"django/db/models/fields/related_descriptors.py","score":0.2763},{"changed":"django/db/models/query.py","missing_partner":"docs/releases/6.1.txt","score":0.2399},{"changed":"django/db/models/query.py","missing_partner":"tests/basic/tests.py","score":0.2222},{"changed":"django/db/models/query.py","missing_partner":"tests/lookup/tests.py","score":0.2119},{"changed":"django/db/models/query.py","missing_partner":"django/db/models/query_utils.py","score":0.1919},{"changed":"django/db/models/query.py","missing_partner":"django/db/models/expressions.py","score":0.1883},{"changed":"django/db/models/query.py","missing_partner":"AUTHORS","score":0.1709},{"changed":"django/db/models/query.py","missing_partner":"docs/releases/6.0.txt","score":0.1242},{"changed":"django/db/models/query.py","missing_partner":"docs/releases/5.2.2.txt","score":0.1138},{"changed":"django/db/models/query.py","missing_partner":"tests/composite_pk/test_aggregate.py","score":0.1039},{"changed":"django/db/models/query.py","missing_partner":"tests/model_inheritance_regress/tests.py","score":0.0789},{"changed":"django/db/models/query.py","missing_partner":"tests/select_related/tests.py","score":0.0789},{"changed":"django/db/models/query.py","missing_partner":"docs/releases/5.2.1.txt","score":0.0722},{"changed":"django/db/models/query.py","missing_partner":"tests/update/tests.py","score":0.0705}],"recommended_reviewers":[{"email":"[email protected]","files":4,"ownership_pct":0.012},{"email":"[email protected]","files":2,"ownership_pct":0.053},{"email":"[email protected]","files":1,"ownership_pct":0.5},{"email":"[email protected]","files":1,"ownership_pct":0.18},{"email":"[email protected]","files":1,"ownership_pct":0.161}],"test_gaps":[],"test_impact":{"recommendations":[{"test_id":"tests/async/test_async_queryset.py","test_file":"tests/async/test_async_queryset.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/basic/tests.py","test_file":"tests/basic/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/contenttypes_tests/test_fields.py","test_file":"tests/contenttypes_tests/test_fields.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/contenttypes_tests/test_models.py","test_file":"tests/contenttypes_tests/test_models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/custom_managers/models.py","test_file":"tests/custom_managers/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/generic_relations/tests.py","test_file":"tests/generic_relations/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/generic_views/models.py","test_file":"tests/generic_views/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/get_earliest_or_latest/models.py","test_file":"tests/get_earliest_or_latest/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/migrations/models.py","test_file":"tests/migrations/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/model_forms/tests.py","test_file":"tests/model_forms/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/prefetch_related/models.py","test_file":"tests/prefetch_related/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/prefetch_related/test_prefetch_related_objects.py","test_file":"tests/prefetch_related/test_prefetch_related_objects.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/prefetch_related/tests.py","test_file":"tests/prefetch_related/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/queries/test_query.py","test_file":"tests/queries/test_query.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/queryset_pickle/models.py","test_file":"tests/queryset_pickle/models.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/raw_query/tests.py","test_file":"tests/raw_query/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]},{"test_id":"tests/serializers/tests.py","test_file":"tests/serializers/tests.py","repository_id":"9a58b951a10a437d93ce0beebd4dc50e","repository":"9a58b951a10a437d93ce0beebd4dc50e","basis":"inferred","bases":["inferred"],"source_files":["django/db/models/query.py"],"evidence":[{"basis":"inferred","source_file":"django/db/models/query.py","via":"call-graph","source_format":null}]}],"recommendations_total":17,"recommendations_emitted":17,"recommendations_truncated":false,"recommendations_omitted":0,"recommendations_by_primary_basis":{"measured":0,"inferred":17},"files":[{"source_file":"django/db/models/query.py","status":"inferred","change_status":null,"head_present":true,"measured_tests":[],"measured_tests_total":0,"inferred_tests":["tests/async/test_async_queryset.py","tests/basic/tests.py","tests/contenttypes_tests/test_fields.py","tests/contenttypes_tests/test_models.py","tests/custom_managers/models.py","tests/generic_relations/tests.py","tests/generic_views/models.py","tests/get_earliest_or_latest/models.py","tests/migrations/models.py","tests/model_forms/tests.py","tests/prefetch_related/models.py","tests/prefetch_related/test_prefetch_related_objects.py","tests/prefetch_related/tests.py","tests/queries/test_query.py","tests/queryset_pickle/models.py","tests/raw_query/tests.py","tests/serializers/tests.py"],"inferred_tests_total":17}],"files_total":1,"files_without_measured_tests":["django/db/models/query.py"],"unknown_files":[],"deleted_files":[],"coverage":{"status":"unavailable","reason":"no_per_test_coverage_map","map_present":false,"pair_count":0,"test_count":0,"source_file_count":0,"changed_files_total":1,"changed_files_with_measured_tests":0,"changed_files_without_measured_tests":1,"ingested_at":null,"source_format":null,"freshness":{"status":"unknown","reason":"coverage_or_index_commit_unavailable","ingested_commit":null,"indexed_commit":"e78991410b78391bc07a4b5010b273dfec814ff6"}},"inference":{"status":"available","reason":null,"changed_files_total":1,"changed_files_with_candidates":1,"candidates_before_dedup":17},"analysis":{"status":"partial","stale":false,"partial":true,"degraded":false,"basis_categories":["inferred"]}},"structural_impact_score":1.84,"structural_impact_band":"localized","structural_impact_scale":{"field":"structural_impact_score","kind":"heuristic_structural_score","unit":"normalized_points","range":{"minimum":0.0,"maximum":10.0},"measures":"indexed structural exposure: centrality of the changed files plus bounded direct and transitive dependent breadth","deterministic":true,"calibration":{"status":"uncalibrated","source":null,"calibrated_at":null,"population":null,"granularity":null},"authoritative":null,"authoritative_for_change_review":false,"runtime_breakage_probability":false,"formula":null,"thresholds":null,"band_thresholds":{"moderate":4.0,"broad":7.0},"component_fields":null},"overall_risk_score":1.84,"overall_risk_score_compatibility":{"deprecated":true,"replacement":"structural_impact_score","equivalent_value":true,"historical_meaning":"uncalibrated 0-10 structural blast-radius heuristic"}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_answer.json b/packages/claude-mod/test/fixtures/flow/get_answer.json
new file mode 100644
index 000000000..b6bfe29fa
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_answer.json
@@ -0,0 +1 @@
+{"result":{"answer":"Synthesis is unavailable (no-llm-provider), but symbol_bodies contains live source for the named code. Use that evidence directly.","citations":["django/db/models/query.py"],"confidence":"medium","retrieval_quality":"high","degraded":"no-llm-provider","note":"Synthesis is unavailable; local retrieval and source evidence remain usable. code_rationale carries rationale comments mined from the candidate source — they may already answer the question. symbol_bodies carries the live body of the symbol(s) you named, so answer from that rather than re-reading the file.","best_guesses":[{"file":"django/db/models/query.py","why_relevant":"Implements class PreventQuerySetCloning.","score":5,"excerpt":"# django/db/models/query.py\n\n## Overview\n\nThe main QuerySet implementation. This provides the public API for the ORM.\n\nIt exposes 106 public symbols and depends on 20 other files.\n\n## History\n\n500 commits in its history, 7 in the last 90 days. The last landed on 2026-06-25. **Author One** is its primary maintainer, at 7% of commits. It is one of the repository's change hotspots.\n\n## Changes together with\n\nFiles that change in the same commits as this one without importing it or being imported by it.\n\n- `django/db/models/sql/compiler.py` — 7 shared commits (last together on 2026-06-10)\n\n## Public API\n\n| Symbol | Kind | Signature |\n| --- | --- | --- |\n| `MAX_GET_RESULTS` | constant | MAX_GET_RESULTS = 21 |\n| `REPR_OUTPUT_SIZE` | constant | REPR_OUTPUT_SIZE = 20 |\n| `DEFAULT_FETCH_MODE` | constant | DEFAULT_FETCH_MODE = FETCH_ONE |\n| `BaseIterable` | class | class BaseIterable |\n| `ModelIterable` | class | class ModelIterable |\n| `RawModelIterable` | class | class RawModelIterable |\n| `ValuesIterable` | class | class ValuesIterable |\n| `ValuesListIterable` | class | class ValuesListIterable |\n| `NamedValuesListIterable` | class | class NamedValuesListIterable |\n| `FlatValuesListIterable` | class | class FlatValuesListIterable |\n| `PreventQuerySetCloning` | class | class PreventQuerySetCloning |\n| `QuerySet` | class | class QuerySet |\n| `query` | method | def query(self) |\n| `query` | method | def query(self, value) |\n| `as_manager` | method | def as_manager(cls) |\n| `iterato"},{"file":"django/db/models/sql/query.py","why_relevant":"Create SQL statements for QuerySets..","score":3.5,"excerpt":"# django/db/models/sql/query.py\n\n## Overview\n\nCreate SQL statements for QuerySets.\n\nThe code in here encapsulates all of the SQL construction so that QuerySets\nthemselves do not have to (and could be backed by things other than SQL\ndatabases). The abstraction barrier only works one way: this module has to know\nall about the internals of models in order to get the information it needs.\n\nIt exposes 102 public symbols and depends on 18 other files.\n\n## History\n\n500 commits in its history, 5 in the last 90 days. The last landed on 2026-06-10. **Anssi Kääriäinen** is its primary maintainer, at 18% of commits. It is one of the repository's change hotspots.\n\n## Changes together with\n\nFiles that change in the same commits as this one without importing it or being imported by it.\n\n- `tests/aggregation_regress/tests.py` — 4 shared commits (last together on 2026-04-19)\n- `tests/queries/test_qs_combinators.py` — 2 shared commits (last together on 2026-05-18)\n- `tests/composite_pk/test_filter.py` — 6 shared commits (last together on 2026-04-02)\n- `tests/filtered_relation/tests.py` — 4 shared commits (last together on 2026-02-03)\n- `tests/queries/tests.py` — 4 shared commits (last together on 2026-04-02)\n\n## Public API\n\n| Symbol | Kind | Signature |\n| --- | --- | --- |\n| `FORBIDDEN_ALIAS_PATTERN` | constant | FORBIDDEN_ALIAS_PATTERN = _lazy_re_compile(…) |\n| `EXPLAIN_OPTIONS_PATTERN` | constant | EXPLAIN_OPTIONS_PATTERN = _lazy_re_compile(r\"[\\w-]+\") |\n| `get_field_names_from_opts` | functi"},{"file":"django/db/models/query.py","why_relevant":"Represent a lazy database lookup for a set of objects..","score":3,"excerpt":"# QuerySet\n\n**Kind:** class | **Defined in:** `django/db/models/query.py` | **Estimated complexity:** 1\n\n```\nclass QuerySet\n```\n\n## Overview\n\nRepresent a lazy database lookup for a set of objects.\n\n## Where it is used\n\n12 files import the module that defines it. These are import-level references, not confirmed call sites.\n\n- `django/contrib/contenttypes/fields.py`\n- `django/contrib/contenttypes/prefetch.py`\n- `django/db/models/__init__.py`\n- `django/db/models/base.py`\n- `django/db/models/manager.py`\n- `django/db/models/fields/related_descriptors.py`\n- `django/db/models/sql/query.py`\n- `tests/basic/tests.py`\n- `tests/model_forms/tests.py`\n- `tests/prefetch_related/models.py`\n- `tests/prefetch_related/tests.py`\n- `tests/raw_query/tests.py`\n\n## Implementation\n\n```\nclass QuerySet(AltersData):\n \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n def __init__(self, model=None, query=None, using=None, hints=None):\n self.model = model\n self._db = using\n self._hints = hints or {}\n self._query = query or sql.Query(self.model)\n self._result_cache = None\n self._sticky_filter = False\n self._for_write = False\n self._prefetch_related_lookups = ()\n self._prefetch_done = False\n self._known_related_objects = {} # {rel_field: {pk: rel_obj}}\n self._iterable_class = ModelIterable\n self._fetch_mode = DEFAULT_FETCH_MODE\n self._fields = None\n self._defer_next_filter = False\n sel"}],"code_rationale":[{"path":"django/db/models/query.py","lines":[309,316],"comment":"Temporarily prevent the given QuerySet from creating new QuerySet instances on each mutating operation (e.g: filter(), exclude() etc), instead modifying the QuerySet in-place. @contextlib.contextmanager is intentionally not used for performance reasons.","matched_terms":["queryset"]},{"path":"django/db/models/query.py","lines":[566,570],"comment":"An iterator over the results from applying this QuerySet to the database. chunk_size must be provided for QuerySets that prefetch related objects. Otherwise, a default chunk_size of 2000 is supplied.","matched_terms":["queryset"]}],"symbol_bodies":[{"path":"django/db/models/query.py","name":"QuerySet","lines":[330,450],"source":"class QuerySet(AltersData):\n \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n\n def __init__(self, model=None, query=None, using=None, hints=None):\n self.model = model\n self._db = using\n self._hints = hints or {}\n self._query = query or sql.Query(self.model)\n self._result_cache = None\n self._sticky_filter = False\n self._for_write = False\n self._prefetch_related_lookups = ()\n self._prefetch_done = False\n self._known_related_objects = {} # {rel_field: {pk: rel_obj}}\n self._iterable_class = ModelIterable\n self._fetch_mode = DEFAULT_FETCH_MODE\n self._fields = None\n self._defer_next_filter = False\n self._deferred_filter = None\n self._cloning_enabled = True\n\n @property\n def query(self):\n if self._deferred_filter:\n negate, args, kwargs = self._deferred_filter\n self._filter_or_exclude_inplace(negate, args, kwargs)\n self._deferred_filter = None\n return self._query\n\n @query.setter\n def query(self, value):\n if value.values_select:\n self._iterable_class = ValuesIterable\n self._query = value\n\n def as_manager(cls):\n # Address the circular dependency between `Queryset` and `Manager`.\n from django.db.models.manager import Manager\n\n manager = Manager.from_queryset(cls)()\n manager._built_with_as_manager = True\n return manager\n\n as_manager.queryset_only = True\n as_manager = classmethod(as_manager)\n\n ########################\n # PYTHON MAGIC METHODS #\n ########################\n\n def __deepcopy__(self, memo):\n \"\"\"Don't populate the QuerySet's cache.\"\"\"\n obj = self.__class__()\n for k, v in self.__dict__.items():\n if k == \"_result_cache\":\n obj.__dict__[k] = None\n else:\n obj.__dict__[k] = copy.deepcopy(v, memo)\n return obj\n\n def __getstate__(self):\n # Force the cache to be fully populated.\n self._fetch_all()\n return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n\n def __setstate__(self, state):\n pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n if pickled_version:\n if pickled_version != django.__version__:\n warnings.warn(\n \"Pickled queryset instance's Django version %s does not \"\n \"match the current version %s.\"\n % (pickled_version, django.__version__),\n RuntimeWarning,\n stacklevel=2,\n )\n else:\n warnings.warn(\n \"Pickled queryset instance's Django version is not specified.\",\n RuntimeWarning,\n stacklevel=2,\n )\n self.__dict__.update(state)\n\n def __repr__(self):\n data = list(self[: REPR_OUTPUT_SIZE + 1])\n if len(data) > REPR_OUTPUT_SIZE:\n data[-1] = \"...(remaining elements truncated)...\"\n return \"<%s %r>\" % (self.__class__.__name__, data)\n\n def __len__(self):\n self._fetch_all()\n return len(self._result_cache)\n\n def __iter__(self):\n \"\"\"\n The queryset iterator protocol uses three nested iterators in the\n default case:\n 1. sql.compiler.execute_sql()\n - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n using cursor.fetchmany(). This part is responsible for\n doing some column masking, and returning the rows in chunks.\n 2. sql.compiler.results_iter()\n - Returns one row at time. At this point the rows are still just\n tuples. In some cases the return values are converted to\n Python values at this location.\n 3. self.iterator()\n - Responsible for turning the rows into model objects.\n \"\"\"\n self._fetch_all()\n return iter(self._result_cache)\n\n def __aiter__(self):\n # Remember, __aiter__ itself is synchronous, it's the thing it returns\n # that is async!\n async def generator():\n await sync_to_async(self._fetch_all)()\n for item in self._result_cache:\n yield item\n\n return generator()","verified":true,"truncated":true,"continuation":"django/db/models/query.py:451-2367","withheld_symbols":[{"name":"QuerySet","kind":"class","line":330,"symbol_id":"django/db/models/query.py::QuerySet","signature":"class QuerySet(AltersData):","body_continues":true},{"name":"__bool__","kind":"def","line":452,"symbol_id":"django/db/models/query.py::__bool__","signature":"def __bool__(self):"},{"name":"__getitem__","kind":"def","line":456,"symbol_id":"django/db/models/query.py::__getitem__","signature":"def __getitem__(self, k):"},{"name":"__class_getitem__","kind":"def","line":493,"symbol_id":"django/db/models/query.py::__class_getitem__","signature":"def __class_getitem__(cls, *args, **kwargs):"},{"name":"__and__","kind":"def","line":496,"symbol_id":"django/db/models/query.py::__and__","signature":"def __and__(self, other):"},{"name":"__or__","kind":"def","line":508,"symbol_id":"django/db/models/query.py::__or__","signature":"def __or__(self, other):"},{"name":"__xor__","kind":"def","line":527,"symbol_id":"django/db/models/query.py::__xor__","signature":"def __xor__(self, other):"},{"name":"_iterator","kind":"def","line":550,"symbol_id":"django/db/models/query.py::_iterator","signature":"def _iterator(self, use_chunked_fetch, chunk_size):"}]}],"grounding":"symbol_body","next_action_hint":"QuerySet was served through line 450; call get_symbol id='django/db/models/query.py::__bool__' for the withheld body.","_meta":{"contract_version":2,"timing_ms":2087,"hint":"Synthesis is what is missing here, not retrieval. Answer from symbol_bodies; retrieval_quality rates what was served.","index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"degraded":"no-llm-provider","projection":{"recovery":{"tool":"get_answer","arguments":{"question":"why is QuerySet lazy?","include":["evidence"]}}},"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"scope_hint":"Unrelated to what was served: Application (472 files), Config (205), Service (80).","state":{"degraded":true,"degraded_reasons":{"degraded":"no-llm-provider"}},"response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":14042},"completeness":{"capped":true,"shown":2,"total":21,"reason":"confidence_projection_and_deduplication"}},"retrieval_total":5,"retrieval_emitted":0,"retrieval_reduced_reason":"confidence_projection_and_deduplication","code_rationale_total":6,"code_rationale_emitted":2,"code_rationale_reduced_reason":"confidence_projection_and_deduplication","candidates_total":5,"candidates_emitted":0,"candidates_reduced_reason":"confidence_projection_and_deduplication","fallback_targets_total":5,"fallback_targets_emitted":0,"fallback_targets_reduced_reason":"confidence_projection_and_deduplication"}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_context.json b/packages/claude-mod/test/fixtures/flow/get_context.json
new file mode 100644
index 000000000..2ac584edc
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_context.json
@@ -0,0 +1 @@
+{"result":{"targets":{"django/db/models/query.py":{"type":"file","path":"django/db/models/query.py","parent_page":{"title":"Models Overview","target_path":"django/db/models","section":"10.2"},"docs":{"title":"File: django/db/models/query.py","summary":"The main QuerySet implementation. This provides the public API for the ORM.","symbols":[{"name":"MAX_GET_RESULTS","kind":"constant","signature":"MAX_GET_RESULTS = 21","line":49,"symbol_id":"django/db/models/query.py::MAX_GET_RESULTS"},{"name":"REPR_OUTPUT_SIZE","kind":"constant","signature":"REPR_OUTPUT_SIZE = 20","line":52,"symbol_id":"django/db/models/query.py::REPR_OUTPUT_SIZE"},{"name":"DEFAULT_FETCH_MODE","kind":"constant","signature":"DEFAULT_FETCH_MODE = FETCH_ONE","line":54,"symbol_id":"django/db/models/query.py::DEFAULT_FETCH_MODE"},{"name":"BaseIterable","kind":"class","signature":"class BaseIterable","line":57,"symbol_id":"django/db/models/query.py::BaseIterable"},{"name":"__init__","kind":"method","signature":"def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE )","line":58,"symbol_id":"django/db/models/query.py::BaseIterable::__init__"},{"name":"_async_generator","kind":"method","signature":"async def _async_generator(self)","line":65,"symbol_id":"django/db/models/query.py::BaseIterable::_async_generator"},{"name":"__aiter__","kind":"method","signature":"def __aiter__(self)","line":89,"symbol_id":"django/db/models/query.py::BaseIterable::__aiter__"},{"name":"ModelIterable","kind":"class","signature":"class ModelIterable","line":93,"symbol_id":"django/db/models/query.py::ModelIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":96,"symbol_id":"django/db/models/query.py::ModelIterable::__iter__"},{"name":"RawModelIterable","kind":"class","signature":"class RawModelIterable","line":171,"symbol_id":"django/db/models/query.py::RawModelIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":176,"symbol_id":"django/db/models/query.py::RawModelIterable::__iter__"},{"name":"ValuesIterable","kind":"class","signature":"class ValuesIterable","line":227,"symbol_id":"django/db/models/query.py::ValuesIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":232,"symbol_id":"django/db/models/query.py::ValuesIterable::__iter__"},{"name":"ValuesListIterable","kind":"class","signature":"class ValuesListIterable","line":253,"symbol_id":"django/db/models/query.py::ValuesListIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":259,"symbol_id":"django/db/models/query.py::ValuesListIterable::__iter__"},{"name":"NamedValuesListIterable","kind":"class","signature":"class NamedValuesListIterable","line":270,"symbol_id":"django/db/models/query.py::NamedValuesListIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":276,"symbol_id":"django/db/models/query.py::NamedValuesListIterable::__iter__"},{"name":"FlatValuesListIterable","kind":"class","signature":"class FlatValuesListIterable","line":293,"symbol_id":"django/db/models/query.py::FlatValuesListIterable"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":299,"symbol_id":"django/db/models/query.py::FlatValuesListIterable::__iter__"},{"name":"PreventQuerySetCloning","kind":"class","signature":"class PreventQuerySetCloning","line":308,"symbol_id":"django/db/models/query.py::PreventQuerySetCloning"},{"name":"__init__","kind":"method","signature":"def __init__(self, queryset)","line":320,"symbol_id":"django/db/models/query.py::PreventQuerySetCloning::__init__"},{"name":"__enter__","kind":"method","signature":"def __enter__(self)","line":323,"symbol_id":"django/db/models/query.py::PreventQuerySetCloning::__enter__"},{"name":"__exit__","kind":"method","signature":"def __exit__(self, exc_type, exc_value, traceback)","line":326,"symbol_id":"django/db/models/query.py::PreventQuerySetCloning::__exit__"},{"name":"QuerySet","kind":"class","signature":"class QuerySet","line":330,"symbol_id":"django/db/models/query.py::QuerySet"},{"name":"__init__","kind":"method","signature":"def __init__(self, model=None, query=None, using=None, hints=None)","line":333,"symbol_id":"django/db/models/query.py::QuerySet::__init__"},{"name":"query","kind":"method","signature":"def query(self, value)","line":360,"symbol_id":"django/db/models/query.py::QuerySet::query"},{"name":"as_manager","kind":"method","signature":"def as_manager(cls)","line":365,"symbol_id":"django/db/models/query.py::QuerySet::as_manager"},{"name":"__deepcopy__","kind":"method","signature":"def __deepcopy__(self, memo)","line":380,"symbol_id":"django/db/models/query.py::QuerySet::__deepcopy__"},{"name":"__getstate__","kind":"method","signature":"def __getstate__(self)","line":390,"symbol_id":"django/db/models/query.py::QuerySet::__getstate__"},{"name":"__setstate__","kind":"method","signature":"def __setstate__(self, state)","line":395,"symbol_id":"django/db/models/query.py::QuerySet::__setstate__"},{"name":"__repr__","kind":"method","signature":"def __repr__(self)","line":414,"symbol_id":"django/db/models/query.py::QuerySet::__repr__"},{"name":"__len__","kind":"method","signature":"def __len__(self)","line":420,"symbol_id":"django/db/models/query.py::QuerySet::__len__"},{"name":"__iter__","kind":"method","signature":"def __iter__(self)","line":424,"symbol_id":"django/db/models/query.py::QuerySet::__iter__"},{"name":"__aiter__","kind":"method","signature":"def __aiter__(self)","line":442,"symbol_id":"django/db/models/query.py::QuerySet::__aiter__"},{"name":"__bool__","kind":"method","signature":"def __bool__(self)","line":452,"symbol_id":"django/db/models/query.py::QuerySet::__bool__"},{"name":"__getitem__","kind":"method","signature":"def __getitem__(self, k)","line":456,"symbol_id":"django/db/models/query.py::QuerySet::__getitem__"},{"name":"__class_getitem__","kind":"method","signature":"def __class_getitem__(cls, *args, **kwargs)","line":493,"symbol_id":"django/db/models/query.py::QuerySet::__class_getitem__"},{"name":"__and__","kind":"method","signature":"def __and__(self, other)","line":496,"symbol_id":"django/db/models/query.py::QuerySet::__and__"},{"name":"__or__","kind":"method","signature":"def __or__(self, other)","line":508,"symbol_id":"django/db/models/query.py::QuerySet::__or__"},{"name":"__xor__","kind":"method","signature":"def __xor__(self, other)","line":527,"symbol_id":"django/db/models/query.py::QuerySet::__xor__"}],"symbols_truncated":{"shown":40,"total":180,"hint":"Call with compact=False or include=['full_doc'] for the full list."}},"hotspot":true,"freshness":{"confidence_score":1,"freshness_status":"fresh","is_stale":false},"architectural_layer":{"name":"Data","description":"","role":"edge_connector"}}},"_meta":{"contract_version":2,"timing_ms":55.98,"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"scope_hint":"Unrelated to what was served: Application (472 files), Config (205), Service (80).","response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":7566},"completeness":{"capped":false}}}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_context_ownership.json b/packages/claude-mod/test/fixtures/flow/get_context_ownership.json
new file mode 100644
index 000000000..f2e1ea53a
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_context_ownership.json
@@ -0,0 +1,508 @@
+{
+ "targets": {
+ "django/db/models/query.py": {
+ "type": "file",
+ "path": "django/db/models/query.py",
+ "parent_page": {
+ "title": "Models Overview",
+ "target_path": "django/db/models",
+ "section": "10.2"
+ },
+ "docs": {
+ "title": "File: django/db/models/query.py",
+ "summary": "The main QuerySet implementation. This provides the public API for the ORM.",
+ "symbols": [
+ {
+ "name": "MAX_GET_RESULTS",
+ "kind": "constant",
+ "signature": "MAX_GET_RESULTS = 21",
+ "line": 49,
+ "symbol_id": "django/db/models/query.py::MAX_GET_RESULTS"
+ },
+ {
+ "name": "REPR_OUTPUT_SIZE",
+ "kind": "constant",
+ "signature": "REPR_OUTPUT_SIZE = 20",
+ "line": 52,
+ "symbol_id": "django/db/models/query.py::REPR_OUTPUT_SIZE"
+ },
+ {
+ "name": "DEFAULT_FETCH_MODE",
+ "kind": "constant",
+ "signature": "DEFAULT_FETCH_MODE = FETCH_ONE",
+ "line": 54,
+ "symbol_id": "django/db/models/query.py::DEFAULT_FETCH_MODE"
+ },
+ {
+ "name": "BaseIterable",
+ "kind": "class",
+ "signature": "class BaseIterable",
+ "line": 57,
+ "symbol_id": "django/db/models/query.py::BaseIterable"
+ },
+ {
+ "name": "__init__",
+ "kind": "method",
+ "signature": "def __init__( self, queryset, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE )",
+ "line": 58,
+ "symbol_id": "django/db/models/query.py::BaseIterable::__init__"
+ },
+ {
+ "name": "_async_generator",
+ "kind": "method",
+ "signature": "async def _async_generator(self)",
+ "line": 65,
+ "symbol_id": "django/db/models/query.py::BaseIterable::_async_generator"
+ },
+ {
+ "name": "__aiter__",
+ "kind": "method",
+ "signature": "def __aiter__(self)",
+ "line": 89,
+ "symbol_id": "django/db/models/query.py::BaseIterable::__aiter__"
+ },
+ {
+ "name": "ModelIterable",
+ "kind": "class",
+ "signature": "class ModelIterable",
+ "line": 93,
+ "symbol_id": "django/db/models/query.py::ModelIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 96,
+ "symbol_id": "django/db/models/query.py::ModelIterable::__iter__"
+ },
+ {
+ "name": "RawModelIterable",
+ "kind": "class",
+ "signature": "class RawModelIterable",
+ "line": 171,
+ "symbol_id": "django/db/models/query.py::RawModelIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 176,
+ "symbol_id": "django/db/models/query.py::RawModelIterable::__iter__"
+ },
+ {
+ "name": "ValuesIterable",
+ "kind": "class",
+ "signature": "class ValuesIterable",
+ "line": 227,
+ "symbol_id": "django/db/models/query.py::ValuesIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 232,
+ "symbol_id": "django/db/models/query.py::ValuesIterable::__iter__"
+ },
+ {
+ "name": "ValuesListIterable",
+ "kind": "class",
+ "signature": "class ValuesListIterable",
+ "line": 253,
+ "symbol_id": "django/db/models/query.py::ValuesListIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 259,
+ "symbol_id": "django/db/models/query.py::ValuesListIterable::__iter__"
+ },
+ {
+ "name": "NamedValuesListIterable",
+ "kind": "class",
+ "signature": "class NamedValuesListIterable",
+ "line": 270,
+ "symbol_id": "django/db/models/query.py::NamedValuesListIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 276,
+ "symbol_id": "django/db/models/query.py::NamedValuesListIterable::__iter__"
+ },
+ {
+ "name": "FlatValuesListIterable",
+ "kind": "class",
+ "signature": "class FlatValuesListIterable",
+ "line": 293,
+ "symbol_id": "django/db/models/query.py::FlatValuesListIterable"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 299,
+ "symbol_id": "django/db/models/query.py::FlatValuesListIterable::__iter__"
+ },
+ {
+ "name": "PreventQuerySetCloning",
+ "kind": "class",
+ "signature": "class PreventQuerySetCloning",
+ "line": 308,
+ "symbol_id": "django/db/models/query.py::PreventQuerySetCloning"
+ },
+ {
+ "name": "__init__",
+ "kind": "method",
+ "signature": "def __init__(self, queryset)",
+ "line": 320,
+ "symbol_id": "django/db/models/query.py::PreventQuerySetCloning::__init__"
+ },
+ {
+ "name": "__enter__",
+ "kind": "method",
+ "signature": "def __enter__(self)",
+ "line": 323,
+ "symbol_id": "django/db/models/query.py::PreventQuerySetCloning::__enter__"
+ },
+ {
+ "name": "__exit__",
+ "kind": "method",
+ "signature": "def __exit__(self, exc_type, exc_value, traceback)",
+ "line": 326,
+ "symbol_id": "django/db/models/query.py::PreventQuerySetCloning::__exit__"
+ },
+ {
+ "name": "QuerySet",
+ "kind": "class",
+ "signature": "class QuerySet",
+ "line": 330,
+ "symbol_id": "django/db/models/query.py::QuerySet"
+ },
+ {
+ "name": "__init__",
+ "kind": "method",
+ "signature": "def __init__(self, model=None, query=None, using=None, hints=None)",
+ "line": 333,
+ "symbol_id": "django/db/models/query.py::QuerySet::__init__"
+ },
+ {
+ "name": "query",
+ "kind": "method",
+ "signature": "def query(self, value)",
+ "line": 360,
+ "symbol_id": "django/db/models/query.py::QuerySet::query"
+ },
+ {
+ "name": "as_manager",
+ "kind": "method",
+ "signature": "def as_manager(cls)",
+ "line": 365,
+ "symbol_id": "django/db/models/query.py::QuerySet::as_manager"
+ },
+ {
+ "name": "__deepcopy__",
+ "kind": "method",
+ "signature": "def __deepcopy__(self, memo)",
+ "line": 380,
+ "symbol_id": "django/db/models/query.py::QuerySet::__deepcopy__"
+ },
+ {
+ "name": "__getstate__",
+ "kind": "method",
+ "signature": "def __getstate__(self)",
+ "line": 390,
+ "symbol_id": "django/db/models/query.py::QuerySet::__getstate__"
+ },
+ {
+ "name": "__setstate__",
+ "kind": "method",
+ "signature": "def __setstate__(self, state)",
+ "line": 395,
+ "symbol_id": "django/db/models/query.py::QuerySet::__setstate__"
+ },
+ {
+ "name": "__repr__",
+ "kind": "method",
+ "signature": "def __repr__(self)",
+ "line": 414,
+ "symbol_id": "django/db/models/query.py::QuerySet::__repr__"
+ },
+ {
+ "name": "__len__",
+ "kind": "method",
+ "signature": "def __len__(self)",
+ "line": 420,
+ "symbol_id": "django/db/models/query.py::QuerySet::__len__"
+ },
+ {
+ "name": "__iter__",
+ "kind": "method",
+ "signature": "def __iter__(self)",
+ "line": 424,
+ "symbol_id": "django/db/models/query.py::QuerySet::__iter__"
+ },
+ {
+ "name": "__aiter__",
+ "kind": "method",
+ "signature": "def __aiter__(self)",
+ "line": 442,
+ "symbol_id": "django/db/models/query.py::QuerySet::__aiter__"
+ },
+ {
+ "name": "__bool__",
+ "kind": "method",
+ "signature": "def __bool__(self)",
+ "line": 452,
+ "symbol_id": "django/db/models/query.py::QuerySet::__bool__"
+ },
+ {
+ "name": "__getitem__",
+ "kind": "method",
+ "signature": "def __getitem__(self, k)",
+ "line": 456,
+ "symbol_id": "django/db/models/query.py::QuerySet::__getitem__"
+ },
+ {
+ "name": "__class_getitem__",
+ "kind": "method",
+ "signature": "def __class_getitem__(cls, *args, **kwargs)",
+ "line": 493,
+ "symbol_id": "django/db/models/query.py::QuerySet::__class_getitem__"
+ },
+ {
+ "name": "__and__",
+ "kind": "method",
+ "signature": "def __and__(self, other)",
+ "line": 496,
+ "symbol_id": "django/db/models/query.py::QuerySet::__and__"
+ },
+ {
+ "name": "__or__",
+ "kind": "method",
+ "signature": "def __or__(self, other)",
+ "line": 508,
+ "symbol_id": "django/db/models/query.py::QuerySet::__or__"
+ },
+ {
+ "name": "__xor__",
+ "kind": "method",
+ "signature": "def __xor__(self, other)",
+ "line": 527,
+ "symbol_id": "django/db/models/query.py::QuerySet::__xor__"
+ }
+ ],
+ "symbols_truncated": {
+ "shown": 40,
+ "total": 180,
+ "hint": "Call with compact=False or include=['full_doc'] for the full list."
+ }
+ },
+ "hotspot": true,
+ "ownership": {
+ "primary_owner": "Author One",
+ "owner_pct": 0.066,
+ "owner_line_pct": null,
+ "contributor_count": 172,
+ "bus_factor": 72,
+ "recent_owner": "author_two",
+ "recent_owner_pct": 0.2857
+ },
+ "last_change": {
+ "date": "2026-06-25T20:47:00",
+ "author": "Author One",
+ "days_ago": 6030
+ },
+ "decisions": [],
+ "freshness": {
+ "confidence_score": 1.0,
+ "freshness_status": "fresh",
+ "is_stale": false
+ },
+ "architectural_layer": {
+ "name": "Data",
+ "description": "",
+ "role": "edge_connector"
+ },
+ "callers": [
+ {
+ "file": "tests/aggregation/tests.py",
+ "inbound_calls": 131
+ },
+ {
+ "file": "tests/queries/tests.py",
+ "inbound_calls": 88
+ },
+ {
+ "file": "tests/aggregation_regress/tests.py",
+ "inbound_calls": 87
+ },
+ {
+ "file": "tests/prefetch_related/tests.py",
+ "imports": true,
+ "inbound_calls": 83
+ },
+ {
+ "file": "tests/annotations/tests.py",
+ "inbound_calls": 64
+ },
+ {
+ "file": "tests/expressions_case/tests.py",
+ "inbound_calls": 63
+ },
+ {
+ "file": "tests/expressions_window/tests.py",
+ "inbound_calls": 51
+ },
+ {
+ "file": "tests/queries/test_qs_combinators.py",
+ "inbound_calls": 45
+ },
+ {
+ "file": "tests/lookup/tests.py",
+ "inbound_calls": 41
+ },
+ {
+ "file": "tests/db_functions/datetime/test_extract_trunc.py",
+ "inbound_calls": 37
+ },
+ {
+ "file": "tests/filtered_relation/tests.py",
+ "inbound_calls": 37
+ },
+ {
+ "file": "tests/defer/tests.py",
+ "inbound_calls": 25
+ },
+ {
+ "file": "tests/prefetch_related/test_prefetch_related_objects.py",
+ "inbound_calls": 24
+ },
+ {
+ "file": "tests/expressions/tests.py",
+ "inbound_calls": 20
+ },
+ {
+ "file": "tests/composite_pk/test_filter.py",
+ "inbound_calls": 18
+ },
+ {
+ "file": "tests/defer_regress/tests.py",
+ "inbound_calls": 18
+ },
+ {
+ "file": "tests/select_for_update/tests.py",
+ "inbound_calls": 18
+ },
+ {
+ "file": "tests/basic/tests.py",
+ "imports": true,
+ "inbound_calls": 17
+ },
+ {
+ "file": "tests/postgres_tests/test_aggregates.py",
+ "inbound_calls": 17
+ },
+ {
+ "file": "tests/foreign_object/test_tuple_lookups.py",
+ "inbound_calls": 15
+ }
+ ],
+ "callers_total": 131,
+ "callers_emitted": 20,
+ "callers_truncated": true,
+ "callers_reduced_reason": "construction_cap",
+ "callers_omitted": 111,
+ "_call_graph_note": "File-level rollup: importing files plus inbound cross-file call counts. For symbol-precise callers pass 'file.py::Symbol'.",
+ "health": {
+ "score": 2.0,
+ "max_ccn": 26,
+ "max_nesting": 7,
+ "nloc": 2471,
+ "has_test_file": true,
+ "module": "django",
+ "duplication_pct": 2.56,
+ "top_biomarkers": [
+ {
+ "biomarker_type": "change_entropy",
+ "severity": "critical",
+ "impact": 1.27,
+ "suggestion": "Calm this file's change history. Its modifications arrive in wide, scattered commits — a strong history-based fault predictor. Land future edits in focused, single-purpose commits, and consider splitting the file so unrelated changes stop landing together."
+ },
+ {
+ "biomarker_type": "ownership_risk",
+ "severity": "critical",
+ "impact": 1.17,
+ "suggestion": "Assign a clear owner and reduce drive-by contributors on this file. Fragmented ownership — many authors each touching a small slice — is one of the strongest defect predictors; nominate a DRI for reviews, or split the file along its natural seams so each part has a coherent owner."
+ }
+ ],
+ "signals": {
+ "prior_defect_count": 0,
+ "change_entropy_pct": 99.7,
+ "lines_added_90d": 54,
+ "lines_deleted_90d": 15,
+ "commit_count_90d": 7,
+ "age_days": 6030,
+ "primary_owner_name": "Author One",
+ "primary_owner_commit_pct": 0.066,
+ "recent_owner_name": "author_two",
+ "recent_owner_commit_pct": 0.2857,
+ "in_degree": 12,
+ "out_degree": 28,
+ "bug_magnet": false
+ }
+ }
+ }
+ },
+ "_meta": {
+ "contract_version": 2,
+ "timing_ms": 131.3,
+ "index_age_days": 0,
+ "indexed_commit": "e78991410b78",
+ "live_head": "e78991410b78",
+ "index_behind": false,
+ "index_scope": {
+ "version": 1,
+ "projection": "compact",
+ "run_mode": "standard",
+ "content_provenance": "template",
+ "git_tier": "full",
+ "status": "upgrading",
+ "fingerprint": "99c42a358f89",
+ "full": "get_overview()",
+ "degraded_analyses": [
+ "Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."
+ ]
+ },
+ "embedder": "mock",
+ "embedder_degraded": false,
+ "semantic_search": false,
+ "scope_hint": "Unrelated to what was served: Application (472 files), Config (205), Service (80).",
+ "omitted": {
+ "refs": [
+ "repowise#5da23d779663"
+ ],
+ "tokens": 2181,
+ "restore": "`repowise expand <ref>`, or get_symbol(\"repowise#<ref>\", query=...)"
+ },
+ "state": {
+ "truncated": true
+ },
+ "response_budget": {
+ "limit_chars": 32000,
+ "tier": "expanded",
+ "serialized_chars": 10995
+ },
+ "completeness": {
+ "capped": true,
+ "shown": 20,
+ "total": 131,
+ "reason": "construction_cap"
+ },
+ "floor": [
+ "callers_total"
+ ]
+ },
+ "omission_marker": "[repowise#5da23d779663: 459 lines omitted (~2181 tokens); restore: repowise expand 5da23d779663]"
+}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_risk.json b/packages/claude-mod/test/fixtures/flow/get_risk.json
new file mode 100644
index 000000000..6ce2dcaf9
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_risk.json
@@ -0,0 +1 @@
+{"result":{"targets":{"django/db/models/query.py":{"dependents_count":12,"hotspot_score":0.9964,"is_hotspot":true,"co_change_partners":[{"file_path":"tests/queries/tests.py","weight":0.8024,"last_co_change":"2026-05-11","relationship_type":"co_change","direction":"b_to_a","evidence_kind":"historical","provenance":"git_history","has_structural_link":false,"has_import_link":false,"support":5,"conf_ab":0.085,"conf_ba":0.333},{"file_path":"django/db/models/sql/query.py","weight":0.5127,"last_co_change":"2026-06-10","relationship_type":"co_change","direction":"b_to_a","evidence_kind":"historical","provenance":"git_history","has_structural_link":true,"has_import_link":true,"structural_relationship_types":["imports"],"support":6,"conf_ab":0.102,"conf_ba":0.162},{"file_path":"django/db/models/sql/compiler.py","weight":0.4635,"last_co_change":"2026-06-10","relationship_type":"co_change","direction":"b_to_a","evidence_kind":"historical","provenance":"git_history","has_structural_link":false,"has_import_link":false,"support":7,"conf_ab":0.119,"conf_ba":0.212},{"file_path":"docs/internals/deprecation.txt","weight":0.4385,"last_co_change":"2026-06-18","relationship_type":"co_change","direction":"b_to_a","evidence_kind":"historical","provenance":"git_history","has_structural_link":false,"has_import_link":false,"support":3,"conf_ab":0.051,"conf_ba":0.073},{"file_path":"tests/queries/test_qs_combinators.py","weight":0.4262,"last_co_change":"2026-02-06","relationship_type":"co_change","direction":"b_to_a","evidence_kind":"historical","provenance":"git_history","has_structural_link":false,"has_import_link":false,"support":2,"conf_ab":0.034,"conf_ba":0.2}],"co_change_partners_total":25,"co_change_partners_emitted":5,"co_change_partners_truncated":true,"co_change_partners_reduced_reason":"construction_cap","co_change_partners_omitted":20,"primary_owner":"Author One","owner_pct":0.066,"owner_line_pct":null,"recent_owner":"author_two","recent_owner_pct":0.2857,"bus_factor":72,"contributor_count":172,"trend":"stable","test_gap":false,"security_signals":[],"commit_count_capped":true,"risk_summary":"django/db/models/query.py — hotspot score 100% (stable), 12 direct dependents, churn-heavy, fix-heavy, 25 co-change partners, primary owner Author One (7% of commits) (history truncated — actual count may be higher)","health_score":2,"top_biomarkers":[{"biomarker_type":"change_entropy","severity":"critical","impact":1.27},{"biomarker_type":"ownership_risk","severity":"critical","impact":1.17},{"biomarker_type":"co_change_scatter","severity":"high","impact":0.91}]}},"_meta":{"contract_version":2,"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"omitted":{"refs":["repowise#63d56ff4867f"],"tokens":1849,"restore":"`repowise expand <ref>`, or get_symbol(\"repowise#<ref>\", query=...)"},"state":{"truncated":true},"response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":3715},"completeness":{"capped":true,"shown":5,"total":25,"reason":"construction_cap"},"floor":["co_change_partners_total","dependents_count"],"replaced_tokens":2000,"tokens_saved":1087,"timing_ms":445.36},"omission_marker":"[repowise#63d56ff4867f: 301 lines omitted (~1849 tokens); restore: repowise expand 63d56ff4867f]"}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_symbol.json b/packages/claude-mod/test/fixtures/flow/get_symbol.json
new file mode 100644
index 000000000..6ebfce277
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_symbol.json
@@ -0,0 +1 @@
+{"result":{"symbol_id":"django/db/models/query.py::QuerySet","file":"django/db/models/query.py","name":"QuerySet","kind":"class","qualified_name":"django.db.models.query.QuerySet","signature":"class QuerySet","start_line":330,"end_line":929,"source":" 330\tclass QuerySet(AltersData):\n 331\t \"\"\"Represent a lazy database lookup for a set of objects.\"\"\"\n 332\t\n 333\t def __init__(self, model=None, query=None, using=None, hints=None):\n 334\t self.model = model\n 335\t self._db = using\n 336\t self._hints = hints or {}\n 337\t self._query = query or sql.Query(self.model)\n 338\t self._result_cache = None\n 339\t self._sticky_filter = False\n 340\t self._for_write = False\n 341\t self._prefetch_related_lookups = ()\n 342\t self._prefetch_done = False\n 343\t self._known_related_objects = {} # {rel_field: {pk: rel_obj}}\n 344\t self._iterable_class = ModelIterable\n 345\t self._fetch_mode = DEFAULT_FETCH_MODE\n 346\t self._fields = None\n 347\t self._defer_next_filter = False\n 348\t self._deferred_filter = None\n 349\t self._cloning_enabled = True\n 350\t\n 351\t @property\n 352\t def query(self):\n 353\t if self._deferred_filter:\n 354\t negate, args, kwargs = self._deferred_filter\n 355\t self._filter_or_exclude_inplace(negate, args, kwargs)\n 356\t self._deferred_filter = None\n 357\t return self._query\n 358\t\n 359\t @query.setter\n 360\t def query(self, value):\n 361\t if value.values_select:\n 362\t self._iterable_class = ValuesIterable\n 363\t self._query = value\n 364\t\n 365\t def as_manager(cls):\n 366\t # Address the circular dependency between `Queryset` and `Manager`.\n 367\t from django.db.models.manager import Manager\n 368\t\n 369\t manager = Manager.from_queryset(cls)()\n 370\t manager._built_with_as_manager = True\n 371\t return manager\n 372\t\n 373\t as_manager.queryset_only = True\n 374\t as_manager = classmethod(as_manager)\n 375\t\n 376\t ########################\n 377\t # PYTHON MAGIC METHODS #\n 378\t ########################\n 379\t\n 380\t def __deepcopy__(self, memo):\n 381\t \"\"\"Don't populate the QuerySet's cache.\"\"\"\n 382\t obj = self.__class__()\n 383\t for k, v in self.__dict__.items():\n 384\t if k == \"_result_cache\":\n 385\t obj.__dict__[k] = None\n 386\t else:\n 387\t obj.__dict__[k] = copy.deepcopy(v, memo)\n 388\t return obj\n 389\t\n 390\t def __getstate__(self):\n 391\t # Force the cache to be fully populated.\n 392\t self._fetch_all()\n 393\t return {**self.__dict__, DJANGO_VERSION_PICKLE_KEY: django.__version__}\n 394\t\n 395\t def __setstate__(self, state):\n 396\t pickled_version = state.get(DJANGO_VERSION_PICKLE_KEY)\n 397\t if pickled_version:\n 398\t if pickled_version != django.__version__:\n 399\t warnings.warn(\n 400\t \"Pickled queryset instance's Django version %s does not \"\n 401\t \"match the current version %s.\"\n 402\t % (pickled_version, django.__version__),\n 403\t RuntimeWarning,\n 404\t stacklevel=2,\n 405\t )\n 406\t else:\n 407\t warnings.warn(\n 408\t \"Pickled queryset instance's Django version is not specified.\",\n 409\t RuntimeWarning,\n 410\t stacklevel=2,\n 411\t )\n 412\t self.__dict__.update(state)\n 413\t\n 414\t def __repr__(self):\n 415\t data = list(self[: REPR_OUTPUT_SIZE + 1])\n 416\t if len(data) > REPR_OUTPUT_SIZE:\n 417\t data[-1] = \"...(remaining elements truncated)...\"\n 418\t return \"<%s %r>\" % (self.__class__.__name__, data)\n 419\t\n 420\t def __len__(self):\n 421\t self._fetch_all()\n 422\t return len(self._result_cache)\n 423\t\n 424\t def __iter__(self):\n 425\t \"\"\"\n 426\t The queryset iterator protocol uses three nested iterators in the\n 427\t default case:\n 428\t 1. sql.compiler.execute_sql()\n 429\t - Returns 100 rows at time (constants.GET_ITERATOR_CHUNK_SIZE)\n 430\t using cursor.fetchmany(). This part is responsible for\n 431\t doing some column masking, and returning the rows in chunks.\n 432\t 2. sql.compiler.results_iter()\n 433\t - Returns one row at time. At this point the rows are still just\n 434\t tuples. In some cases the return values are converted to\n 435\t Python values at this location.\n 436\t 3. self.iterator()\n 437\t - Responsible for turning the rows into model objects.\n 438\t \"\"\"\n 439\t self._fetch_all()\n 440\t return iter(self._result_cache)\n 441\t\n 442\t def __aiter__(self):\n 443\t # Remember, __aiter__ itself is synchronous, it's the thing it returns\n 444\t # that is async!\n 445\t async def generator():\n 446\t await sync_to_async(self._fetch_all)()\n 447\t for item in self._result_cache:\n 448\t yield item\n 449\t\n 450\t return generator()\n 451\t\n 452\t def __bool__(self):\n 453\t self._fetch_all()\n 454\t return bool(self._result_cache)\n 455\t\n 456\t def __getitem__(self, k):\n 457\t \"\"\"Retrieve an item or slice from the set of results.\"\"\"\n 458\t if not isinstance(k, (int, slice)):\n 459\t raise TypeError(\n 460\t \"QuerySet indices must be integers or slices, not %s.\"\n 461\t % type(k).__name__\n 462\t )\n 463\t if (isinstance(k, int) and k < 0) or (\n 464\t isinstance(k, slice)\n 465\t and (\n 466\t (k.start is not None and k.start < 0)\n 467\t or (k.stop is not None and k.stop < 0)\n 468\t )\n 469\t ):\n 470\t raise ValueError(\"Negative indexing is not supported.\")\n 471\t\n 472\t if self._result_cache is not None:\n 473\t return self._result_cache[k]\n 474\t\n 475\t if isinstance(k, slice):\n 476\t qs = self._chain()\n 477\t if k.start is not None:\n 478\t start = int(k.start)\n 479\t else:\n 480\t start = None\n 481\t if k.stop is not None:\n 482\t stop = int(k.stop)\n 483\t else:\n 484\t stop = None\n 485\t qs.query.set_limits(start, stop)\n 486\t return list(qs)[:: k.step] if k.step else qs\n 487\t\n 488\t qs = self._chain()\n 489\t qs.query.set_limits(k, k + 1)\n 490\t qs._fetch_all()\n 491\t return qs._result_cache[0]\n 492\t\n 493\t def __class_getitem__(cls, *args, **kwargs):\n 494\t return cls\n 495\t\n 496\t def __and__(self, other):\n 497\t self._check_operator_queryset(other, \"&\")\n 498\t self._merge_sanity_check(other)\n 499\t if isinstance(other, EmptyQuerySet):\n 500\t return other\n 501\t if isinstance(self, EmptyQuerySet):\n 502\t return self\n 503\t combined = self._chain()\n 504\t combined._merge_known_related_objects(other)\n 505\t combined.query.combine(other.query, sql.AND)\n 506\t return combined\n 507\t\n 508\t def __or__(self, other):\n 509\t self._check_operator_queryset(other, \"|\")\n 510\t self._merge_sanity_check(other)\n 511\t if isinstance(self, EmptyQuerySet):\n 512\t return other\n 513\t if isinstance(other, EmptyQuerySet):\n 514\t return self\n 515\t query = (\n 516\t self\n 517\t if self.query.can_filter()\n 518\t else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n 519\t )\n 520\t combined = query._chain()\n 521\t combined._merge_known_related_objects(other)\n 522\t if not other.query.can_filter():\n 523\t other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n 524\t combined.query.combine(other.query, sql.OR)\n 525\t return combined\n 526\t\n 527\t def __xor__(self, other):\n 528\t self._check_operator_queryset(other, \"^\")\n 529\t self._merge_sanity_check(other)\n 530\t if isinstance(self, EmptyQuerySet):\n 531\t return other\n 532\t if isinstance(other, EmptyQuerySet):\n 533\t return self\n 534\t query = (\n 535\t self\n 536\t if self.query.can_filter()\n 537\t else self.model._base_manager.filter(pk__in=self.values(\"pk\"))\n 538\t )\n 539\t combined = query._chain()\n 540\t combined._merge_known_related_objects(other)\n 541\t if not other.query.can_filter():\n 542\t other = other.model._base_manager.filter(pk__in=other.values(\"pk\"))\n 543\t combined.query.combine(other.query, sql.XOR)\n 544\t return combined\n 545\t\n 546\t ####################################\n 547\t # METHODS THAT DO DATABASE QUERIES #\n 548\t ####################################\n 549\t\n 550\t def _iterator(self, use_chunked_fetch, chunk_size):\n 551\t iterable = self._iterable_class(\n 552\t self,\n 553\t chunked_fetch=use_chunked_fetch,\n 554\t chunk_size=chunk_size or 2000,\n 555\t )\n 556\t if not self._prefetch_related_lookups or chunk_size is None:\n 557\t yield from iterable\n 558\t return\n 559\t\n 560\t iterator = iter(iterable)\n 561\t while results := list(islice(iterator, chunk_size)):\n 562\t prefetch_related_objects(results, *self._prefetch_related_lookups)\n 563\t yield from results\n 564\t\n 565\t def iterator(self, chunk_size=None):\n 566\t \"\"\"\n 567\t An iterator over the results from applying this QuerySet to the\n 568\t database. chunk_size must be provided for QuerySets that prefetch\n 569\t related objects. Otherwise, a default chunk_size of 2000 is supplied.\n 570\t \"\"\"\n 571\t if chunk_size is None:\n 572\t if self._prefetch_related_lookups:\n 573\t raise ValueError(\n 574\t \"chunk_size must be provided when using QuerySet.iterator() after \"\n 575\t \"prefetch_related().\"\n 576\t )\n 577\t elif chunk_size <= 0:\n 578\t raise ValueError(\"Chunk size must be strictly positive.\")\n 579\t use_chunked_fetch = not connections[self.db].settings_dict.get(\n 580\t \"DISABLE_SERVER_SIDE_CURSORS\"\n 581\t )\n 582\t return self._iterator(use_chunked_fetch, chunk_size)\n 583\t\n 584\t async def aiterator(self, chunk_size=None):\n 585\t \"\"\"\n 586\t An asynchronous iterator over the results from applying this QuerySet\n 587\t to the database.\n 588\t \"\"\"\n 589\t if chunk_size is None:\n 590\t if self._prefetch_related_lookups:\n 591\t # RemovedInDjango71Warning: Replace the warning with:\n 592\t # raise ValueError(\n 593\t # \"chunk_size must be provided when using \"\n 594\t # \"QuerySet.aiterator() after prefetch_related().\"\n 595\t # )\n 596\t warnings.warn(\n 597\t \"Using QuerySet.aiterator() after prefetch_related() without \"\n 598\t \"providing a chunk_size is deprecated and will raise a \"\n 599\t \"ValueError in Django 7.1.\",\n 600\t category=RemovedInDjango71Warning,\n 601\t skip_file_prefixes=django_file_prefixes(),\n 602\t )\n 603\t # RemovedInDjango71Warning: When the deprecation ends, remove.\n 604\t chunk_size = 2000\n 605\t elif chunk_size <= 0:\n 606\t raise ValueError(\"Chunk size must be strictly positive.\")\n 607\t use_chunked_fetch = not connections[self.db].settings_dict.get(\n 608\t \"DISABLE_SERVER_SIDE_CURSORS\"\n 609\t )\n 610\t iterable = self._iterable_class(\n 611\t self,\n 612\t chunked_fetch=use_chunked_fetch,\n 613\t chunk_size=chunk_size or 2000,\n 614\t )\n 615\t if self._prefetch_related_lookups:\n 616\t results = []\n 617\t\n 618\t async for item in iterable:\n 619\t results.append(item)\n 620\t if len(results) >= chunk_size:\n 621\t await aprefetch_related_objects(\n 622\t results, *self._prefetch_related_lookups\n 623\t )\n 624\t for result in results:\n 625\t yield result\n 626\t results.clear()\n 627\t\n 628\t if results:\n 629\t await aprefetch_related_objects(\n 630\t results, *self._prefetch_related_lookups\n 631\t )\n 632\t for result in results:\n 633\t yield result\n 634\t else:\n 635\t async for item in iterable:\n 636\t yield item\n 637\t\n 638\t def aggregate(self, *args, **kwargs):\n 639\t \"\"\"\n 640\t Return a dictionary containing the calculations (aggregation)\n 641\t over the current queryset.\n 642\t\n 643\t If args is present the expression is passed as a kwarg using\n 644\t the Aggregate object's default alias.\n 645\t \"\"\"\n 646\t if self.query.distinct_fields:\n 647\t raise NotImplementedError(\"aggregate() + distinct(fields) not implemented.\")\n 648\t self._validate_values_are_expressions(\n 649\t (*args, *kwargs.values()), method_name=\"aggregate\"\n 650\t )\n 651\t for arg in args:\n 652\t # The default_alias property raises TypeError if default_alias\n 653\t # can't be set automatically or AttributeError if it isn't an\n 654\t # attribute.\n 655\t try:\n 656\t arg.default_alias\n 657\t except (AttributeError, TypeError):\n 658\t raise TypeError(\"Complex aggregates require an alias\")\n 659\t kwargs[arg.default_alias] = arg\n 660\t\n 661\t return self.query.chain().get_aggregation(self.db, kwargs)\n 662\t\n 663\t async def aaggregate(self, *args, **kwargs):\n 664\t return await sync_to_async(self.aggregate)(*args, **kwargs)\n 665\t\n 666\t def count(self):\n 667\t \"\"\"\n 668\t Perform a SELECT COUNT() and return the number of records as an\n 669\t integer.\n 670\t\n 671\t If the QuerySet is already fully cached, return the length of the\n 672\t cached results set to avoid multiple SELECT COUNT(*) calls.\n 673\t \"\"\"\n 674\t if self._result_cache is not None:\n 675\t return len(self._result_cache)\n 676\t\n 677\t return self.query.get_count(using=self.db)\n 678\t\n 679\t async def acount(self):\n 680\t return await sync_to_async(self.count)()\n 681\t\n 682\t def get(self, *args, **kwargs):\n 683\t \"\"\"\n 684\t Perform the query and return a single object matching the given\n 685\t keyword arguments.\n 686\t \"\"\"\n 687\t if self.query.combinator and (args or kwargs):\n 688\t raise NotSupportedError(\n 689\t \"Calling QuerySet.get(...) with filters after %s() is not \"\n 690\t \"supported.\" % self.query.combinator\n 691\t )\n 692\t clone = self._chain() if self.query.combinator else self.filter(*args, **kwargs)\n 693\t if self.query.can_filter() and not self.query.distinct_fields:\n 694\t clone = clone.order_by()\n 695\t limit = None\n 696\t if (\n 697\t not clone.query.select_for_update\n 698\t or connections[clone.db].features.supports_select_for_update_with_limit\n 699\t ):\n 700\t limit = MAX_GET_RESULTS\n 701\t clone.query.set_limits(high=limit)\n 702\t num = len(clone)\n 703\t if num == 1:\n 704\t return clone._result_cache[0]\n 705\t if not num:\n 706\t raise self.model.DoesNotExist(\n 707\t \"%s matching query does not exist.\" % self.model._meta.object_name\n 708\t )\n 709\t raise self.model.MultipleObjectsReturned(\n 710\t \"get() returned more than one %s -- it returned %s!\"\n 711\t % (\n 712\t self.model._meta.object_name,\n 713\t num if not limit or num < limit else \"more than %s\" % (limit - 1),\n 714\t )\n 715\t )\n 716\t\n 717\t async def aget(self, *args, **kwargs):\n 718\t return await sync_to_async(self.get)(*args, **kwargs)\n 719\t\n 720\t def create(self, **kwargs):\n 721\t \"\"\"\n 722\t Create a new object with the given kwargs, saving it to the database\n 723\t and returning the created object.\n 724\t \"\"\"\n 725\t reverse_one_to_one_fields = frozenset(kwargs).intersection(\n 726\t self.model._meta._reverse_one_to_one_field_names\n 727\t )\n 728\t if reverse_one_to_one_fields:\n 729\t raise ValueError(\n 730\t \"The following fields do not exist in this model: %s\"\n 731\t % \", \".join(reverse_one_to_one_fields)\n 732\t )\n 733\t\n 734\t obj = self.model(**kwargs)\n 735\t self._for_write = True\n 736\t obj.save(force_insert=True, using=self.db)\n 737\t obj._state.fetch_mode = self._fetch_mode\n 738\t return obj\n 739\t\n 740\t create.alters_data = True\n 741\t\n 742\t async def acreate(self, **kwargs):\n 743\t return await sync_to_async(self.create)(**kwargs)\n 744\t\n 745\t acreate.alters_data = True\n 746\t\n 747\t def _prepare_for_bulk_create(self, objs):\n 748\t objs_with_pk, objs_without_pk = [], []\n 749\t for obj in objs:\n 750\t if isinstance(obj.pk, DatabaseDefault):\n 751\t objs_without_pk.append(obj)\n 752\t elif obj._is_pk_set():\n 753\t objs_with_pk.append(obj)\n 754\t else:\n 755\t obj.pk = obj._meta.pk.get_pk_value_on_save(obj)\n 756\t if obj._is_pk_set():\n 757\t objs_with_pk.append(obj)\n 758\t else:\n 759\t objs_without_pk.append(obj)\n 760\t obj._prepare_related_fields_for_save(operation_name=\"bulk_create\")\n 761\t return objs_with_pk, objs_without_pk\n 762\t\n 763\t def _check_bulk_create_options(\n 764\t self, ignore_conflicts, update_conflicts, update_fields, unique_fields\n 765\t ):\n 766\t if ignore_conflicts and update_conflicts:\n 767\t raise ValueError(\n 768\t \"ignore_conflicts and update_conflicts are mutually exclusive.\"\n 769\t )\n 770\t db_features = connections[self.db].features\n 771\t if ignore_conflicts:\n 772\t if not db_features.supports_ignore_conflicts:\n 773\t raise NotSupportedError(\n 774\t \"This database backend does not support ignoring conflicts.\"\n 775\t )\n 776\t return OnConflict.IGNORE\n 777\t elif update_conflicts:\n 778\t if not db_features.supports_update_conflicts:\n 779\t raise NotSupportedError(\n 780\t \"This database backend does not support updating conflicts.\"\n 781\t )\n 782\t if not update_fields:\n 783\t raise ValueError(\n 784\t \"Fields that will be updated when a row insertion fails \"\n 785\t \"on conflicts must be provided.\"\n 786\t )\n 787\n[repowise#aaf472a70919: 600 lines omitted (~6961 tokens); restore: repowise expand aaf472a70919]","truncated":true,"verified":true,"_meta":{"contract_version":2,"timing_ms":50.42,"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"replaced_tokens":29766,"state":{"truncated":true},"response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":22816},"omitted":{"refs":["repowise#aaf472a70919","repowise#9c9e18d5ccad"],"tokens":7089,"restore":"`repowise expand <ref>`, or get_symbol(\"repowise#<ref>\", query=...)"},"completeness":{"capped":true},"tokens_saved":24068},"continuation":"django/db/models/query.py:930-2367","continuation_reference":{"id":"django/db/models/query.py:930-2367","repository":"default","kind":"file_range","path":"django/db/models/query.py","verification_basis":"live","source_kind":"source","range":[930,2367]},"omission_marker":"[repowise#9c9e18d5ccad: 11 lines omitted (~128 tokens); restore: repowise expand 9c9e18d5ccad]"}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/get_why.json b/packages/claude-mod/test/fixtures/flow/get_why.json
new file mode 100644
index 000000000..45e161ec7
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/get_why.json
@@ -0,0 +1 @@
+{"result":{"mode":"search","query":"why is QuerySet lazy","decisions":[],"reason":"No decision record covers this question. The rationale comments below carry its terms. They are quoted from the code and its history, not a ruling: read them as evidence, not as the recorded reason.","code_rationale":[{"path":"django/forms/models.py","lines":[1564,1570],"comment":"Otherwise, execute the QuerySet in self.queryset to determine the choices dynamically. Return a fresh ModelChoiceIterator that has not been consumed. Note that we're instantiating a new ModelChoiceIterator *each* time _get_choices() is called (and, thus, each time self.choices is accessed) so that we can ensure the QuerySet has not been consumed. This construct might look complicated but it allows for lazy evaluation of the queryset.","provenance":"extracted_rationale","evidence_refs":[{"id":"ev_f777c9cdffdc0028cce6","repository":"default","kind":"file_content","path":"django/forms/models.py","line":1564,"content_id":"f4ea3d71bc2e4029ca23","range":[1564,1570],"provenance":"extracted_rationale","source":"live_code_rationale","source_kind":"code_comment","verification":"exact","verification_basis":"live"}]},{"path":"django/core/paginator.py","lines":[320,321],"comment":"The object_list is converted to a list so that if it was a QuerySet it won't be a database hit per __getitem__.","provenance":"extracted_rationale","evidence_refs":[{"id":"ev_7908cb0a3caa60de169b","repository":"default","kind":"file_content","path":"django/core/paginator.py","line":320,"content_id":"f179e54b0ab819dc1b05","range":[320,321],"provenance":"extracted_rationale","source":"live_code_rationale","source_kind":"code_comment","verification":"exact","verification_basis":"live"}]},{"path":"django/db/models/manager.py","lines":[158,163],"comment":"We can't proxy this method through the `QuerySet` like we do for the rest of the `QuerySet` methods. This is because `QuerySet.all()` works by creating a \"copy\" of the current queryset and in making said copy, all the cached `prefetch_related` lookups are lost. See the implementation of `RelatedManager.get_queryset()` for a better understanding of how this comes into play.","provenance":"extracted_rationale","evidence_refs":[{"id":"ev_8aaef556652e1e34f5dc","repository":"default","kind":"file_content","path":"django/db/models/manager.py","line":158,"content_id":"4220a741d81fef4df260","range":[158,163],"provenance":"extracted_rationale","source":"live_code_rationale","source_kind":"code_comment","verification":"exact","verification_basis":"live"}]}],"_meta":{"contract_version":2,"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":3311},"completeness":{"capped":false},"replaced_tokens":3000,"tokens_saved":2188,"timing_ms":1983.1},"answer_basis":"rationale"}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/fixtures/flow/search_codebase.json b/packages/claude-mod/test/fixtures/flow/search_codebase.json
new file mode 100644
index 000000000..4d2e2b1d8
--- /dev/null
+++ b/packages/claude-mod/test/fixtures/flow/search_codebase.json
@@ -0,0 +1 @@
+{"result":{"results":[{"type":"symbol","symbol_id":"django/db/models/query.py::QuerySet::bulk_create","name":"bulk_create","kind":"method","file":"django/db/models/query.py","start_line":817,"end_line":920,"signature":"def bulk_create(\r\n self,\r\n objs,\r\n batch_size=None,\r\n ignore_conflicts=False,\r\n update_conflicts=False,\r\n update_fields=None,\r\n unique_fields=None,\r\n )","qualified_name":"django.db.models.query.QuerySet.bulk_create","language":"python","score":160,"next":"get_symbol"},{"type":"symbol","symbol_id":"django/utils/tree.py::Node::create","name":"create","kind":"method","file":"django/utils/tree.py","start_line":29,"end_line":38,"signature":"def create(cls, children=None, connector=None, negated=False)","qualified_name":"django.utils.tree.Node.create","language":"python","score":55.01,"next":"get_symbol"},{"type":"symbol","symbol_id":"django/db/models/query_utils.py::Q::create","name":"create","kind":"method","file":"django/db/models/query_utils.py","start_line":64,"end_line":66,"signature":"def create(cls, children=None, connector=None, negated=False)","qualified_name":"django.db.models.query_utils.Q.create","language":"python","score":55.01,"next":"get_symbol"},{"type":"symbol","symbol_id":"tests/bulk_create/models.py::Country","name":"Country","kind":"class","file":"tests/bulk_create/models.py","start_line":15,"end_line":26,"signature":"class Country","qualified_name":"bulk_create.models.Country","language":"python","score":55.01,"next":"get_symbol"},{"page_id":"symbol_spotlight:django/db/models/deletion.py::get_del_batches","title":"Symbol: django/db/models/deletion.py::get_del_batches","page_type":"symbol_spotlight","snippet":"# get_del_batches\n\n**Kind:** method | **Defined in:** `django/db/models/deletion.py` | **Estimated complexity:** 2\n\n```\ndef get_del_batches(self, objs, fields)\n```\n\n## Overview\n\nReturn the objs in sui","relevance_score":2.903,"sources":["fts"],"target_path":"django/db/models/deletion.py","symbol_id":"django/db/models/deletion.py::get_del_batches","file":"django/db/models/deletion.py","type":"page"}],"mode":"hybrid","_meta":{"contract_version":2,"index_age_days":0,"indexed_commit":"e78991410b78","live_head":"e78991410b78","index_behind":false,"index_scope":{"version":1,"projection":"compact","run_mode":"standard","content_provenance":"template","git_tier":"full","status":"upgrading","fingerprint":"99c42a358f89","full":"get_overview()","degraded_analyses":["Graph build can take several minutes on a first run. Safe to Ctrl-C — re-run 'repowise init --resume' to continue where it stopped."]},"embedder":"mock","embedder_degraded":false,"semantic_search":false,"response_budget":{"limit_chars":24000,"tier":"default","serialized_chars":3071},"completeness":{"capped":false},"timing_ms":293.09},"candidates":[{"path":"django/db/models/query.py"},{"path":"django/utils/tree.py"},{"path":"django/db/models/query_utils.py"},{"path":"tests/bulk_create/models.py"},{"path":"django/db/models/deletion.py"}],"exact_match":true}}
\ No newline at end of file
diff --git a/packages/claude-mod/test/flow-register.test.ts b/packages/claude-mod/test/flow-register.test.ts
new file mode 100644
index 000000000..5d3bb2a3b
--- /dev/null
+++ b/packages/claude-mod/test/flow-register.test.ts
@@ -0,0 +1,258 @@
+// Flow's wiring through register(): tool.call still returns next(e)'s value
+// untouched while Flow records the call, the review's own result feeds the
+// turn's health, redraws stay under 8 a second, and the owl ticks only while
+// Claude works with Flow on screen.
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+import { REDRAW_MS } from "../src/flow-controller";
+import type { Hook, ModApi, On } from "../src/mod-api";
+import { BLINK_MS } from "../src/views/owl";
+import { buttonsOf, fixture, flatten, textOf } from "./fake-host";
+
+type Hooks = Record<string, Hook<any>>;
+
+async function load(options: Record<string, boolean> = {}): Promise<Hooks> {
+ vi.resetModules();
+ const { register } = await import("../src/register");
+ const hooks: Hooks = {};
+ const on = ((event: string, a: unknown, b?: unknown) => {
+ const m = a as { component?: string; command?: string; element?: string };
+ (hooks as Record<string, unknown>)[b === undefined ? event : `${event}:${m.component ?? m.command ?? m.element}`] = b ?? a;
+ }) as On;
+ register(on, options);
+ return hooks;
+}
+
+function fakeDollar() {
+ const calls = { invalidate: 0, logs: [] as string[] };
+ const $: ModApi = {
+ session: { cwd: async () => "C:\\work\\django" },
+ fs: { read: async () => Promise.reject(new Error("ENOENT")), exists: async () => false },
+ process: { run: async () => ({ exitCode: 1, stdout: "", stderr: "" }) },
+ http: { fetch: async () => ({ status: 500, ok: false, headers: {}, text: "" }) },
+ mcp: { connect: async () => ({ isConnected: false }), call: async () => Promise.reject(new Error("no MCP")) },
+ prompt: { submit: async () => ({}) },
+ ui: {
+ invalidate: () => {
+ calls.invalidate++;
+ },
+ log: (text) => {
+ calls.logs.push(text);
+ },
+ resolve: () => Object.fromEntries(["Box", "Text", "Button", "Input", "Markdown", "Raster"].map((el) => [el, (props: Record<string, unknown>) => ({ el, props })])),
+ open: async () => ({ isPlaced: true }),
+ close: async () => undefined,
+ blit: async () => ({}),
+ },
+ command: { register: async () => ({}) },
+ config: { list: async () => [] },
+ settings: { read: async () => ({}) },
+ };
+ return { $, calls };
+}
+
+const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
+const PANE = { surface: "terminal", requestId: "lens", props: { bodyColumns: 120, placement: "dock", scroll: { bodyRows: 40 } } };
+
+let hooks: Hooks;
+beforeEach(async () => {
+ hooks = await load();
+});
+afterEach(() => {
+ vi.useRealTimers();
+});
+
+async function session() {
+ const d = fakeDollar();
+ await hooks["session.start"]!(d.$, { cwd: "C:\\work\\django" }, async () => undefined);
+ for (let i = 0; i < 4; i++) await settle();
+ return d;
+}
+const pane = (d: { $: ModApi }) => hooks["ui.render:Pane"]!(d.$, PANE, async () => null);
+
+describe("lens_flow off", () => {
+ it("records nothing and Flow leaves the tab bar; tool.call is untouched", async () => {
+ hooks = await load({ lens_flow: false });
+ expect(Object.keys(hooks)).not.toContain("turn.step");
+ const d = await session();
+ expect(buttonsOf(await pane(d)).map((b) => b.props.label)).toEqual(["Map", "Ask", "Recap"]);
+ const out = { text: "x" };
+ expect(await hooks["tool.call"]!(d.$, { tool: "Bash", tool_use_id: "b", command: "ls" }, async () => out)).toBe(out);
+ });
+});
+
+describe("tool.call", () => {
+ const RW = { tool: "mcp__repowise__get_context", tool_use_id: "toolu_rw", targets: ["django/db/models/query.py"] };
+
+ it("returns next(e)'s value untouched; the call and what its reply was built from land in Flow", async () => {
+ const d = await session();
+ await hooks["turn.start"]!(d.$, { text: "<system-reminder>r</system-reminder>add a comment", turnId: "t" }, async () => ({ turnId: "t" }));
+ const out = { ref: 1, result: {}, text: fixture("flow/get_context.json") };
+ expect(await hooks["tool.call"]!(d.$, RW, async () => out)).toBe(out);
+ const shown = textOf(await pane(d)).join("|");
+ expect(shown).toContain("Repowise 1 call");
+ expect(shown).toContain('"add a comment"');
+ expect(shown).toContain("420 ms".slice(0, 0) + "1 target · 1 documentation page");
+ });
+
+ it("the turn's health is the change review's own result: no second get_change_risk", async () => {
+ const risk = { health_delta: { status: "available", introduced: 1, worsened: 0, resolved: 0, top_findings: [{ change: "introduced", biomarker: "complex_method", path: "a.py" }] } };
+ const d = await session();
+ let reviews = 0;
+ d.$.mcp.connect = async () => ({ isConnected: true, server: "plugin:repowise:repowise" });
+ d.$.mcp.call = async (_s, tool) => {
+ if (tool === "get_change_risk") reviews++;
+ return { content: [{ type: "text", text: JSON.stringify({ result: risk }) }], isError: false };
+ };
+ await hooks["session.start"]!(d.$, { cwd: "C:\\work\\django" }, async () => undefined);
+ for (let i = 0; i < 4; i++) await settle();
+ await hooks["turn.start"]!(d.$, { text: "edit", turnId: "t" }, async () => ({}));
+ await hooks["tool.call"]!(d.$, { tool: "Edit", tool_use_id: "e", file_path: "C:\\work\\django\\a.py" }, async () => ({ result: { type: "update" } }));
+ await hooks["turn.complete"]!(d.$, { reason: "answer", answer: "done" }, async () => ({ text: "done" }));
+ await settle();
+ const shown = textOf(await pane(d)).join("|");
+ expect(shown).toContain("this turn introduced 1 finding: complex method in a.py");
+ expect(reviews).toBe(1);
+ });
+
+ it("a call that throws rethrows the same error and shows as failed", async () => {
+ const d = await session();
+ const err = new Error("denied");
+ await expect(hooks["tool.call"]!(d.$, { ...RW, tool_use_id: "bad" }, async () => Promise.reject(err))).rejects.toBe(err);
+ expect(textOf(await pane(d))).toContain("error");
+ });
+
+ it("Lens's own calls are not Claude's steps", async () => {
+ const d = await session();
+ await hooks["tool.call"]!(d.$, { ...RW, tool_use_id: "toolu_plugin_1" }, async () => ({ text: "{}" }));
+ expect(textOf(await pane(d))).not.toContain("get_context");
+ });
+
+ it("a row's press opens its detail; j and k step between calls", async () => {
+ const d = await session();
+ await hooks["tool.call"]!(d.$, RW, async () => ({ text: fixture("flow/get_context.json") }));
+ await hooks["tool.call"]!(d.$, { ...RW, tool_use_id: "toolu_2", tool: "mcp__repowise__get_risk" }, async () => ({ text: fixture("flow/get_risk.json") }));
+ const press = async (label: string) => buttonsOf(await pane(d)).find((b) => b.props.label === label)!.props.onPress();
+ await press("get_context");
+ expect(textOf(await pane(d)).join("|")).toContain("how it was answered");
+ await press("Next call");
+ const shown = textOf(await pane(d)).join("|");
+ expect(shown).toContain("1,849 tokens left out, restorable");
+ await press("Previous call");
+ expect(textOf(await pane(d)).join("|")).toContain("reply 7.4 KB (cap 24,000 characters)");
+ });
+
+ it("turn.complete says how the turn ended: stopped and did not finish in plain words, no thistle", async () => {
+ for (const [reason, word] of [["aborted", "Stopped"], ["error", "Did not finish"], ["answer", "Done"]] as const) {
+ const d = await session();
+ await hooks["turn.start"]!(d.$, { text: "go", turnId: "t" }, async () => ({}));
+ await hooks["turn.complete"]!(d.$, { reason, durationMs: 2_000 }, async () => ({}));
+ const shown = textOf(await pane(d));
+ expect(shown).toContain(`${word} · 2.0 s`);
+ expect(shown.some((t) => t.includes("⚘"))).toBe(reason === "answer");
+ }
+ });
+});
+
+describe("redraws and the owl's clock", () => {
+ const bash = (d: { $: ModApi }, id: string) => hooks["tool.call"]!(d.$, { tool: "Bash", tool_use_id: id, command: "ls" }, async () => ({}));
+
+ it("at most one redraw per 125 ms while Flow is shown; none while another tab is", async () => {
+ const d = await session();
+ vi.useFakeTimers();
+ await pane(d);
+ const before = d.calls.invalidate;
+ for (let i = 0; i < 20; i++) await bash(d, `b${i}`);
+ expect(d.calls.invalidate - before).toBe(1);
+ vi.advanceTimersByTime(REDRAW_MS);
+ expect(d.calls.invalidate - before).toBe(2);
+ vi.advanceTimersByTime(REDRAW_MS * 10);
+ expect(d.calls.invalidate - before).toBe(2);
+ // On the Map tab Flow asks for no redraws.
+ buttonsOf(await pane(d)).find((b) => b.props.label === "Map")!.props.onPress();
+ await pane(d);
+ const onMap = d.calls.invalidate;
+ await bash(d, "late");
+ vi.advanceTimersByTime(REDRAW_MS * 4);
+ expect(d.calls.invalidate).toBe(onMap);
+ });
+
+ it("a closed pane: once redraws go unanswered for a second Flow stops asking, until it is drawn again", async () => {
+ const d = await session();
+ vi.useFakeTimers();
+ await pane(d);
+ const before = d.calls.invalidate;
+ // The call's start redraws at once, its end once the throttle allows.
+ await bash(d, "a");
+ vi.advanceTimersByTime(REDRAW_MS);
+ expect(d.calls.invalidate - before).toBe(2);
+ // No render comes back.
+ vi.advanceTimersByTime(1_000);
+ await bash(d, "b");
+ await bash(d, "c");
+ vi.advanceTimersByTime(1_000);
+ expect(d.calls.invalidate - before).toBe(2);
+ await pane(d);
+ await bash(d, "d");
+ expect(d.calls.invalidate - before).toBe(3);
+ });
+
+ it("ticks while Claude works and renders come back; stops when they do not, and at the turn's end", async () => {
+ const d = await session();
+ vi.useFakeTimers();
+ await hooks["turn.start"]!(d.$, { text: "go", turnId: "t" }, async () => ({}));
+ await pane(d);
+ let n = d.calls.invalidate;
+ vi.advanceTimersByTime(BLINK_MS);
+ expect(d.calls.invalidate).toBe(n + 1);
+ await pane(d);
+ vi.advanceTimersByTime(BLINK_MS);
+ expect(d.calls.invalidate).toBe(n + 2);
+ // No render comes back (the pane closed): within a second the clock stops.
+ vi.advanceTimersByTime(BLINK_MS * 20);
+ const stopped = d.calls.invalidate;
+ expect(stopped - n).toBeLessThanOrEqual(2 + Math.ceil(1_000 / BLINK_MS));
+ vi.advanceTimersByTime(BLINK_MS * 20);
+ expect(d.calls.invalidate).toBe(stopped);
+ await pane(d);
+ await hooks["turn.complete"]!(d.$, { reason: "answer", durationMs: 4_000 }, async () => ({}));
+ await pane(d);
+ n = d.calls.invalidate;
+ vi.advanceTimersByTime(BLINK_MS * 5);
+ expect(d.calls.invalidate).toBe(n);
+ // One redraw when the owl's happy moment ends, then quiet; the status stays.
+ vi.advanceTimersByTime(3_000);
+ expect(d.calls.invalidate).toBe(n + 1);
+ vi.advanceTimersByTime(10_000);
+ expect(d.calls.invalidate).toBe(n + 1);
+ expect(textOf(await pane(d))).toContain("Done · 4.0 s");
+ });
+
+ it("a timer that fails logs it and keeps the runtime clear", async () => {
+ const d = await session();
+ vi.useFakeTimers();
+ await pane(d);
+ await bash(d, "a");
+ d.$.ui.invalidate = () => {
+ throw new Error("gone");
+ };
+ await bash(d, "b");
+ vi.advanceTimersByTime(REDRAW_MS);
+ expect(d.calls.logs).toContain("lens: flow timer failed: Error: gone");
+ });
+
+ it("with reduced motion the owl holds still and the turn's clock ticks once a second", async () => {
+ const d = fakeDollar();
+ d.$.settings.read = async () => ({ prefersReducedMotion: true });
+ await hooks["session.start"]!(d.$, {}, async () => undefined);
+ for (let i = 0; i < 4; i++) await settle();
+ vi.useFakeTimers();
+ await hooks["turn.start"]!(d.$, { text: "go", turnId: "t" }, async () => ({}));
+ await pane(d);
+ const n = d.calls.invalidate;
+ vi.advanceTimersByTime(999);
+ expect(d.calls.invalidate).toBe(n);
+ vi.advanceTimersByTime(1);
+ expect(d.calls.invalidate).toBe(n + 1);
+ expect(flatten(await pane(d)).some((x) => x.el === "Text" && x.props.children?.[0] === "◉")).toBe(true);
+ });
+});
diff --git a/packages/claude-mod/test/flow.test.ts b/packages/claude-mod/test/flow.test.ts
new file mode 100644
index 000000000..60c714db8
--- /dev/null
+++ b/packages/claude-mod/test/flow.test.ts
@@ -0,0 +1,350 @@
+// Flow's model: the activity record, the user's words, bytes per result, "found via",
+// the ring caps, and per-tool reply summaries over replies recorded from
+// `repowise mcp` on an indexed Django copy (test/fixtures/flow).
+import { describe, expect, it } from "vitest";
+import {
+ MAX_ACTIVITIES,
+ MAX_TURNS,
+ activities,
+ activityOf,
+ inFlight,
+ initialFlow,
+ isWorking,
+ openable,
+ pathKey,
+ reduceFlow,
+ repowiseTool,
+ searchHits,
+ shortPath,
+ toolEnded,
+ turnEnd,
+ turnTotals,
+ userWords,
+ visits,
+ type FlowAction,
+ type FlowState,
+} from "../src/model/flow";
+import { EXCERPT_CHARS, PARSE_CHARS, summarizeReply } from "../src/model/replies";
+
+/** A reply body as the server sends it. */
+const body = (tool: string, result: unknown) => summarizeReply(tool, JSON.stringify({ result }));
+import { fixture } from "./fake-host";
+
+const ROOT = "C:\\work\\django";
+const reply = (tool: string) => fixture(`flow/${tool}.json`);
+const run = (actions: FlowAction[], from: FlowState = initialFlow) => actions.reduce(reduceFlow, from);
+
+const call = (tool: string, id: string, args: Record<string, unknown> = {}) => ({ tool, tool_use_id: id, ...args });
+function start(tool: string, id: string, at: number, args: Record<string, unknown> = {}): FlowAction {
+ return { type: "toolStarted", activity: activityOf(call(tool, id, args), at, ROOT)! };
+}
+function end(tool: string, id: string, at: number, outcome: unknown): FlowAction {
+ return toolEnded(call(tool, id), outcome, at, ROOT)!;
+}
+
+describe("reply summaries over recorded replies", () => {
+ it("get_context: targets, documentation, symbols shown of total, hotspots; the index commit and budget", () => {
+ const s = summarizeReply("get_context", reply("get_context"));
+ expect(s.inside).toEqual([
+ { what: "targets", n: 1 },
+ { what: "docs", n: 1 },
+ { what: "symbols", n: 40, of: 180 },
+ { what: "hotspots", n: 1 },
+ ]);
+ expect(s.behind).toMatchObject({ commit: "e78991410b78", ageDays: 0, complete: true, budget: { used: 7566, limit: 24000 }, semantic: false });
+ expect(s.paths).toEqual(["django/db/models/query.py"]);
+ expect(s.bytes).toBe(new TextEncoder().encode(reply("get_context")).length);
+ expect(s.excerpt).toHaveLength(EXCERPT_CHARS);
+ expect(s.error).toBeNull();
+ });
+
+ it("get_risk: dependents, co-change partners, contributors; capped and tokens left out", () => {
+ const s = summarizeReply("get_risk", reply("get_risk"));
+ expect(s.inside).toEqual([
+ { what: "targets", n: 1 },
+ { what: "dependents", n: 12 },
+ { what: "coChange", n: 25 },
+ { what: "contributors", n: 172 },
+ { what: "hotspots", n: 1 },
+ ]);
+ expect(s.behind).toMatchObject({ complete: false, omittedTokens: 1849 });
+ expect(s.paths).toContain("tests/queries/tests.py");
+ });
+
+ it("get_answer: citations, bodies, rationale shown of total, guesses; confidence, grounding, retrieval, why degraded", () => {
+ const s = summarizeReply("get_answer", reply("get_answer"));
+ expect(s.inside).toEqual([
+ { what: "citations", n: 1 },
+ { what: "bodies", n: 1 },
+ { what: "rationale", n: 2, of: 6 },
+ { what: "guesses", n: 3 },
+ ]);
+ expect(s.behind).toMatchObject({ confidence: "medium", grounding: "symbol_body", retrieval: "high", degraded: "no-llm-provider" });
+ });
+
+ it("get_why, search_codebase, get_symbol: their own evidence", () => {
+ expect(summarizeReply("get_why", reply("get_why")).inside).toEqual([
+ { what: "decisions", n: 0 },
+ { what: "rationale", n: 3 },
+ ]);
+ expect(summarizeReply("get_why", reply("get_why")).paths).toEqual(["django/forms/models.py", "django/core/paginator.py", "django/db/models/manager.py"]);
+ expect(summarizeReply("search_codebase", reply("search_codebase")).inside).toEqual([{ what: "results", n: 5 }]);
+ const symbol = summarizeReply("get_symbol", reply("get_symbol"));
+ expect(symbol.inside).toEqual([{ what: "lines", n: 600 }]);
+ expect(symbol.behind).toMatchObject({ verified: true, omittedTokens: 7089 });
+ });
+
+ it("an unknown tool falls back to the reply's own lists; a known tool with nothing it reads does too", () => {
+ const text = JSON.stringify({ result: { findings: [1, 2], files: ["a.py"], _private: [1], empty: [], name: "x" } });
+ expect(summarizeReply("get_dead_code", text).inside).toEqual([
+ { what: "findings", n: 2 },
+ { what: "files", n: 1 },
+ ]);
+ expect(summarizeReply("search_codebase", JSON.stringify({ result: { hits: [1] } })).inside).toEqual([{ what: "hits", n: 1 }]);
+ });
+
+ it("_meta beside the result is read; an error is said", () => {
+ const beside = summarizeReply("get_context", JSON.stringify({ result: { targets: {} }, _meta: { indexed_commit: "abc", index_age_days: 3 } }));
+ expect(beside.behind).toMatchObject({ commit: "abc", ageDays: 3 });
+ expect(summarizeReply("get_context", JSON.stringify({ error: { message: "no index" } })).error).toBe("no index");
+ expect(summarizeReply("get_context", JSON.stringify({ result: { error: "bad target\nmore" } })).error).toBe("bad target");
+ expect(summarizeReply("get_context", JSON.stringify({ result: { _meta: { completeness: { capped: true } } } })).behind.complete).toBe(false);
+ });
+
+ it("text that is not JSON keeps its first line as the error; text too large to parse keeps its size only", () => {
+ const plain = summarizeReply("get_why", "Error: tool failed\nstack");
+ expect(plain).toMatchObject({ parsed: false, error: "Error: tool failed", inside: [], paths: [] });
+ expect(summarizeReply("get_why", " ").error).toBeNull();
+ const big = summarizeReply("get_symbol", JSON.stringify({ result: { source: "x".repeat(PARSE_CHARS) } }));
+ expect(big).toMatchObject({ parsed: false, error: null });
+ expect(big.bytes).toBeGreaterThan(PARSE_CHARS);
+ expect(summarizeReply("get_why", "[1]")).toMatchObject({ parsed: false });
+ });
+
+ it("get_why's commits from the archaeology; a result that is not an object reads as empty", () => {
+ const s = body("get_why", { decisions: [], code_rationale: [{ path: "a\\b.py" }], git_archaeology: { file_commits: [1, 2] } });
+ expect(s).toMatchObject({ paths: ["a/b.py"], inside: [{ what: "decisions", n: 0 }, { what: "rationale", n: 1 }, { what: "commits", n: 2 }] });
+ expect(body("get_context", null).inside).toEqual([{ what: "targets", n: 0 }]);
+ });
+
+ it("the path walk takes cited files and target keys, skips _meta, and stops at its depth", () => {
+ const deep = { a: { b: { c: { d: { e: { f: { g: { path: "too/deep.py" } } } } } } } };
+ const s = body("x", { citations: ["c.py", 3], targets: { "t.py": {} }, _meta: { path: "meta.py" }, deep });
+ expect(s.paths).toEqual(["c.py", "t.py"]);
+ });
+});
+
+describe("activities", () => {
+ it("names Repowise tools from its three server name forms only; everything else by its own name", () => {
+ expect(repowiseTool("mcp__plugin_repowise_repowise__get_context")).toBe("get_context");
+ expect(repowiseTool("mcp__repowise__get_answer")).toBe("get_answer");
+ expect(repowiseTool("mcp__claude_ai_Repowise__get_why")).toBe("get_why");
+ expect(repowiseTool("MCP__REPOWISE__get_risk")).toBe("get_risk");
+ expect(repowiseTool("mcp__github__get_issue")).toBeNull();
+ expect(repowiseTool("mcp__not_repowise_fork__get_context")).toBeNull();
+ expect(repowiseTool("mcp__repowise_clone__get_context")).toBeNull();
+ expect(repowiseTool("Read")).toBeNull();
+ });
+
+ it("a turn's end from turn.complete: an answer, stopped when aborted, did not finish on a refusal or an error", () => {
+ expect(turnEnd("answer", false)).toBe("answer");
+ expect(turnEnd("aborted", true)).toBe("stopped");
+ expect(turnEnd("refusal", false)).toBe("failed");
+ expect(turnEnd("error", false)).toBe("failed");
+ expect(turnEnd(undefined, true)).toBe("stopped");
+ expect(turnEnd(undefined, undefined)).toBe("answer");
+ });
+
+ it("compacts arguments and shows paths relative to the session's directory", () => {
+ const a = activityOf(call("Read", "t1", { file_path: `${ROOT}\\django\\db\\models\\query.py`, limit: 40 }), 5, ROOT)!;
+ expect(a).toMatchObject({ kind: "read", tool: "Read", paths: ["django/db/models/query.py"], args: [["file_path", "django/db/models/query.py"]] });
+ const rw = activityOf(call("mcp__repowise__get_context", "t2", { targets: ["query.py", "base.py"], include: ["callers"] }), 5, ROOT)!;
+ expect(rw).toMatchObject({ kind: "repowise", tool: "get_context", args: [["targets", "query.py, base.py"]] });
+ const other = activityOf(call("Bash", "t3", { command: "npm test", agentId: "sub1", timeout: { s: 5 } }), 5, null)!;
+ expect(other).toMatchObject({ kind: "shell", agentId: "sub1", args: [["command", "npm test"]], command: "npm test", asked: [] });
+ expect(activityOf(call("WebFetch", "w", { url: "https://x" }), 0, null)).toMatchObject({ kind: "other", command: null });
+ // Symbol ids in targets are not files.
+ expect(activityOf(call("mcp__repowise__get_context", "s", { targets: ["a.py::f", `${ROOT}\\b.py`] }), 0, ROOT)!.asked).toEqual(["b.py"]);
+ expect(activityOf(call("Task", "t4", { description: { long: true } }), 0, null)!.args).toEqual([["description", '{"long":true}']]);
+ expect(shortPath("/elsewhere/x.py", "/work/app/")).toBe("/elsewhere/x.py");
+ expect(shortPath("C:\\a\\b.py", null)).toBe("C:/a/b.py");
+ });
+
+ it("an edit's size from its arguments; Lens's own calls and malformed ones are not activities", () => {
+ expect(activityOf(call("Edit", "e", { file_path: "/w/a.py", old_string: "a", new_string: "a\nb" }), 0, "/w")!.lines).toEqual({ delta: 1 });
+ expect(activityOf(call("Write", "w", { file_path: "/w/a.py", content: "a\nb\nc" }), 0, "/w")!.lines).toEqual({ written: 3 });
+ expect(activityOf(call("NotebookEdit", "n", { notebook_path: "/w/a.ipynb" }), 0, "/w")).toMatchObject({ kind: "edit", lines: null, paths: ["a.ipynb"] });
+ expect(activityOf(call("mcp__repowise__get_context", "toolu_plugin_1"), 0, null)).toBeNull();
+ expect(activityOf({ tool: "Read" } as never, 0, null)).toBeNull();
+ expect(toolEnded(call("Read", "toolu_plugin_2"), {}, 0, null)).toBeNull();
+ });
+
+ it("a search's hits: count and names, or the count alone, or nothing", () => {
+ expect(searchHits({ result: { filenames: ["django\\db\\a.py", 3], numFiles: 2 } }, ROOT)).toEqual({ hits: 1, hitPaths: ["django/db/a.py"] });
+ expect(searchHits({ result: { numFiles: 4 } }, ROOT)).toEqual({ hits: 4, hitPaths: [] });
+ expect(searchHits({ result: {} }, ROOT)).toEqual({ hits: null, hitPaths: [] });
+ expect(searchHits(null, ROOT)).toEqual({ hits: null, hitPaths: [] });
+ expect(searchHits({ result: "text" }, ROOT)).toEqual({ hits: null, hitPaths: [] });
+ });
+
+ it("an ending: failure when next(e) threw or said so; a Repowise reply summarized from its text", () => {
+ expect(end("Read", "r", 9, null)).toMatchObject({ isError: true, reply: null });
+ expect(end("Read", "r", 9, { isError: true })).toMatchObject({ isError: true });
+ expect(end("Read", "r", 9, undefined)).toMatchObject({ isError: false });
+ expect(end("mcp__repowise__get_risk", "r", 9, { text: reply("get_risk") })).toMatchObject({ reply: { tool: "get_risk" } });
+ expect(end("mcp__repowise__get_risk", "r", 9, { result: {} })).toMatchObject({ reply: null });
+ });
+});
+
+/** A turn: get_context names query.py, then Claude reads it and edits it, reads another, and greps. */
+function session(): FlowState {
+ return run([
+ { type: "turnStarted", turnId: "t-1", prompt: "add a comment above bulk_create", at: 1_000 },
+ start("mcp__repowise__get_context", "c1", 2_000, { targets: ["django/db/models/query.py"] }),
+ end("mcp__repowise__get_context", "c1", 2_420, { text: reply("get_context") }),
+ start("Read", "r1", 3_000, { file_path: `${ROOT}\\django\\db\\models\\query.py` }),
+ end("Read", "r1", 3_300, {}),
+ start("Read", "r2", 4_000, { file_path: `${ROOT}\\django\\db\\models\\base.py` }),
+ end("Read", "r2", 4_100, {}),
+ start("Grep", "g1", 4_500, { pattern: "bulk_create" }),
+ end("Grep", "g1", 4_600, { result: { filenames: ["django\\db\\models\\query.py", "tests\\bulk_create\\tests.py"] } }),
+ start("Edit", "e1", 5_000, { file_path: `${ROOT}\\django\\db\\models\\query.py`, old_string: "a", new_string: "# c\na" }),
+ end("Edit", "e1", 5_200, {}),
+ { type: "turnEnded", at: 9_000, durationMs: 8_000, end: "answer" },
+ ]);
+}
+
+describe("the user's own words", () => {
+ it("drops injected blocks at the start of a turn's text; nothing typed leaves nothing", () => {
+ const handBack = '<agent-message from="agent-7">[Subagent hand-back] The text below is the report.</agent-message>\nfix the bulk_create comment';
+ expect(userWords(handBack)).toBe("fix the bulk_create comment");
+ expect(userWords('<\\agent-message from=\\"x\\"> [Subagent hand-back] The text below i')).toBe("");
+ expect(userWords("<system-reminder>be brief</system-reminder><task-notification>done</task-notification> hi")).toBe("hi");
+ expect(userWords("<command-name>/lens</command-name><command-args></command-args>")).toBe("");
+ expect(userWords("why does <b>this</b> render?")).toBe("why does <b>this</b> render?");
+ // Trailing and inline blocks go too, and the words either side keep one space.
+ expect(userWords("fix the bulk_create comment\n<system-reminder>be brief</system-reminder>")).toBe("fix the bulk_create comment");
+ expect(userWords("fix <task-notification>done</task-notification> the comment")).toBe("fix the comment");
+ expect(userWords("fix it <system-reminder>never closed")).toBe("fix it");
+ const s = reduceFlow(initialFlow, { type: "turnStarted", turnId: "t", prompt: handBack, at: 0 });
+ expect(s.turns[0]!.prompt).toBe("fix the bulk_create comment");
+ });
+});
+
+describe("the flow reducer", () => {
+ it("a result's bytes are counted from its text, Repowise's from the reply; none without text", () => {
+ expect(end("Read", "r", 1, { text: "héllo" })).toMatchObject({ bytes: 6 });
+ expect(end("Read", "r", 1, { result: {} })).toMatchObject({ bytes: null });
+ });
+
+ it("records the turn in order, with the reply, the bytes each result carried, and the files Repowise named first", () => {
+ const s = session();
+ expect(s.turns).toHaveLength(1);
+ const [t] = s.turns;
+ expect(t).toMatchObject({ seq: 1, turnId: "t-1", prompt: "add a comment above bulk_create", endedAt: 9_000, durationMs: 8_000 });
+ expect(t!.activities.map((a) => [a.kind, a.tool])).toEqual([
+ ["repowise", "get_context"],
+ ["read", "Read"],
+ ["read", "Read"],
+ ["search", "Grep"],
+ ["edit", "Edit"],
+ ]);
+ const [rw, read, other] = t!.activities;
+ expect(rw!.bytes).toBe(new TextEncoder().encode(reply("get_context")).length);
+ expect(rw!.asked).toEqual(["django/db/models/query.py"]);
+ expect(rw!.reply?.inside[0]).toEqual({ what: "targets", n: 1 });
+ expect(read!.namedBy).toEqual({ id: "c1", tool: "get_context", at: 2_420, turn: 1 });
+ expect(other!.namedBy).toBeNull();
+ expect(t!.end).toBe("answer");
+ expect(turnTotals(t!)).toEqual({ repowise: 1, answered: 1, answeredMs: 420, reads: 2, edits: 1, opened: 2, named: 1, editNamed: true });
+ expect(isWorking(s)).toBe(false);
+ });
+
+ it("visits: reads and edits numbered in order, a search's hits share one number", () => {
+ expect(visits(session()).map((v) => [v.path, v.kind, v.order])).toEqual([
+ ["django/db/models/query.py", "read", 1],
+ ["django/db/models/base.py", "read", 2],
+ ["django/db/models/query.py", "search-hit", 3],
+ ["tests/bulk_create/tests.py", "search-hit", 3],
+ ["django/db/models/query.py", "edit", 4],
+ ]);
+ const failed = run([start("Read", "x", 1, { file_path: "/w/a.py" }), end("Read", "x", 2, null), start("Grep", "g", 3), end("Grep", "g", 4, { result: { mode: "content" } })]);
+ expect(visits(failed)).toEqual([]);
+ expect(activities(session())).toHaveLength(5);
+ });
+
+ it("a call before any turn starts one Lens did not see begin; an end for an unknown call changes nothing", () => {
+ const s = run([start("Read", "r", 50, { file_path: "/a.py" })]);
+ expect(s.turns[0]).toMatchObject({ seq: 1, turnId: null, prompt: "", startedAt: 50, endedAt: null });
+ expect(isWorking(s)).toBe(true);
+ expect(reduceFlow(s, end("Read", "zzz", 60, {}))).toBe(s);
+ expect(reduceFlow(initialFlow, { type: "turnEnded", at: 1, durationMs: null, end: "answer" })).toBe(initialFlow);
+ const ended = reduceFlow(s, { type: "turnEnded", at: 80, durationMs: null, end: "answer" });
+ expect(ended.turns[0]!.durationMs).toBe(30);
+ expect(reduceFlow(ended, { type: "turnEnded", at: 99, durationMs: 1, end: "answer" })).toBe(ended);
+ });
+
+ it("keeps six turns and folds older ones into totals; keeps 60 activities a turn and counts the rest", () => {
+ let s = initialFlow;
+ for (let i = 0; i < MAX_TURNS + 2; i++) s = run([{ type: "turnStarted", turnId: `t${i}`, prompt: "p", at: i }, start("mcp__repowise__get_why", `w${i}`, i), start("Read", `r${i}`, i, { file_path: `/f${i}.py` }), { type: "turnEnded", at: i + 1, durationMs: 1, end: "answer" }], s);
+ expect(s.turns.map((t) => t.seq)).toEqual([3, 4, 5, 6, 7, 8]);
+ expect(s.earlier).toEqual({ turns: 2, repowise: 2, reads: 2, edits: 0 });
+ let big = run([{ type: "turnStarted", turnId: "x", prompt: "", at: 0 }]);
+ for (let i = 0; i < MAX_ACTIVITIES + 5; i++) big = reduceFlow(big, start("Bash", `b${i}`, i));
+ expect(big.turns[0]!.activities).toHaveLength(MAX_ACTIVITIES);
+ expect(big.turns[0]!.dropped).toBe(5);
+ });
+
+ it("open rows toggle; j and k step through the Repowise calls", () => {
+ const s = run([start("mcp__repowise__get_why", "a", 1), start("Read", "r", 2, { file_path: "/x" }), start("mcp__repowise__get_risk", "b", 3)]);
+ expect(openable(s)).toEqual(["a", "b"]);
+ expect(reduceFlow(s, { type: "step", by: 1 }).open).toBe("a");
+ expect(reduceFlow(s, { type: "step", by: -1 }).open).toBe("b");
+ const onA = reduceFlow(s, { type: "toggle", id: "a" });
+ expect(onA.open).toBe("a");
+ expect(reduceFlow(onA, { type: "toggle", id: "a" }).open).toBeNull();
+ expect(reduceFlow(onA, { type: "step", by: 1 }).open).toBe("b");
+ expect(reduceFlow(onA, { type: "step", by: -1 })).toBe(onA);
+ expect(reduceFlow(initialFlow, { type: "step", by: 1 })).toBe(initialFlow);
+ });
+
+ it("path keys fold separators and case; a reply naming a path twice keeps its first naming", () => {
+ expect(pathKey(".\\Django\\DB\\query.py")).toBe("django/db/query.py");
+ const twice = run([
+ start("mcp__repowise__get_context", "a", 1),
+ end("mcp__repowise__get_context", "a", 2, { text: reply("get_context") }),
+ start("mcp__repowise__get_risk", "b", 3),
+ end("mcp__repowise__get_risk", "b", 4, { text: reply("get_risk") }),
+ start("mcp__repowise__get_risk", "c", 5),
+ end("mcp__repowise__get_risk", "c", 6, { text: "not json" }),
+ ]);
+ expect(twice.named["django/db/models/query.py"]).toEqual({ id: "a", tool: "get_context", at: 2, turn: 1 });
+ expect(twice.named["tests/queries/tests.py"]).toEqual({ id: "b", tool: "get_risk", at: 4, turn: 1 });
+ });
+
+ it("named first only on an exact repo-relative match; an absolute reply path under the root is made relative", () => {
+ const abs = JSON.stringify({ result: { targets: { [`${ROOT}\\django\\db\\a.py`]: {} }, file: "pkg/b.py" } });
+ const s = run([
+ start("mcp__repowise__get_context", "a", 1),
+ end("mcp__repowise__get_context", "a", 2, { text: abs }),
+ start("Read", "r1", 3, { file_path: `${ROOT}\\django\\db\\a.py` }),
+ // Same tail, other place: not the file the reply named.
+ start("Read", "r2", 4, { file_path: `${ROOT}\\vendor\\pkg\\b.py` }),
+ start("Read", "r3", 5, { file_path: `${ROOT}\\pkg\\b.py` }),
+ start("Read", "r4", 6, { file_path: "D:\\other\\pkg\\b.py" }),
+ ]);
+ expect(s.turns[0]!.activities.slice(1).map((a) => a.namedBy?.id ?? null)).toEqual(["a", null, "a", null]);
+ });
+
+ it("a prompt while the last turn is open closes it as stopped; turn.complete says how a turn ended", () => {
+ const s = run([
+ { type: "turnStarted", turnId: "t1", prompt: "one", at: 0 },
+ { type: "turnStarted", turnId: "t2", prompt: "two", at: 5_000 },
+ { type: "turnEnded", at: 6_000, durationMs: null, end: "failed" },
+ ]);
+ expect(s.turns.map((t) => [t.seq, t.end, t.durationMs])).toEqual([
+ [1, "stopped", 5_000],
+ [2, "failed", 1_000],
+ ]);
+ });
+});
diff --git a/packages/claude-mod/test/flowView.test.ts b/packages/claude-mod/test/flowView.test.ts
new file mode 100644
index 000000000..9143498bd
--- /dev/null
+++ b/packages/claude-mod/test/flowView.test.ts
@@ -0,0 +1,373 @@
+// The Flow tab as element trees: the one-line owl and its states, the theme
+// and its color rules, the copy's units, and each section of the dashboard at
+// wide and narrow widths.
+import { describe, expect, it } from "vitest";
+import { BRAND, DARK, LIGHT } from "@repowise-dev/ui/brand";
+import { activityOf, initialFlow, reduceFlow, toolEnded, type FlowAction, type FlowState } from "../src/model/flow";
+import type { ChangeRisk } from "../src/model/review";
+import { summarizeReply } from "../src/model/replies";
+import type { FileContext } from "../src/model/session";
+import { blastFacts, type BlastResponse } from "../src/model/turnFacts";
+import {
+ FLOW_COPY,
+ answerLine,
+ behindParts,
+ clockText,
+ cochangeLine,
+ durationText,
+ freshnessText,
+ importersLine,
+ insideFact,
+ introducedLine,
+ knowsParts,
+ sizeText,
+ statusLine,
+ testsReachLine,
+ 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 { BLINK_MS, EYES, owl, owlEyes } from "../src/views/owl";
+import { THISTLE, flowTheme, hills, loch } from "../src/views/theme";
+import { fixture } from "./fake-host";
+
+const ROOT = "C:\\work\\django";
+const QUERY = "django/db/models/query.py";
+const DARK_THEME = flowTheme(false);
+const call = (tool: string, id: string, args: Record<string, unknown> = {}) => ({ tool, tool_use_id: id, ...args });
+const start = (tool: string, id: string, at: number, args: Record<string, unknown> = {}): FlowAction => ({
+ type: "toolStarted",
+ activity: activityOf(call(tool, id, args), at, ROOT)!,
+});
+const end = (tool: string, id: string, at: number, outcome: unknown): FlowAction => toolEnded(call(tool, id), outcome, at, ROOT)!;
+const run = (actions: FlowAction[], from: FlowState = initialFlow) => actions.reduce(reduceFlow, from);
+const abs = (rel: string) => `${ROOT}\\${rel.replace(/\//g, "\\")}`;
+
+/** One drawn line per child of the tab's column; rows run their runs together. */
+function line(n: Node): string {
+ if (n.type === "Text") return n.children.join("");
+ // A row's Button has no hotkey and draws its label alone; the bar's draw `j: label`.
+ if (n.type === "Button") return n.props.hotkey === undefined ? n.props.label : `[${n.props.hotkey}: ${n.props.label}]`;
+ if (n.type === "Markdown") return n.props.text;
+ if (n.type !== "Box") return "";
+ return n.children.map(line).join(n.props.flexDirection === "row" ? " ".repeat(n.props.columnGap ?? 0) : "\n");
+}
+const lines = (n: Node): string[] => (n.type === "Box" ? n.children.map(line) : [line(n)]).flatMap((l) => l.split("\n"));
+
+function all(n: Node): Node[] {
+ return n.type === "Box" ? [n, ...n.children.flatMap(all)] : [n];
+}
+const texts = (n: Node) => all(n).filter((x): x is Extract<Node, { type: "Text" }> => x.type === "Text");
+const colored = (n: Node, color: string) => texts(n).filter((x) => x.props.color === color).map(line);
+const strong = (n: Node) => texts(n).filter((x) => x.props.dimColor !== true).map(line);
+
+const CARD: FileContext = { callerFiles: 131, contributors: 172, hotspot: true, recentOwner: { name: "author_two", share: 0.2857 } };
+const view = (s: FlowState, o: Partial<FlowViewInput> = {}) =>
+ flowView(s, { columns: 120, rows: 50, now: 10_000, still: false, mode: "full", contexts: { [QUERY]: CARD }, review: null, ...o });
+const BLAST = JSON.parse(fixture("flow/blast_query.json")) as BlastResponse;
+
+/** A Django turn: get_context names query.py, Claude reads it and a search hit, edits query.py, runs the queries tests, asks get_risk after the edit. */
+function working(): FlowState {
+ return run([
+ { type: "turnStarted", turnId: "t1", prompt: "<system-reminder>x</system-reminder>add a comment above bulk_create", at: 1_000 },
+ start("mcp__repowise__get_context", "c1", 3_000, { targets: [QUERY] }),
+ end("mcp__repowise__get_context", "c1", 3_420, { text: fixture("flow/get_context.json") }),
+ start("Read", "r1", 5_000, { file_path: abs(QUERY) }),
+ end("Read", "r1", 5_100, { text: "x".repeat(12_000) }),
+ start("Grep", "g1", 6_000, { pattern: "bulk_create" }),
+ end("Grep", "g1", 6_100, { result: { filenames: ["django\\db\\models\\base.py"] }, text: "y".repeat(300) }),
+ start("Read", "r2", 6_200, { file_path: abs("django/db/models/base.py") }),
+ end("Read", "r2", 6_300, { text: "z".repeat(8_000) }),
+ start("Edit", "e1", 42_000, { file_path: abs(QUERY), old_string: "a", new_string: "# x\na" }),
+ end("Edit", "e1", 42_100, { text: "ok" }),
+ { type: "blastLanded", path: QUERY, facts: blastFacts(QUERY, BLAST) },
+ start("Bash", "b1", 44_000, { command: "python tests/runtests.py queries" }),
+ end("Bash", "b1", 50_000, { text: "w".repeat(2_048) }),
+ start("mcp__repowise__get_risk", "c2", 50_500, { targets: [QUERY] }),
+ ]);
+}
+const finished = (how: "answer" | "stopped" | "failed" = "answer") =>
+ run([end("mcp__repowise__get_risk", "c2", 51_100, { text: fixture("flow/get_risk.json") }), { type: "turnEnded", at: 52_000, durationMs: 51_000, end: how }], working());
+
+const INTRODUCED = {
+ health_delta: { status: "available", introduced: 1, worsened: 0, resolved: 0, top_findings: [{ change: "introduced", biomarker: "complex_method", path: QUERY }] },
+} as unknown as ChangeRisk;
+
+describe("the owl", () => {
+ it("one line, five cells: eyes say the state, strokes keep the terminal's color, open eyes amber", () => {
+ expect(owl("watching", EYES.open, "#f59520").map(line).join("")).toBe("{◉,◉}");
+ expect(colored({ type: "Box", props: {}, children: owl("asking", EYES.side, "#f59520") }, "#f59520")).toEqual(["◐", "◐"]);
+ const asleep = owl("asleep", EYES.shut, "#f59520");
+ expect(asleep.map(line)).toEqual(["{─,─}"]);
+ expect(asleep[0]).toMatchObject({ props: { dimColor: true } });
+ expect(texts({ type: "Box", props: {}, children: owl("stopped", EYES.still, "#f59520") }).every((t) => t.props.color === undefined)).toBe(true);
+ });
+
+ it("asleep, a slow blink while working (none with reduced motion), aside while Repowise answers, happy, a neutral dot after a stop", () => {
+ expect(owlEyes("asleep", 0, false)).toBe("─");
+ expect(owlEyes("asking", 0, false)).toBe("◐");
+ expect(owlEyes("happy", 0, false)).toBe("^");
+ expect(owlEyes("stopped", 0, false)).toBe("•");
+ expect([0, 8, 9, 10].map((f) => owlEyes("watching", f * BLINK_MS, false))).toEqual(["◉", "◉", "─", "◉"]);
+ expect(owlEyes("watching", 9 * BLINK_MS, true)).toBe("◉");
+ });
+});
+
+describe("the theme and its color rules", () => {
+ it("two accents from the brand ramps: dark by default, the light ramp on a light terminal", () => {
+ expect(flowTheme(false)).toEqual({ plum: DARK.accentSecondary, amber: BRAND.accent });
+ expect(flowTheme(true)).toEqual({ plum: LIGHT.accentSecondary, amber: BRAND.accentTextLight });
+ });
+
+ it("the same hills at any width, and their reflection", () => {
+ expect(hills(12)).toBe("▁▂▃▅▃▂▁▁▂▃▂▁");
+ expect(hills(45)).toHaveLength(45);
+ expect(hills(0)).toBe("");
+ expect(loch(6)).toBe(" ▔▔▀▔▔");
+ expect(THISTLE).toBe("⚘");
+ });
+
+ it("no Flow text sets a background; readable text keeps the terminal's color; only marks take an accent", () => {
+ for (const light of [false, true]) {
+ const theme = flowTheme(light);
+ const states = [initialFlow, working(), finished(), reduceFlow(finished(), { type: "toggle", id: "c1" })];
+ for (const s of states) {
+ const tree = view(s, { light, review: INTRODUCED, mode: "no-index" });
+ for (const t of texts(tree)) expect(t.props).not.toHaveProperty("backgroundColor");
+ const marks = texts(tree).filter((t) => t.props.color !== undefined);
+ for (const m of marks) expect([theme.plum, theme.amber]).toContain(m.props.color);
+ // Marks are short: glyphs, a tool name, the hills; never a sentence.
+ for (const m of marks) expect(line(m).trim().length <= 16 || /^[▁▂▃▄▅█]+$/.test(line(m))).toBe(true);
+ }
+ }
+ });
+});
+
+describe("Flow copy", () => {
+ it("every figure has its unit", () => {
+ expect([clockText(42_000), clockText(-5), clockText(725_000)]).toEqual(["0:42", "0:00", "12:05"]);
+ expect([durationText(420), durationText(2_200), durationText(41_000), durationText(192_000)]).toEqual(["420 ms", "2.2 s", "41 s", "3 min 12 s"]);
+ expect([sizeText(820), sizeText(2_150), sizeText(3 * 1024 * 1024)]).toEqual(["820 B", "2.1 KB", "3.0 MB"]);
+ });
+
+ it("the status and the answer line", () => {
+ expect(statusLine(null, 42_000, 0)).toBe("Working · 0:42");
+ expect(statusLine("answer", 41_000, 1)).toBe("Done · 41 s · edited 1 file");
+ expect(statusLine("stopped", 2_000, 2)).toBe("Stopped · 2.0 s · edited 2 files");
+ expect(statusLine("failed", 900, 0)).toBe("Did not finish · 900 ms");
+ expect(answerLine({ repowise: 3, opened: 4, named: 2, editNamed: true })).toBe(
+ "Repowise 3 calls · Claude opened 4 files, 2 named by Repowise first · edit landed in a file Repowise named",
+ );
+ expect(answerLine({ repowise: 1, opened: 1, named: 0, editNamed: false })).toBe("Repowise 1 call · Claude opened 1 file");
+ expect(answerLine({ repowise: 0, opened: 0, named: 0, editNamed: false })).toBe("No Repowise calls");
+ });
+
+ it("before you accept, said with the server's units and bases", () => {
+ expect(importersLine(12, 1)).toBe("12 direct importers; Claude opened 1");
+ expect(importersLine(1, 0)).toBe("1 direct importer; Claude opened none");
+ expect(cochangeLine([{ path: "tests/queries/tests.py", score: 0.8024 }])).toBe("not opened, usually changes with it (co-change score): tests/queries/tests.py 0.80");
+ expect(testsReachLine(17, "inferred", 0, "query.py")).toBe("17 test files reach query.py (inferred); none run");
+ expect(testsReachLine(1, "measured", 1, "a.py")).toBe("1 test file reach a.py (measured); 1 run");
+ expect(introducedLine(1, { biomarker: "complex_method", path: QUERY })).toBe("this turn introduced 1 finding: complex method in query.py");
+ expect(introducedLine(2, null)).toBe("this turn introduced 2 findings");
+ });
+
+ it("what the index knows of a file, and how fresh a reply's index was", () => {
+ expect(knowsParts(CARD)).toEqual(["hotspot", "131 files use it", "recent owner author_two 29 %"]);
+ expect(knowsParts({ callerFiles: 1, hotspot: false, recentOwner: null })).toEqual(["1 file uses it"]);
+ expect(knowsParts({ callerFiles: 0, hotspot: null, recentOwner: null })).toEqual([]);
+ expect(freshnessText({ indexBehind: false, ageDays: 0 })).toBe("index current");
+ expect(freshnessText({ indexBehind: true, ageDays: 3 })).toBe("index behind HEAD");
+ expect(freshnessText({ indexBehind: null, ageDays: 3 })).toBe("index 3 days old");
+ expect(freshnessText({ indexBehind: null, ageDays: null })).toBeNull();
+ });
+
+ it("earlier turns in one line; contains facts with their unit; how it was answered says only what the reply said", () => {
+ const t = { repowise: 2, reads: 3, edits: 0 };
+ expect(turnFooter(2, 41_000, t)).toBe("Turn 2 · 41 s · 2 Repowise calls · 3 files read · 0 edited");
+ expect(turnFooter(2, null, t, "stopped")).toBe("Turn 2 · stopped · 2 Repowise calls · 3 files read · 0 edited");
+ expect(turnFooter(2, 1_000, t, null)).toBe("Turn 2 · 1.0 s · 2 Repowise calls · 3 files read · 0 edited");
+ expect(insideFact({ what: "symbols", n: 40, of: 180 })).toBe("40 of 180 symbols");
+ expect(insideFact({ what: "dead_files", n: 3 })).toBe("3 dead files");
+ const risk = summarizeReply("get_risk", fixture("flow/get_risk.json"));
+ expect(behindParts(risk.behind, risk.bytes)).toEqual([
+ "indexed at e78991410b78",
+ "index 0 days old",
+ "partial: the server capped it",
+ "reply 3.6 KB (cap 24,000 characters)",
+ "1,849 tokens left out, restorable",
+ "semantic search off",
+ ]);
+ expect(behindParts(risk.behind)).toContain("reply 3,715 characters (cap 24,000 characters)");
+ const symbol = summarizeReply("get_symbol", fixture("flow/get_symbol.json")).behind;
+ expect(behindParts(symbol)).toContain("verified against the code");
+ expect(behindParts({ ...symbol, verified: false })).toContain("not verified");
+ const answer = summarizeReply("get_answer", fixture("flow/get_answer.json")).behind;
+ expect(behindParts(answer)).toEqual(expect.arrayContaining(["confidence medium", "grounding symbol body", "retrieval high", "degraded: no-llm-provider"]));
+ });
+});
+
+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);
+ 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");
+ expect(shown.slice(2, 4).every((l) => l.length <= 76)).toBe(true);
+ expect(lines(view(initialFlow, { mode: "no-cli" }))).toContain(FLOW_COPY.notConnected);
+ expect(flowPresses(initialFlow)).toEqual([[FLOW_NEXT, null], [FLOW_PREV, null]]);
+ });
+
+ it("while Claude works: the owl and status, the answer at full strength, the user's own words dim, three lines in all", () => {
+ const tree = view(working(), { now: 1_000 + 52 * 1_000 });
+ const shown = lines(tree);
+ expect(shown[1]).toBe("{◐,◐} Working · 0:52 · edited 1 file");
+ expect(shown[2]).toBe("Repowise 2 calls · Claude opened 2 files, 1 named by Repowise first · edit landed in a file Repowise named");
+ expect(strong(tree)).toContain(shown[2]);
+ expect(shown[3]).toBe('"add a comment above bulk_create"');
+ expect(strong(tree)).not.toContain(shown[3]);
+ expect(shown[4]).toBe(FLOW_COPY.beforeAccept);
+ });
+
+ it("before you accept: per edited file what it reaches that Claude did not look at, as of the last index; the turn's health", () => {
+ const shown = lines(view(finished(), { review: INTRODUCED }));
+ const at = shown.indexOf(FLOW_COPY.beforeAccept);
+ expect(shown[at + 1]).toMatch(/^ {2}django\/db\/models\/query\.py {2}as of the last index$/);
+ // base.py, which Claude read, is one of the importers.
+ expect(shown[at + 2]).toBe(" 12 direct importers; Claude opened 1");
+ expect(shown[at + 3]).toMatch(/^ {4}not opened, usually changes with it \(co-change score\): tests\/queries\/tests\.py 0\.80, /);
+ expect(shown[at + 4]).toMatch(/^ {4}17 test files reach query\.py \(inferred\); \d+ run$/);
+ expect(shown[at + 5]).toBe(" this turn introduced 1 finding: complex method in query.py");
+ const partly = { health_delta: { status: "partial", introduced: 0, top_findings: [] } } as unknown as ChangeRisk;
+ expect(lines(view(finished(), { review: partly }))).toContain(` health compared in part only; no new findings in the part compared`);
+ const clean = { health_delta: { status: "available", introduced: 0, top_findings: [] } } as unknown as ChangeRisk;
+ expect(lines(view(finished(), { review: clean })).some((l) => l.includes("introduced"))).toBe(false);
+ expect(lines(view(finished(), { review: {} as ChangeRisk })).some((l) => l.includes("introduced"))).toBe(false);
+ });
+
+ it("nothing to flag: no BEFORE YOU ACCEPT section at all", () => {
+ const reads = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }, start("Read", "r", 1, { file_path: abs(QUERY) }), end("Read", "r", 2, { text: "x" })]);
+ expect(lines(view(reads))).not.toContain(FLOW_COPY.beforeAccept);
+ });
+
+ it("the working set: edited first, then reads, how Claude came to each, and what the index knows", () => {
+ const tree = view(finished());
+ const shown = lines(tree);
+ const at = shown.indexOf(`${FLOW_COPY.workingSet} · ${FLOW_COPY.asOfIndex}`);
+ expect(shown[at + 1]).toBe(" django/db/models/query.py edited get_context hotspot · 131 files use it · recent owner author_two 29 %");
+ expect(shown[at + 2]).toBe(" django/db/models/base.py read search ");
+ expect(colored(tree, DARK_THEME.plum)).toContain("get_context ");
+ const narrow = lines(view(finished(), { columns: 70 }));
+ expect(narrow.find((l) => l.startsWith(" django/db/models/query.py edited"))).toBe(" django/db/models/query.py edited get_context ");
+ });
+
+ it("the working set caps its rows and says how many more", () => {
+ let s = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }]);
+ for (let i = 0; i < 9; i++) s = run([start("Read", `r${i}`, i, { file_path: abs(`f${i}.py`) }), end("Read", `r${i}`, i, { text: "x" })], s);
+ const shown = lines(view(s));
+ expect(shown.filter((l) => /^ {2}f\d\.py/.test(l))).toHaveLength(6);
+ expect(shown).toContain(" +3 more");
+ expect(shown.find((l) => l.startsWith(" f0.py"))).toBe(" f0.py read direct ");
+ });
+
+ it("context: one bar of measured bytes by kind, shades not colors, a legend with sizes, and the first edit", () => {
+ const tree = view(finished());
+ const shown = lines(tree);
+ const at = shown.indexOf(FLOW_COPY.context);
+ expect(shown[at + 1]).toMatch(/^ {2}█+▓+▒+░+·$/);
+ expect(shown[at + 2]).toMatch(/^ {2}█ Repowise \d+\.\d KB {2}▓ file reads 19\.5 KB {2}▒ search 300 B {2}░ shell 2\.0 KB {2}· other 2 B {2}first edit after 41 s$/);
+ expect(colored(tree, DARK_THEME.plum).some((t) => /^█+$/.test(t))).toBe(true);
+ const nothing = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }]);
+ expect(lines(view(nothing))).not.toContain(FLOW_COPY.context);
+ });
+
+ it("Repowise calls: one line each with time, tool, target, latency and what the reply was built from; the call in flight marked", () => {
+ const tree = view(working());
+ const shown = lines(tree);
+ const at = shown.indexOf(FLOW_COPY.calls);
+ expect(shown[at + 1]).toMatch(/^ {2}0:02 {2}get_context {2}django\/db\/models\/query\.py +420 ms · 1 target · 1 documentation page · index current$/);
+ expect(shown[at + 1]).toHaveLength(120);
+ expect(shown[at + 2]).toMatch(/^▸ 0:49 {2}get_risk {2}django\/db\/models\/query\.py +asking\.\.\.$/);
+ expect(colored(tree, DARK_THEME.amber)).toContain(`${ACTIVE_MARK} `);
+ expect(all(tree).find((n) => n.type === "Button" && n.props.label === "get_context")).toMatchObject({ props: { key: rowKey("c1") } });
+ expect(shown.at(-1)).toBe("[j: Next call] [k: Previous call]");
+ });
+
+ it("a call about a file Claude had already edited says, dim and plain, that its answer came from the index before the edit", () => {
+ const tree = view(finished());
+ const row = lines(tree).find((l) => l.includes("get_risk"))!;
+ expect(row).toContain("from the index before this edit");
+ expect(lines(tree).find((l) => l.includes("get_context django"))).not.toContain("before this edit");
+ const note = texts(tree).find((t) => line(t).includes("from the index before this edit"))!;
+ expect(note.props).toEqual({ dimColor: true });
+ const open = lines(view(reduceFlow(finished(), { type: "toggle", id: "c2" }), { columns: 90 }));
+ expect(open.find((l) => l.includes("how it was answered"))).toMatch(/how it was answered from the index before this edit · indexed at e78991410b78/);
+ });
+
+ it("an open call: how it was answered, its first characters, and what Claude then opened", () => {
+ const shown = lines(view(reduceFlow(finished(), { type: "toggle", id: "c1" })));
+ const at = shown.findIndex((l) => l.includes("how it was answered"));
+ // Its parts wrap at the pane's width rather than being cut.
+ expect(shown.slice(at, at + 2)).toEqual([
+ " how it was answered indexed at e78991410b78 · index 0 days old · reply 7.4 KB (cap 24,000 characters)",
+ " semantic search off",
+ ]);
+ expect(shown[at + 2]).toMatch(/^ {8}reply begins {8}\{"result":\{"targets":/);
+ expect(shown[at + 3]).toBe(` Claude then opened ${QUERY}`);
+ const lone = run([start("mcp__repowise__get_why", "w", 1), end("mcp__repowise__get_why", "w", 2, { text: "{}" }), { type: "toggle", id: "w" }]);
+ expect(lines(view(lone)).find((l) => l.includes("Claude then opened"))).toContain(FLOW_COPY.nothingOpened);
+ const waiting = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }, start("mcp__repowise__get_why", "x", 1), { type: "toggle", id: "x" }]);
+ expect(lines(view(waiting)).some((l) => l.includes("how it was answered"))).toBe(false);
+ });
+
+ it("done: the owl happy for a moment, then asleep; the status stays; a thistle and the loch", () => {
+ const happy = lines(view(finished(), { now: 52_000 + HAPPY_MS - 1 }));
+ expect(happy[1]).toBe("{^,^} Done · 51 s · edited 1 file ⚘");
+ const later = lines(view(finished(), { now: 52_000 + 60 * 60_000 }));
+ expect(later[1]).toBe("{─,─} Done · 51 s · edited 1 file ⚘");
+ expect(later).toContain(loch(120));
+ });
+
+ it("stopped or not finished: plain words, a neutral owl, no thistle, no loch", () => {
+ for (const [how, word] of [["stopped", "Stopped"], ["failed", "Did not finish"]] as const) {
+ const shown = lines(view(finished(how), { now: 52_001 }));
+ expect(shown[1]).toBe(`{•,•} ${word} · 51 s · edited 1 file`);
+ expect(shown.join("\n")).not.toContain(THISTLE);
+ expect(shown).not.toContain(loch(120));
+ }
+ });
+
+ it("subagent calls and failed calls say so", () => {
+ const s = run([
+ { type: "turnStarted", turnId: "t", prompt: "", at: 0 },
+ start("mcp__repowise__get_why", "w", 1_000, { query: "q", agentId: "sub-1" }),
+ end("mcp__repowise__get_why", "w", 2_000, null),
+ ]);
+ expect(lines(view(s)).find((l) => l.includes("get_why"))).toMatch(/get_why {2}q {2}subagent +error$/);
+ });
+
+ it("too many calls: the newest stay, or the open call's, with the calls above and below counted; earlier turns one line each", () => {
+ let s = initialFlow;
+ for (let t = 0; t < 8; t++) {
+ s = run([{ type: "turnStarted", turnId: `t${t}`, prompt: `turn ${t}`, at: t * 100_000 }], s);
+ for (let i = 0; i < 12; i++) s = reduceFlow(s, start("mcp__repowise__get_why", `w${t}-${i}`, t * 100_000 + i * 1_000, { query: `q${i}` }));
+ s = reduceFlow(s, { type: "turnEnded", at: t * 100_000 + 50_000, durationMs: 50_000, end: t === 6 ? "stopped" : "answer" });
+ }
+ const shown = lines(view(s, { rows: 22, now: 10_000_000 }));
+ expect(shown.find((l) => l.includes("hidden"))).toMatch(/^\d+ earlier calls hidden · j \/ k step through calls$/);
+ expect(shown.some((l) => l.includes("q11"))).toBe(true);
+ expect(shown).toContain(" Turn 7 · stopped · 50 s · 12 Repowise calls · 0 files read · 0 edited");
+ expect(shown).toContain(" Earlier: 2 turns · 24 Repowise calls · 0 files read · 0 edited");
+ const around = lines(view(reduceFlow(s, { type: "toggle", id: "w7-0" }), { rows: 22, now: 10_000_000 }));
+ expect(around.some((l) => l.includes("q0"))).toBe(true);
+ expect(around.some((l) => l.includes("q11"))).toBe(false);
+ expect(around.find((l) => l.includes("later call"))).toMatch(/^\d+ later calls below · j \/ k step through calls$/);
+ });
+
+ it("says how many steps of a long turn were not kept", () => {
+ let s = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }]);
+ for (let i = 0; i < 65; i++) s = reduceFlow(s, start("mcp__repowise__get_why", `b${i}`, i, { query: `c${i}` }));
+ expect(lines(view(s, { rows: 200 }))).toContain(" 5 earlier steps of this turn not kept");
+ });
+});
diff --git a/packages/claude-mod/test/map-register.test.ts b/packages/claude-mod/test/map-register.test.ts
index ff4aa5cf3..85405f322 100644
--- a/packages/claude-mod/test/map-register.test.ts
+++ b/packages/claude-mod/test/map-register.test.ts
@@ -4,6 +4,8 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
import type { Hook, ModApi, On, PluginOptions } from "../src/mod-api";
import { MAP_COPY, PANE_COPY } from "../src/views/copy";
+import { DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
+import { decode } from "./django";
import { fixture, flatten, textOf, type Tree } from "./fake-host";
type Hooks = Record<string, Hook<any>>;
@@ -95,6 +97,7 @@ function fakeDollar() {
return { command: c.name };
},
},
+ config: { list: async () => [] },
settings: { read: async () => ({}) },
};
const hold = () => {
@@ -174,7 +177,7 @@ describe("register, for the map", () => {
const { $, calls } = fakeDollar();
await hooks["session.start"]!($, {}, async () => undefined);
expect(calls.commands).toEqual([
- { name: "lens", description: PANE_COPY.command, argumentHint: "[map | ask <question> | recap]", immediate: true },
+ { name: "lens", description: PANE_COPY.command, argumentHint: "[flow | map | ask <question> | recap]", immediate: true },
]);
});
});
@@ -194,7 +197,7 @@ async function started(d: Full = fullDollar()): Promise<Full> {
async function opened(d: Full = fullDollar()): Promise<Full> {
await started(d);
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({ text: "core" }));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({ text: "core" }));
await until(() => asked(d, "/health/map?cap=4000") > 0);
await settle();
await settle();
@@ -206,25 +209,40 @@ const render = async (d: Full) => (await hooks["ui.render:Pane"]!(d.$, pane(), a
describe("the map pane", () => {
it("/lens opens the pane with the keyboard (it was asked for) and prints nothing", async () => {
const d = await started();
- expect(await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({ text: "core" }))).toEqual({});
+ expect(await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({ text: "core" }))).toEqual({});
expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29, focus: true }]);
});
it("/lens on a surface that cannot place the pane says why in one band line", async () => {
const d = await started();
d.$.ui.open = async () => ({ isPlaced: false, reason: "below 110 columns (90 now)" });
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
const shown = JSON.stringify(await hooks["ui.render:AbovePrompt"]!(d.$, band, async () => null));
expect(shown).toContain("Lens map needs a wider terminal: below 110 columns (90 now)");
});
+ it("the map is quiet ghost tiles until the Health colours button turns the bands on; lens_map_health starts it on", async () => {
+ const d = await opened();
+ const bands = (tree: Tree) => decode(String(flatten(tree).find((n) => n.el === "Raster")!.props.cells)).some((w, i) => i % 3 === 1 && w === parseInt(DARK_CANVAS_BAND.good.slice(1), 16));
+ let tree = await render(d);
+ expect(bands(tree)).toBe(false);
+ const toggle = flatten(tree).find((n) => n.props.key === "lens-map-health")!;
+ expect(toggle.props.label).toBe(MAP_COPY.healthOff);
+ toggle.props.onPress();
+ tree = await render(d);
+ expect(bands(tree)).toBe(true);
+ expect(flatten(tree).find((n) => n.props.key === "lens-map-health")!.props.label).toBe(MAP_COPY.healthOn);
+ hooks = await load({ lens_map_health: true });
+ expect(bands(await render(await opened()))).toBe(true);
+ });
+
it("draws the Django map with a legend that counts what it drew", async () => {
const d = await opened();
const tree = await render(d);
const r = flatten(tree).find((n) => n.el === "Raster")!;
- // The pane's 55 rows less the tab row and the legend.
- expect(r.props).toMatchObject({ key: "lens-map", columns: 180, rows: 48 });
- expect(r.props.cells).toHaveLength(180 * 48 * 16);
+ // The pane's 55 rows less the tab row and the rows under the map (story, scope, toggle).
+ expect(r.props).toMatchObject({ key: "lens-map", columns: 180, rows: 47 });
+ expect(r.props.cells).toHaveLength(180 * 47 * 16);
expect(textOf(tree).some((t) => /^1,\d{3} of 2,970 files drawn at this size/.test(t))).toBe(true);
});
@@ -234,7 +252,7 @@ describe("the map pane", () => {
const drawing = flatten(tree).find((n) => n.el === "Svg")!;
expect(String(drawing.props.source).startsWith("<svg ")).toBe(true);
expect(String(drawing.props.source).length).toBeLessThan(131_072);
- expect(drawing.props.alt).toMatch(/^Code health map: 1,\d{3} files drawn/);
+ expect(drawing.props.alt).toMatch(/^Map of the repo: 1,\d{3} files drawn as tiles/);
expect(flatten(tree).some((n) => n.el === "Raster")).toBe(false);
expect(textOf(tree).some((t) => / of 2,970 files drawn at this size/.test(t))).toBe(true);
});
@@ -245,7 +263,7 @@ describe("the map pane", () => {
await wait(30);
expect([asked(d, "/health/map"), asked(d, "/blast-radius")]).toEqual([0, 0]);
// Asked for later, the map fetches the importers of the edit it missed.
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await until(() => asked(d, "/blast-radius") === 1);
});
@@ -254,14 +272,87 @@ describe("the map pane", () => {
await render(d);
await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
await until(() => d.calls.blit.length >= 2);
- expect(d.calls.blit[0]).toMatchObject({ requestId: "lens", key: "lens-map", columns: 180, rows: 48 });
+ expect(d.calls.blit[0]).toMatchObject({ requestId: "lens", key: "lens-map", columns: 180, rows: 47 });
const shown = textOf(await render(d));
- // At 180x48 one of the twelve is under a pixel: counted, not hidden.
- expect(shown).toContain("edited query.py · 12 files import it (from imports, not calls) · 1 not drawn");
- expect(shown).toContain("1 file read");
+ expect(shown.some((t) => t.startsWith("12 importers: "))).toBe(true);
+ expect(shown).toContain("◉ query.py");
expect(asked(d, "/blast-radius")).toBe(1);
});
+ /** A turn that edits query.py, drawn: the prompt on Flow, the edit and its importers on the map. */
+ async function editedTurn(): Promise<Full> {
+ const d = await opened();
+ await hooks["turn.start"]!(d.$, { text: "tidy the bulk create path", turnId: "t1" }, async () => ({}));
+ await render(d);
+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
+ await until(() => asked(d, "/blast-radius") === 1);
+ await settle();
+ expect(textOf(await render(d)).some((t) => t.startsWith("12 importers: "))).toBe(true);
+ return d;
+ }
+ const lens = (d: Full, args: string) => hooks["command.run:lens"]!(d.$, { command: "lens", args }, async () => ({}));
+ const flowText = async (d: Full) => {
+ await lens(d, "flow");
+ return JSON.stringify(await render(d));
+ };
+
+ it("/clear starts the conversation over: Flow and the map's lighting go, the health map stays and is not asked again", async () => {
+ const d = await editedTurn();
+ expect(await flowText(d)).toContain("tidy the bulk create path");
+ await hooks["session.end"]!(d.$, { reason: "clear", sessionId: "s1" }, async () => ({}));
+ expect(await flowText(d)).not.toContain("tidy the bulk create path");
+ await lens(d, "map");
+ const tree = await render(d);
+ expect(flatten(tree).some((n) => n.el === "Raster")).toBe(true);
+ const shown = textOf(tree);
+ expect(shown).toContain(MAP_COPY.quiet);
+ expect(shown.some((t) => t.includes("importers") || t.includes("query.py"))).toBe(false);
+ expect(asked(d, "/health/map")).toBe(1);
+ expect(d.calls.logs.filter((l) => /clear failed|render failed/.test(l))).toEqual([]);
+ });
+
+ it("an end that is not a /clear (a resume, an exit) leaves the turn lit", async () => {
+ const d = await editedTurn();
+ await hooks["session.end"]!(d.$, { reason: "resume", sessionId: "s1" }, async () => ({}));
+ expect(textOf(await render(d)).some((t) => t.startsWith("12 importers: "))).toBe(true);
+ expect(await flowText(d)).toContain("tidy the bulk create path");
+ });
+
+ it("Flow reads the same blast radius answer: its importers before you accept, with no second request", async () => {
+ const d = await opened();
+ await render(d);
+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
+ await until(() => d.calls.blit.length >= 2);
+ flatten(await render(d)).find((n) => n.props.key === "lens-tab-flow")!.props.onPress();
+ const shown = textOf(await render(d));
+ expect(shown).toContain("BEFORE YOU ACCEPT");
+ expect(shown).toContain(" 12 direct importers; Claude opened none");
+ expect(asked(d, "/blast-radius")).toBe(1);
+ });
+
+ it("importers are asked once per edited file: five edits to one file, one request; a second file, a second", async () => {
+ const d = await opened();
+ for (let i = 0; i < 5; i++) await hooks["tool.call"]!(d.$, { ...editQuery, tool_use_id: `toolu_q${i}` }, async () => ({ result: {} }));
+ await until(() => asked(d, "/blast-radius") === 1);
+ await wait(30);
+ expect(asked(d, "/blast-radius")).toBe(1);
+ const editBase = { tool: "Edit", tool_use_id: "toolu_b", file_path: `${ROOT}\\django\\db\\models\\base.py` };
+ await hooks["tool.call"]!(d.$, editBase, async () => ({ result: {} }));
+ await hooks["tool.call"]!(d.$, { ...editBase, tool_use_id: "toolu_b2" }, async () => ({ result: {} }));
+ await until(() => asked(d, "/blast-radius") === 2);
+ await wait(30);
+ expect(asked(d, "/blast-radius")).toBe(2);
+ });
+
+ it("edits before the first /lens are each asked for when it opens", async () => {
+ const d = await started();
+ await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
+ await hooks["tool.call"]!(d.$, { tool: "Edit", tool_use_id: "toolu_b", file_path: `${ROOT}\\django\\db\\models\\base.py` }, async () => ({ result: {} }));
+ expect(asked(d, "/blast-radius")).toBe(0);
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
+ await until(() => asked(d, "/blast-radius") === 2);
+ });
+
it("observing a tool call waits on nothing once next(e) resolved", async () => {
const d = await opened();
d.$.session.cwd = () => new Promise(() => {});
@@ -326,27 +417,34 @@ describe("the map pane", () => {
d.$.settings.read = async () => ({ prefersReducedMotion: true });
await opened(d);
await render(d);
- await hooks["tool.call"]!(d.$, { tool: "Grep", pattern: "x" }, async () => ({ result: { filenames: ["django/db/models/query.py"] } }));
+ await hooks["tool.call"]!(d.$, { tool: "Grep", tool_use_id: "toolu_g", pattern: "x" }, async () => ({ result: { filenames: ["django/db/models/query.py"] } }));
await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
await until(() => asked(d, "/blast-radius") === 1);
await wait(120);
expect(d.calls.blit).toEqual([]);
- expect(textOf(await render(d))).toContain("1 file read · last search matched 1 file");
+ expect(textOf(await render(d))).toContain("x: 1 file");
});
it("an edit with no local server asks nothing of the network", async () => {
const d = fakeDollar();
await hooks["session.start"]!(d.$, { cwd: "/work/app" }, async () => undefined);
await settle();
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await hooks["tool.call"]!(d.$, { tool: "Edit", file_path: "/work/app/a.py" }, async () => ({ result: {} }));
expect(d.calls.http).toEqual([]);
});
+ /** Flow is the first tab: press Map on the drawn tab bar. */
+ async function showMap($: ModApi): Promise<void> {
+ const tabs = flatten(await hooks["ui.render:Pane"]!($, pane(), async () => THEIRS)).filter((n) => n.el === "Button");
+ tabs.find((b) => b.props.key === "lens-tab-map")!.props.onPress();
+ }
+
it("says why when there is no map: no local server, or another surface", async () => {
const lite = fakeDollar();
await hooks["session.start"]!(lite.$, {}, async () => undefined);
await settle();
+ await showMap(lite.$);
const tree = (await hooks["ui.render:Pane"]!(lite.$, pane(), async () => THEIRS)) as Tree;
expect(textOf(tree)).toEqual(["index this repo for Lens: repowise init --no-prose --yes"]);
const vscode = (await hooks["ui.render:Pane"]!(lite.$, pane("lens", "vscode"), async () => THEIRS)) as Tree;
@@ -355,6 +453,7 @@ describe("the map pane", () => {
it("before discovery lands, the pane says it is looking", async () => {
const { $ } = fakeDollar();
+ await showMap($);
expect(textOf((await hooks["ui.render:Pane"]!($, pane(), async () => THEIRS)) as Tree)).toEqual([MAP_COPY.looking]);
});
@@ -367,11 +466,11 @@ describe("the map pane", () => {
return fetch(url, init);
};
await started(d);
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await until(() => mapCalls === 1);
await settle();
expect(textOf(await render(d))).toEqual([MAP_COPY.failed]);
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await until(() => mapCalls === 2);
});
@@ -387,7 +486,7 @@ describe("the map pane", () => {
it("loaded mid-session: learns the cwd from the first call and observes from the next", async () => {
const d = await started();
await hooks["session.start"]!(d.$, {}, async () => undefined);
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
await settle();
await hooks["tool.call"]!(d.$, editQuery, async () => ({ result: {} }));
@@ -421,11 +520,14 @@ describe("auto-open", () => {
// Never the keyboard: the person did not ask for it.
expect(d.calls.open).toEqual([{ id: "lens", title: "Lens", rows: 29 }]);
await until(() => asked(d, "/health/map") === 1);
+ // It opens to the map, not to Flow.
+ const shown = await hooks["ui.render:Pane"]!(d.$, pane(), async () => THEIRS);
+ expect(flatten(shown).some((n) => n.props.key === "lens-flow")).toBe(false);
});
it("never touches a pane the person opened with /lens", async () => {
const d = await start({ lens_pane_autoopen: true }, false);
- await hooks["command.run:lens"]!(d.$, { command: "lens" }, async () => ({}));
+ await hooks["command.run:lens"]!(d.$, { command: "lens", args: "map" }, async () => ({}));
await hooks["tool.call"]!(d.$, read, async () => ({ result: {} }));
await settle();
expect(d.calls.open).toHaveLength(1);
diff --git a/packages/claude-mod/test/map.test.ts b/packages/claude-mod/test/map.test.ts
index 6a1d9d11a..9a4d6d5b8 100644
--- a/packages/claude-mod/test/map.test.ts
+++ b/packages/claude-mod/test/map.test.ts
@@ -1,19 +1,9 @@
import { describe, expect, it } from "vitest";
import { DARK, DARK_CANVAS } from "@repowise-dev/ui/brand";
import { scopeParts } from "../src/views/copy";
-import {
- GROUND,
- colorForScore,
- encodeCells,
- groupKeys,
- labelText,
- layoutMap,
- mix,
- type MapFile,
- type MapLayout,
- type PlacedFile,
-} from "../src/views/map";
+import { GROUND, MAP_PALETTES, colorForScore, encodeCells, groupKeys, labelText, layoutMap, mix, type MapFile, type MapLayout, type PlacedFile, TERMINAL_DEFAULT, halfCell } from "../src/views/map";
import { decode, feed } from "./django";
+import { syntheticTree } from "./synthetic";
/** Every pixel index a placed file owns. */
function pixelsOf(f: PlacedFile, width: number): number[] {
@@ -66,7 +56,7 @@ describe("groupKeys", () => {
});
describe("layoutMap on the Django feed at 180x50", () => {
- const layout = layoutMap(feed.files, 180, 50, true);
+ const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });
const total = feed.files.reduce((s, f) => s + f.nloc, 0);
const canvas = 180 * 100;
@@ -87,7 +77,7 @@ describe("layoutMap on the Django feed at 180x50", () => {
});
it("is deterministic, whatever order the feed arrives in", () => {
- const again = layoutMap([...feed.files].reverse(), 180, 50, true);
+ const again = layoutMap([...feed.files].reverse(), { columns: 180, rows: 50, caseInsensitive: true });
expect(again.files).toEqual(layout.files);
expect(again.base).toEqual(layout.base);
expect(again.labels).toEqual(layout.labels);
@@ -99,12 +89,13 @@ describe("layoutMap on the Django feed at 180x50", () => {
expect([...layout.base].every((c) => c < 0x01000000)).toBe(true);
});
- it("darkens the last column and row of a file big enough, so neighbours part", () => {
- const big = layout.files.find((f) => f.px1 - f.px0 >= 3 && f.py1 - f.py0 >= 3)!;
+ it("with health colours on, darkens the last column and row of a file big enough, so neighbours part", () => {
+ const health = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true, style: { theme: "dark", health: true } });
+ const big = health.files.find((f) => f.px1 - f.px0 >= 3 && f.py1 - f.py0 >= 3)!;
const fill = colorForScore(big.score);
- expect(layout.base[big.py0 * 180 + big.px0]).toBe(fill);
- expect(layout.base[big.py0 * 180 + big.px1 - 1]).toBe(mix(fill, 0, 0.3));
- expect(layout.base[(big.py1 - 1) * 180 + big.px0]).toBe(mix(fill, 0, 0.3));
+ expect(health.base[big.py0 * 180 + big.px0]).toBe(fill);
+ expect(health.base[big.py0 * 180 + big.px1 - 1]).toBe(mix(fill, 0, 0.3));
+ expect(health.base[(big.py1 - 1) * 180 + big.px0]).toBe(mix(fill, 0, 0.3));
});
it("paints a missing score neutral", () => {
@@ -118,7 +109,7 @@ describe("layoutMap on the Django feed at 180x50", () => {
});
it("the legend counts exactly the files drawn", () => {
- const parts = scopeParts({ drawn: layout.drawn.length, repositoryTotal: feed.repository_total, indexed: "2h ago", beyondCap: 0, cap: 4_000 });
+ const parts = scopeParts({ drawn: layout.drawn.length, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: "2h ago", beyondCap: 0, dense: layout.dense, notOnMap: 0 });
expect(parts[0]).toBe(`${layout.drawn.length.toLocaleString("en-US")} of 2,970 files drawn at this size`);
});
});
@@ -139,32 +130,41 @@ describe("labelText", () => {
describe("a tiny canvas", () => {
it("draws fewer files than it places, and counts only those", () => {
- const layout = layoutMap(feed.files, 12, 4, true);
+ const layout = layoutMap(feed.files, { columns: 12, rows: 4, caseInsensitive: true });
expect(layout.drawn.length).toBeLessThan(layout.files.length);
expect(distinctOwners(layout)).toBe(layout.drawn.length);
});
it("four equal files fill a 4x2 canvas", () => {
const files: MapFile[] = ["a/1", "a/2", "a/3", "a/4"].map((p) => ({ file_path: p, score: 9, nloc: 1 }));
- const layout = layoutMap(files, 4, 2, false);
+ const layout = layoutMap(files, { columns: 4, rows: 2, caseInsensitive: false });
expect(layout.drawn).toHaveLength(4);
expect([...layout.base].every((c) => c !== GROUND)).toBe(true);
});
});
describe("cell encoding", () => {
- it("round-trips pixels through upper half blocks, labels aside", () => {
- const layout = { ...layoutMap(feed.files, 60, 20, true), labels: [] };
+ it("round-trips pixels through half blocks, labels aside, the empty ground left to the terminal", () => {
+ const layout = { ...layoutMap(feed.files, { columns: 60, rows: 20, caseInsensitive: true }), labels: [] };
const words = decode(encodeCells(layout, layout.base));
expect(words).toHaveLength(60 * 20 * 3);
for (let i = 0; i < 60 * 20; i++) {
const [r, c] = [Math.floor(i / 60), i % 60];
- expect([words[i * 3], words[i * 3 + 1], words[i * 3 + 2]]).toEqual([0x2580, layout.base[2 * r * 60 + c], layout.base[(2 * r + 1) * 60 + c]]);
+ expect([words[i * 3], words[i * 3 + 1], words[i * 3 + 2]]).toEqual(halfCell(layout.base[2 * r * 60 + c]!, layout.base[(2 * r + 1) * 60 + c]!));
}
+ expect([...words].some((w, i) => i % 3 === 2 && w === TERMINAL_DEFAULT)).toBe(true);
+ });
+
+ it("a cell half on the ground draws the other half alone, on the terminal's own background", () => {
+ const tile = 0x42906f;
+ expect(halfCell(tile, 0x123456)).toEqual([0x2580, tile, 0x123456]);
+ expect(halfCell(tile, GROUND)).toEqual([0x2580, tile, TERMINAL_DEFAULT]);
+ expect(halfCell(GROUND, tile)).toEqual([0x2584, tile, TERMINAL_DEFAULT]);
+ expect(halfCell(GROUND, GROUND)).toEqual([0x20, TERMINAL_DEFAULT, TERMINAL_DEFAULT]);
});
it("writes a label whole on ground cells, or not at all when a mark covers any of its cells", () => {
- const layout = layoutMap(feed.files, 180, 50, true);
+ const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });
const label = layout.labels[0]!;
const text = (words: Uint32Array) => [...label.text].map((_, k) => String.fromCharCode(words[(label.row * 180 + label.col + k) * 3]!)).join("");
expect(text(decode(encodeCells(layout, layout.base)))).toBe(label.text);
@@ -174,7 +174,60 @@ describe("cell encoding", () => {
});
it("encodes a 180x50 frame to the documented size", () => {
- const layout = layoutMap(feed.files, 180, 50, true);
+ const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });
expect(encodeCells(layout, layout.base)).toHaveLength(144_000);
});
});
+
+describe("ghost tiles at both ends of scale", () => {
+ const pal = MAP_PALETTES.dark;
+ /** The tones a layout's pixels use, the empty ground aside. */
+ const tones = (l: MapLayout) => new Set([...l.base].filter((c) => c !== GROUND));
+ /** Every tile tone a file could carry, edges darkened included. */
+ const ghost = new Set([pal.tileA, pal.tileB, mix(pal.tileA, 0, 0.3), mix(pal.tileB, 0, 0.3)]);
+
+ it("a small repo (100 files, synthetic) at 120x24: a tile per file, in the two quiet tones only", () => {
+ const small = layoutMap(syntheticTree(100).files, { columns: 120, rows: 24, caseInsensitive: true });
+ expect(small.dense).toBe(false);
+ for (const c of tones(small)) expect(ghost.has(c)).toBe(true);
+ expect(small.drawn.length).toBeGreaterThanOrEqual(95);
+ });
+
+ it("Django at 180x100: still a tile per file; no health colour unless asked", () => {
+ const roomy = layoutMap(feed.files, { columns: 180, rows: 100, caseInsensitive: true });
+ expect(roomy.dense).toBe(false);
+ for (const c of tones(roomy)) expect(ghost.has(c)).toBe(true);
+ });
+
+ it("a huge repo (10,000 files, synthetic; the 4,000 the server sends) at 120x24: folders as tiles, one tone each, no per-file shimmer", () => {
+ const huge = layoutMap(syntheticTree(10_000).files.slice(0, 4_000), { columns: 120, rows: 24, caseInsensitive: true });
+ expect(huge.dense).toBe(true);
+ expect(tones(huge)).toEqual(new Set([pal.tileA, pal.tileB]));
+ // A folder with no folders inside it is one tone throughout: its files do not alternate.
+ const leaf = huge.folders.filter((f, i) => !huge.folders.some((g, j) => j > i && g.x0 >= f.x0 && g.x1 <= f.x1 && g.y0 >= f.y0 && g.y1 <= f.y1));
+ const big = leaf.filter((f) => (f.x1 - f.x0) * (f.y1 - f.y0) >= 4);
+ expect(big.length).toBeGreaterThan(10);
+ for (const f of big) {
+ const seen = new Set<number>();
+ for (let y = f.y0; y < f.y1; y++) for (let x = f.x0; x < f.x1; x++) seen.add(huge.base[y * huge.width + x] as number);
+ expect(seen.size).toBe(1);
+ }
+ });
+
+ it("the light theme uses the light ramp's tones", () => {
+ const light = layoutMap(feed.files, { columns: 120, rows: 24, caseInsensitive: true, style: { theme: "light", health: false } });
+ expect(tones(light).has(MAP_PALETTES.light.tileA) || tones(light).has(MAP_PALETTES.light.tileB)).toBe(true);
+ expect(tones(light).has(pal.tileA)).toBe(false);
+ });
+
+ it("folder names are faint, on the tile under them, and only on large regions, a few at most", () => {
+ const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });
+ expect(layout.labels.length).toBeGreaterThan(0);
+ expect(layout.labels.length).toBeLessThanOrEqual(8);
+ const words = decode(encodeCells(layout, layout.base));
+ const l = layout.labels[0]!;
+ const cell = (l.row * 180 + l.col) * 3;
+ expect(words[cell + 1]).toBe(pal.folder);
+ expect([GROUND, TERMINAL_DEFAULT]).not.toContain(words[cell + 2]);
+ });
+});
diff --git a/packages/claude-mod/test/mapPane.test.ts b/packages/claude-mod/test/mapPane.test.ts
index 8ce13f319..56aafb5e9 100644
--- a/packages/claude-mod/test/mapPane.test.ts
+++ b/packages/claude-mod/test/mapPane.test.ts
@@ -1,12 +1,12 @@
import { describe, expect, it } from "vitest";
-import { BRAND, DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
-import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";
-import { HINTS, MAP_COPY, callersLine, freshnessLine, notPlacedLine, readsLine, scopeParts } from "../src/views/copy";
+import { DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
+import { NO_STORY, type Reach, type Story } from "../src/model/story";
+import { HINTS, MAP_COPY, STORY_COPY, freshnessLine, linesPart, notPlacedLine, reachesPart, scopeParts, searchedPart } from "../src/views/copy";
import type { Node } from "../src/views/elements";
-import { layoutMap } from "../src/views/map";
-import { MAP_KEY, legendRows, mapPaneView, mapSize, noticeView, packRows } from "../src/views/mapPane";
-import { frameCells, resolveOverlay } from "../src/views/overlay";
-import { feed } from "./django";
+import { MAP_PALETTES, layoutMap } from "../src/views/map";
+import { HEALTH_KEY, MAP_KEY, legendRows, mapPaneView, mapSize, noticeView, packRows, storyView, type MapPaneParts } from "../src/views/mapPane";
+import { NO_LIT, frameCells, resolveLit } from "../src/views/overlay";
+import { feed, importers } from "./django";
function texts(node: Node): string[] {
if (node.type === "Text") return [node.children.join("")];
@@ -15,7 +15,7 @@ function texts(node: Node): string[] {
return node.children.flatMap(texts);
}
-/** One row as drawn: a Text, or a row Box's items, each item's texts run together, items two apart. */
+/** One row as drawn: a Text, or a row Box's items, each item's texts run together, items `columnGap` apart. */
function line(node: Node): string {
if (node.type !== "Box") return texts(node).join("");
return node.children.map((c) => texts(c).join("")).join(" ".repeat(node.props.columnGap ?? 0));
@@ -25,25 +25,38 @@ function rows(node: Node): string[] {
return node.type === "Box" ? node.children.map(line) : [];
}
-const scope = { drawn: 1_639, repositoryTotal: 2_970, indexed: "2h ago", beyondCap: 0, cap: 4_000 };
+const DARK = { theme: "dark" as const, health: false };
+const hex = (n: number) => `#${n.toString(16).padStart(6, "0")}`;
+const scope = { drawn: 1_639, shown: 2_347, repositoryTotal: 2_970, indexed: "2h ago", beyondCap: 0, dense: false, notOnMap: 0 };
+
+/** The recorded Django turn's story: Flow's record of it, as model/story.ts reads it. */
+const story: Story = {
+ searched: [
+ { pattern: "class QuerySet", hits: 4 },
+ { pattern: "django/db/models/sql/*.py", hits: 7 },
+ ],
+ opened: [
+ { name: "manager.py", namedBy: null },
+ { name: "query.py", namedBy: "get_context" },
+ ],
+ edited: [{ name: "query.py", lines: { delta: 1 } }],
+};
+const reach: Reach = {
+ edit: "django/db/models/query.py",
+ callers: { status: "ready", paths: importers },
+ opened: new Set(["django/db/models/manager.py", "django/db/models/query.py"]),
+};
describe("mapSize and legendRows", () => {
- it("docked: full width, the pane's rows less the legend at that width", () => {
- expect(legendRows(180)).toBe(6);
- expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 })).toEqual({ columns: 180, rows: 49 });
+ it("docked: full width, the pane's rows less the story, scope and toggle rows (and the health legend when on)", () => {
+ expect(legendRows(180)).toBe(4 + 2 + 1);
+ expect(legendRows(180, true)).toBe(4 + 1 + 2 + 1);
+ expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 })).toEqual({ columns: 180, rows: 48 });
+ expect(mapSize({ bodyColumns: 180, placement: "dock", bodyRows: 55 }, true)).toEqual({ columns: 180, rows: 47 });
});
- it("a narrow pane wraps the swatches and reserves the rows for them", () => {
- expect(legendRows(40)).toBe(9);
- expect(mapSize({ bodyColumns: 40, placement: "dock", bodyRows: 30 })).toEqual({ columns: 40, rows: 21 });
- });
-
- it("inline: a squat share of the width, capped", () => {
+ it("inline: a squat share of the width, capped; within the Raster's limits", () => {
expect(mapSize({ bodyColumns: 120, placement: "inline", bodyRows: 3 })).toEqual({ columns: 120, rows: 20 });
- expect(mapSize({ bodyColumns: 60, placement: "inline", bodyRows: 3 })).toEqual({ columns: 60, rows: 10 });
- });
-
- it("stays within the Raster's limits", () => {
expect(mapSize({ bodyColumns: 900, placement: "dock", bodyRows: 900 })).toEqual({ columns: 512, rows: 256 });
expect(mapSize({ bodyColumns: 0, placement: "dock", bodyRows: 2 })).toEqual({ columns: 1, rows: 4 });
});
@@ -54,118 +67,101 @@ describe("mapSize and legendRows", () => {
});
});
-describe("copy", () => {
- it("scope: all drawn, or how many at this size, then age and any cap", () => {
- expect(scopeParts({ ...scope, drawn: 2_914, repositoryTotal: 2_914 })).toEqual(["2,914 files, all drawn", "indexed 2h ago"]);
- expect(scopeParts({ ...scope, indexed: null, beyondCap: 1_200 })).toEqual([
- "1,639 of 2,970 files drawn at this size",
- "rest empty or too small",
- "1,200 beyond the 4,000-file cap",
+describe("the story strip", () => {
+ it("names what the turn searched, opened, edited and reaches, with units", () => {
+ expect(storyView(story, reach, DARK, 120).map(line)).toEqual([
+ "SEARCHED class QuerySet: 4 files · django/db/models/sql/*.py: 7 files",
+ "OPENED manager.py · query.py ◆ query.py named by get_context",
+ "EDITED ◉ query.py +1 line",
+ "REACHES 12 importers: manager.py (opened), fields.py, prefetch.py, +9",
]);
});
- it("reads: nothing before the first, then reads, what was not drawn, and the last search", () => {
- const r = (count: number, notDrawn = 0, capped = false) => ({ count, capped, notDrawn });
- expect(readsLine(r(0), null)).toBeNull();
- expect(readsLine(r(1), null)).toBe("1 file read");
- expect(readsLine(r(8, 3), null)).toBe("8 files read · 3 not drawn");
- expect(readsLine(r(200, 0, true), 14)).toBe("200+ files read · last search matched 14 files");
- expect(readsLine(r(0), 0)).toBe("last search matched 0 files");
+ it("colors Repowise's naming and the importers plum, the edit amber; heads dim", () => {
+ const json = JSON.stringify(storyView(story, reach, DARK, 120));
+ expect(json).toContain(hex(MAP_PALETTES.dark.importer));
+ expect(json).toContain(hex(MAP_PALETTES.dark.edit));
+ const light = JSON.stringify(storyView(story, reach, { theme: "light", health: false }, 120));
+ expect(light).toContain(hex(MAP_PALETTES.light.edit));
});
- it("importers: loading, unavailable, found, some not drawn", () => {
- expect(callersLine("query.py", null, 0)).toBe("edited query.py · finding the files that import it");
- expect(callersLine("query.py", { status: "loading" }, 0)).toBe("edited query.py · finding the files that import it");
- expect(callersLine("query.py", { status: "failed" }, 0)).toBe("edited query.py · import graph unavailable");
- expect(callersLine("query.py", { status: "ready", paths: ["a"] }, 0)).toBe("edited query.py · 1 file imports it (from imports, not calls)");
- expect(callersLine("query.py", { status: "ready", paths: new Array(12).fill("x") }, 3)).toBe(
- "edited query.py · 12 files import it (from imports, not calls) · 3 not drawn",
- );
+ it("rows appear only once they have something to say; the lookup in flight or failed says so", () => {
+ expect(storyView(NO_STORY, null, DARK, 120)).toEqual([]);
+ expect(storyView({ ...NO_STORY, opened: [{ name: "a.py", namedBy: null }] }, null, DARK, 120).map(line)).toEqual(["OPENED a.py"]);
+ const pending = storyView(story, { ...reach, callers: { status: "loading" } }, DARK, 120).map(line);
+ expect(pending.at(-1)).toBe("REACHES finding the files that import query.py");
+ expect(storyView(story, { ...reach, callers: { status: "failed" } }, DARK, 120).map(line).at(-1)).toBe("REACHES import graph unavailable");
});
- it("no em dash in anything Lens writes", () => {
- const all = [
- ...Object.values(HINTS),
- ...Object.values(MAP_COPY),
- notPlacedLine("below 110 columns (80 now)"),
- freshnessLine({ changedFiles: 3 }),
- ...scopeParts({ ...scope, beyondCap: 5 }),
- readsLine({ count: 3, capped: true, notDrawn: 1 }, 2),
- callersLine("a.py", { status: "ready", paths: ["b"] }, 1),
- callersLine("a.py", { status: "failed" }, 0),
- callersLine("a.py", null, 0),
- ];
- for (const line of all) expect(line).not.toMatch(/[\u2013\u2014]/);
+ it("fits a narrow pane", () => {
+ for (const row of storyView(story, reach, DARK, 40).map(line)) expect(row.length).toBeLessThanOrEqual(40);
});
-});
-describe("mapPaneView", () => {
- const layout = layoutMap(feed.files, 120, 20, true);
- const root = "C:\\work\\django";
- const view = (t: TrailState, columns = 120, facts = scope) => {
- const resolved = resolveOverlay(layout, t, root);
- return mapPaneView({ ...layout, columns }, frameCells(layout, resolved.overlay), resolved, facts);
- };
-
- it("draws the Raster at the layout's size and the legend outside it, with every band word", () => {
- const tree = view(initialTrail);
- if (tree.type !== "Box") throw new Error("expected a Box");
- expect(tree.children[0]).toMatchObject({ type: "Raster", props: { key: MAP_KEY, columns: 120, rows: 20 } });
- expect(rows(tree)).toEqual([
+ it("copy pieces carry their units", () => {
+ expect(searchedPart("", 3)).toBe("last search matched 3 files");
+ expect(searchedPart("x", null)).toBe("x: matches not counted");
+ expect([linesPart(null), linesPart({ delta: -3 }), linesPart({ delta: 0 }), linesPart({ written: 40 })]).toEqual([
"",
- "■ At risk ■ Needs work ■ Fair ■ Good ■ Excellent ■ Not scored",
- "□ Claude read ◆ edited",
- "1,639 of 2,970 files drawn at this size · rest empty or too small · indexed 2h ago",
+ " -3 lines",
+ " 0 lines",
+ " 40 lines written",
]);
+ expect(reachesPart(1, [{ name: "a.py", opened: false }])).toBe("1 importer: a.py");
+ expect(Object.values(STORY_COPY)).toEqual(["SEARCHED", "OPENED", "EDITED", "REACHES"]);
});
+});
- it("colors swatches with the canvas band ramp and Claude's marks orange", () => {
- const json = JSON.stringify(view(initialTrail));
- expect(json).toContain(DARK_CANVAS_BAND.at_risk);
- expect(json).toContain(DARK_CANVAS_BAND.excellent);
- expect(json).toContain(BRAND.accent);
+describe("scope", () => {
+ it("says what is drawn: all, drawn at this size, as folders, or the largest under the cap", () => {
+ expect(scopeParts({ ...scope, drawn: 2_914, repositoryTotal: 2_914 })).toEqual(["2,914 files, all drawn", "indexed 2h ago"]);
+ expect(scopeParts({ ...scope, indexed: null })).toEqual(["1,639 of 2,970 files drawn at this size", "rest too small to draw"]);
+ expect(scopeParts({ ...scope, indexed: null, dense: true })).toEqual(["2,970 files, drawn as folders at this size"]);
+ // Under the cap, never more tiles implied than are drawn: at both densities, and when all of the largest fit.
+ const capped = { ...scope, indexed: null, shown: 4_000, repositoryTotal: 10_312, beyondCap: 6_312 };
+ expect(scopeParts(capped)).toEqual(["1,639 of the 4,000 largest (of 10,312 files) drawn at this size", "rest too small to draw"]);
+ expect(scopeParts({ ...capped, dense: true })).toEqual(["4,000 largest of 10,312 files; drawn as folders at this size"]);
+ expect(scopeParts({ ...capped, drawn: 4_000 })).toEqual(["4,000 largest of 10,312 files drawn"]);
+ expect(scopeParts({ ...scope, indexed: null, dense: true, notOnMap: 2 })).toEqual(["2,970 files, drawn as folders at this size", "2 touched files not on the map"]);
});
- it("names the importer and match marks only when they are on the map, and states the trail", () => {
- let t = reduceTrail(initialTrail, { type: "read", path: "c:/work/django/django/db/models/base.py" });
- t = reduceTrail(t, { type: "read", path: "c:/elsewhere/x.py" });
- t = reduceTrail(t, { type: "search", paths: ["c:/work/django/django/db/models/base.py"] });
- t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });
- t = reduceTrail(t, { type: "callers", edits: 1, callers: { status: "ready", paths: ["django/db/models/base.py", "not/in/feed.py"] } });
- const shown = rows(view(t));
- expect(shown).toContain("□ Claude read ◆ edited · imports the edited file ▪ search match");
- expect(shown).toContain("3 files read · 1 not drawn · last search matched 1 file");
- expect(shown).toContain("edited query.py · 2 files import it (from imports, not calls) · 1 not drawn");
+ it("no em dash in anything the map writes", () => {
+ const all = [...Object.values(HINTS), ...Object.values(MAP_COPY), notPlacedLine("below 110 columns (80 now)"), freshnessLine({ changedFiles: 3 }), ...scopeParts(scope)];
+ for (const l of all) expect(l).not.toMatch(/[–—]/);
+ });
+});
+
+describe("mapPaneView", () => {
+ const layout = layoutMap(feed.files, { columns: 120, rows: 20, caseInsensitive: true });
+ const view = (parts: MapPaneParts = { story, reach, scope }, l = layout) => mapPaneView(l, frameCells(l, resolveLit(l, NO_LIT)), parts);
+
+ it("draws the Raster, then the strip as the legend, the scope, and the health toggle; no swatch row", () => {
+ const tree = view();
+ if (tree.type !== "Box") throw new Error("expected a Box");
+ expect(tree.children[0]).toMatchObject({ type: "Raster", props: { key: MAP_KEY, columns: 120, rows: 20 } });
+ const shown = rows(tree);
+ expect(shown.slice(1, 5).map((r) => r.slice(0, 8))).toEqual(["SEARCHED", "OPENED ", "EDITED ", "REACHES "]);
+ expect(shown.at(-2)).toBe("1,639 of 2,970 files drawn at this size · rest too small to draw · indexed 2h ago");
+ expect(tree.children.at(-1)).toMatchObject({ type: "Button", props: { key: HEALTH_KEY, hotkey: "h", label: MAP_COPY.healthOff } });
+ expect(JSON.stringify(tree)).not.toContain(DARK_CANVAS_BAND.at_risk);
});
- it("wraps the scope onto a second row when narrow, so the age survives", () => {
- const shown = rows(view(initialTrail, 50));
- expect(shown.slice(-2)).toEqual(["1,639 of 2,970 files drawn at this size", "rest empty or too small · indexed 2h ago"]);
+ it("quiet when nothing happened this turn: one line saying what will light up", () => {
+ expect(rows(view({ story: NO_STORY, reach: null, scope }))[1]).toBe(MAP_COPY.quiet);
});
- it("at 60 columns the edit and reads rows keep every count, in a short form", () => {
- let t = reduceTrail(initialTrail, { type: "read", path: "c:/elsewhere/x.py" });
- t = reduceTrail(t, { type: "search", paths: ["c:/work/django/django/db/models/base.py"] });
- t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });
- const paths = ["django/db/models/base.py", ...Array.from({ length: 10 }, (_, i) => `not/in/feed${i}.py`)];
- t = reduceTrail(t, { type: "callers", edits: 1, callers: { status: "ready", paths } });
- const shown = rows(view(t, 60));
- expect(shown).toContain("edited query.py · 11 import it · 10 not drawn");
- expect(shown).toContain("2 files read · 1 not drawn · last search matched 1 file");
- const long = callersLine("a_very_long_module_name_that_goes_on_and_on.py", { status: "ready", paths }, 10, 40);
- expect(long).toMatch(/· 11 import it · 10 not drawn$/);
- expect(long.length).toBeLessThanOrEqual(40);
- expect(readsLine({ count: 200, capped: true, notDrawn: 1_234 }, 1_204, 60)).toBe("200+ read · 1,234 not drawn · search matched 1,204");
+ it("with health colours on, the band legend comes back and the toggle says on", () => {
+ const health = layoutMap(feed.files, { columns: 120, rows: 20, caseInsensitive: true, style: { theme: "dark", health: true } });
+ const tree = view({ story, reach, scope }, health);
+ expect(rows(tree)).toContain("■ At risk ■ Needs work ■ Fair ■ Good ■ Excellent ■ Not scored");
+ expect(texts(tree).at(-1)).toBe(MAP_COPY.healthOn);
});
- it("at 60 columns the cap clause survives; the rest note and the age leave first", () => {
- const capped = { ...scope, drawn: 1_500, repositoryTotal: 8_281, beyondCap: 4_281 };
- const shown = rows(view(initialTrail, 60, capped));
- expect(shown.slice(-2)).toEqual(["1,500 of 8,281 files drawn at this size · indexed 2h ago", "4,281 beyond the 4,000-file cap"]);
- expect(rows(view(initialTrail, 45, capped)).slice(-2)).toEqual(["1,500 of 8,281 files drawn at this size", "4,281 beyond the 4,000-file cap"]);
- expect(rows(view(initialTrail, 120, capped)).at(-1)).toBe(
- "1,500 of 8,281 files drawn at this size · rest empty or too small · indexed 2h ago · 4,281 beyond the 4,000-file cap",
- );
+ it("wraps the scope onto two rows when narrow; the cap clause survives, the rest note and the age leave first", () => {
+ const capped = { ...scope, drawn: 1_500, shown: 4_000, repositoryTotal: 8_281, beyondCap: 4_281, notOnMap: 3 };
+ const narrow = rows(view({ story, reach, scope: capped }, { ...layout, columns: 70 }));
+ expect(narrow.slice(-3, -1)).toEqual(["1,500 of the 4,000 largest (of 8,281 files) drawn at this size", "indexed 2h ago · 3 touched files not on the map"]);
+ const dense = rows(view({ story, reach, scope: { ...capped, dense: true } }, { ...layout, columns: 70 }));
+ expect(dense.slice(-3, -1)).toEqual(["4,000 largest of 8,281 files; drawn as folders at this size", "indexed 2h ago · 3 touched files not on the map"]);
});
it("noticeView is one dim line, fitted", () => {
diff --git a/packages/claude-mod/test/mapSvg.test.ts b/packages/claude-mod/test/mapSvg.test.ts
index 75206baec..119a9800b 100644
--- a/packages/claude-mod/test/mapSvg.test.ts
+++ b/packages/claude-mod/test/mapSvg.test.ts
@@ -1,68 +1,73 @@
// The desktop map over the recorded Django health-map feed (test/django.ts).
import { describe, expect, it } from "vitest";
import { DARK_CANVAS_BAND } from "@repowise-dev/ui/brand";
-import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";
-import { GROUND, layoutMap } from "../src/views/map";
+import { NO_STORY } from "../src/model/story";
+import { GROUND, MAP_PALETTES, layoutMap } from "../src/views/map";
import { mapSize } from "../src/views/mapPane";
import { SVG_CHARS, desktopSize, mapSvg, svgPaneView } from "../src/views/mapSvg";
-import { framePixels, resolveOverlay } from "../src/views/overlay";
+import { NO_LIT, framePixels, resolveLit, type Lit } from "../src/views/overlay";
import { feed, importers } from "./django";
-const ROOT = "C:\\work\\django";
-const scope = { drawn: 0, repositoryTotal: feed.repository_total, indexed: null, beyondCap: 0, cap: 4_000 };
+const scope = { drawn: 0, shown: feed.files.length, repositoryTotal: feed.repository_total, indexed: null, beyondCap: 0, dense: false, notOnMap: 0 };
+const parts = { story: NO_STORY, reach: null, scope };
+const hex = (n: number) => `#${n.toString(16).padStart(6, "0")}`;
-/** The busiest trail the model keeps: 200 reads, a search, and an edit with its importers. */
-function busy(): TrailState {
- let t = initialTrail;
- for (const f of feed.files.slice(0, 260)) t = reduceTrail(t, { type: "read", path: `c:/work/django/${f.file_path}`.toLowerCase() });
- t = reduceTrail(t, { type: "search", paths: feed.files.slice(300, 400).map((f) => `c:/work/django/${f.file_path}`.toLowerCase()) });
- t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });
- return reduceTrail(t, { type: "callers", edits: t.edits, callers: { status: "ready", paths: importers } });
-}
+/** A busy turn: 260 files opened, 100 search matches, query.py edited with its importers. */
+const busy: Lit = {
+ hits: feed.files.slice(300, 400).map((f) => f.file_path),
+ reads: feed.files.slice(0, 260).map((f) => f.file_path),
+ named: [],
+ importers,
+ edits: ["django/db/models/query.py"],
+ edit: "django/db/models/query.py",
+ current: "django/db/models/query.py",
+};
describe("desktop map", () => {
const size = desktopSize(mapSize({ bodyColumns: 400, placement: "dock", bodyRows: 200 }));
- const layout = layoutMap(feed.files, size.columns, size.rows, true);
+ const layout = layoutMap(feed.files, { columns: size.columns, rows: size.rows, caseInsensitive: true });
- it("caps the size, and stays under the Svg limit on the Django feed, at rest and with the busiest trail", () => {
+ it("caps the size, and stays under the Svg limit on the Django feed, at rest and on a busy turn", () => {
expect(size).toEqual({ columns: 160, rows: 45 });
- expect(mapSvg(layout, resolveOverlay(layout, initialTrail, ROOT)).length).toBeLessThan(SVG_CHARS);
- expect(mapSvg(layout, resolveOverlay(layout, busy(), ROOT)).length).toBeLessThan(SVG_CHARS);
+ expect(mapSvg(layout, resolveLit(layout, NO_LIT)).length).toBeLessThan(SVG_CHARS);
+ expect(mapSvg(layout, resolveLit(layout, busy)).length).toBeLessThan(SVG_CHARS);
expect(desktopSize({ columns: 80, rows: 20 })).toEqual({ columns: 80, rows: 20 });
});
- it("draws the terminal's resting frame: every non-ground pixel of it, once, in its color", () => {
- const resolved = resolveOverlay(layout, busy(), ROOT);
- const source = mapSvg(layout, resolved);
- const { pixels } = framePixels(layout, resolved.overlay);
+ it("draws the terminal's resting frame: every non-ground pixel of it, once, in its color; no background of its own", () => {
+ const overlay = resolveLit(layout, busy);
+ const source = mapSvg(layout, overlay);
+ const { pixels } = framePixels(layout, overlay);
const counted = new Map<string, number>();
for (const [, color, d] of source.matchAll(/<path stroke="(#[0-9a-f]{6})" d="([^"]+)"\/>/g)) {
const n = [...d!.matchAll(/h(\d+)/g)].reduce((sum, m) => sum + Number(m[1]), 0);
counted.set(color!, (counted.get(color!) ?? 0) + n);
}
const expected = new Map<string, number>();
- for (const p of pixels) {
- if (p !== GROUND) expected.set(`#${p.toString(16).padStart(6, "0")}`, (expected.get(`#${p.toString(16).padStart(6, "0")}`) ?? 0) + 1);
- }
+ for (const p of pixels) if (p !== GROUND) expected.set(hex(p), (expected.get(hex(p)) ?? 0) + 1);
expect(counted).toEqual(expected);
- expect(source).toContain(DARK_CANVAS_BAND.good.toLowerCase());
+ expect(source).not.toContain("<rect");
+ expect(source).toContain(hex(MAP_PALETTES.dark.tileA));
+ expect(source).not.toContain(DARK_CANVAS_BAND.good.toLowerCase());
+ const health = layoutMap(feed.files, { columns: size.columns, rows: size.rows, caseInsensitive: true, style: { theme: "dark", health: true } });
+ expect(mapSvg(health, resolveLit(health, NO_LIT))).toContain(DARK_CANVAS_BAND.good.toLowerCase());
});
- it("is deterministic, labels its groups as text, and escapes them", () => {
- const resolved = resolveOverlay(layout, initialTrail, ROOT);
- expect(mapSvg(layout, resolved)).toBe(mapSvg(layout, resolved));
- expect(mapSvg(layout, resolved)).toMatch(/<text x="\d+" y="[\d.]+">django\//);
+ it("is deterministic, names folders faintly and the lit files beside them, and escapes text", () => {
+ const overlay = resolveLit(layout, busy);
+ expect(mapSvg(layout, overlay)).toBe(mapSvg(layout, overlay));
+ expect(mapSvg(layout, overlay)).toMatch(new RegExp(`<text x="\\d+" y="[\\d.]+" fill="${hex(MAP_PALETTES.dark.folder)}">`));
+ expect(mapSvg(layout, overlay)).toContain(`fill="${hex(MAP_PALETTES.dark.edit)}">query.py</text>`);
const odd = { ...layout, labels: [{ row: 0, col: 0, text: "a<b&c" }] };
- expect(mapSvg(odd, resolved)).toContain("<text x=\"0\" y=\"1.6\">a&lt;b&amp;c</text>");
+ expect(mapSvg(odd, resolveLit(odd, NO_LIT))).toContain(`<text x="0" y="1.6" fill="${hex(MAP_PALETTES.dark.folder)}">a&lt;b&amp;c</text>`);
});
- it("the pane: the drawing with its alt text over the legend; a drawing over the limit says so instead", () => {
- const resolved = resolveOverlay(layout, initialTrail, ROOT);
- const view = svgPaneView(layout, resolved, { ...scope, drawn: layout.drawn.length });
+ it("the pane: the drawing with its alt text over the strip; a drawing over the limit says so instead", () => {
+ const view = svgPaneView(layout, resolveLit(layout, NO_LIT), { ...parts, scope: { ...scope, drawn: layout.drawn.length } });
if (view.type !== "Box") throw new Error("expected a Box");
- expect(view.children[0]).toMatchObject({ type: "Svg", props: { alt: expect.stringMatching(/^Code health map: [\d,]+ files drawn/) } });
- const huge = layoutMap(feed.files, 512, 256, true);
- const over = svgPaneView(huge, resolveOverlay(huge, busy(), ROOT), scope);
+ expect(view.children[0]).toMatchObject({ type: "Svg", props: { alt: expect.stringMatching(/^Map of the repo: [\d,]+ files drawn as tiles/) } });
+ const huge = layoutMap(feed.files, { columns: 512, rows: 256, caseInsensitive: true, style: { theme: "dark", health: true } });
+ const over = svgPaneView(huge, resolveLit(huge, busy), parts);
if (over.type !== "Box") throw new Error("expected a Box");
expect(over.children[0]).toMatchObject({ type: "Text", children: ["Lens map has too much detail to draw here; the terminal map shows it"] });
});
diff --git a/packages/claude-mod/test/mcp.test.ts b/packages/claude-mod/test/mcp.test.ts
index f4e136a81..40d0b78e6 100644
--- a/packages/claude-mod/test/mcp.test.ts
+++ b/packages/claude-mod/test/mcp.test.ts
@@ -130,7 +130,12 @@ describe("callTool", () => {
describe("fetchFileContext", () => {
it("reads caller files and contributors from a recorded card", async () => {
const host = await warmed(fakeHost({ mcp: () => sessions }));
- expect(await fetchFileContext(host, "src/requests/sessions.py")).toEqual({ callerFiles: 3, contributors: 6 });
+ expect(await fetchFileContext(host, "src/requests/sessions.py")).toEqual({
+ callerFiles: 3,
+ contributors: 6,
+ hotspot: false,
+ recentOwner: { name: "Joren Hammudoglu", share: 0.5 },
+ });
expect(host.calls.mcp[0]?.args).toEqual({ targets: ["src/requests/sessions.py"], include: ["callers", "ownership"] });
});
@@ -140,12 +145,12 @@ describe("fetchFileContext", () => {
mcp: () => mcpResult({ targets: { "q.py": { callers: [{}, {}], callers_total: 41, ownership: { contributor_count: 3 } } } }),
}),
);
- expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: 41, contributors: 3 });
+ expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: 41, contributors: 3, hotspot: null, recentOwner: null });
});
it("keeps an unreported count unknown rather than zero", async () => {
const host = await warmed(fakeHost({ mcp: () => mcpResult({ targets: { "q.py": { type: "file" } } }) }));
- expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: null, contributors: null });
+ expect(await fetchFileContext(host, "q.py")).toEqual({ callerFiles: null, contributors: null, hotspot: null, recentOwner: null });
});
it("is null for a file the index does not know", async () => {
diff --git a/packages/claude-mod/test/overlay.test.ts b/packages/claude-mod/test/overlay.test.ts
index e58075eab..ad7f55bf1 100644
--- a/packages/claude-mod/test/overlay.test.ts
+++ b/packages/claude-mod/test/overlay.test.ts
@@ -1,151 +1,133 @@
import { describe, expect, it } from "vitest";
-import { initialTrail, reduceTrail, type TrailState } from "../src/model/trail";
-import { ACCENT, GROUND, layoutMap, mix, type MapLayout, type PlacedFile } from "../src/views/map";
-import { EDIT_TINT, frameCells, framePixels, resolveOverlay, rippleRadius } from "../src/views/overlay";
-import { feed, importers } from "./django";
+import { GROUND, MAP_PALETTES, TERMINAL_DEFAULT, layoutMap, type MapLayout, type PlacedFile } from "../src/views/map";
+import { NO_LIT, frameCells, framePixels, litPixels, notOnMap, resolveLit, rippleRadius, type Lit } from "../src/views/overlay";
+import { decode, feed, importers } from "./django";
+import { syntheticTree } from "./synthetic";
-const ROOT = "C:\\Users\\dev\\django";
-const ROOT_KEY = "c:/users/dev/django";
const QUERY = "django/db/models/query.py";
-const layout = layoutMap(feed.files, 180, 50, true);
-
-/** The trail after reading these repo files in order, then editing one. */
-function session(reads: string[], edit?: string): TrailState {
- let t = initialTrail;
- for (const r of reads) t = reduceTrail(t, { type: "read", path: `${ROOT_KEY}/${r}` });
- if (edit !== undefined) t = reduceTrail(t, { type: "edit", path: `${ROOT_KEY}/${edit}` });
- return t;
+const MANAGER = "django/db/models/manager.py";
+const HITS = ["tests/queries/tests.py", "tests/queries/test_qs_combinators.py", "tests/queries/test_iterator.py"];
+const pal = MAP_PALETTES.dark;
+const layout = layoutMap(feed.files, { columns: 180, rows: 50, caseInsensitive: true });
+
+/** The recorded Django turn: two searches' matches, two files opened, query.py edited, its importers. */
+const turn: Lit = { hits: HITS, reads: [MANAGER, QUERY], named: [QUERY], importers, edits: [QUERY], edit: QUERY, current: QUERY };
+
+const fileOf = (l: MapLayout, path: string): PlacedFile => l.files[l.index.get(path.toLowerCase()) as number] as PlacedFile;
+
+/** The colors a file's lit pixels hold. */
+function colorsOf(l: MapLayout, pixels: Uint32Array, path: string): Set<number> {
+ const b = litPixels(l, fileOf(l, path));
+ const out = new Set<number>();
+ for (let y = b.y0; y < b.y1; y++) for (let x = b.x0; x < b.x1; x++) out.add(pixels[y * l.width + x] as number);
+ return out;
}
-const withImporters = (t: TrailState) => reduceTrail(t, { type: "callers", edits: t.edits, callers: { status: "ready", paths: importers } });
-
-function centerOf(l: MapLayout, i: number): number {
- const f = l.files[i]!;
- return Math.floor((f.py0 + f.py1 - 1) / 2) * l.width + Math.floor((f.px0 + f.px1 - 1) / 2);
-}
-
-const at = (f: PlacedFile, x: number, y: number) => y * layout.width + x;
-
-describe("resolveOverlay", () => {
- const edited = withImporters(session(["django/db/models/base.py", "django/db/models/manager.py"], QUERY));
- const resolved = resolveOverlay(layout, edited, ROOT);
-
- it("the importer count shown equals the count fetched: drawn plus not drawn", () => {
- expect(importers).toHaveLength(12);
- expect(resolved.overlay.callers.length + resolved.edit!.notDrawn).toBe(importers.length);
- expect(resolved.edit!.name).toBe("query.py");
- });
-
- it("maps reads case-insensitively under the root and counts the rest as not drawn", () => {
- const t = reduceTrail(edited, { type: "read", path: "c:/elsewhere/notes.md" });
- const r = resolveOverlay(layout, t, ROOT);
- expect(r.overlay.reads).toHaveLength(3);
- expect(r.reads).toEqual({ count: 4, capped: false, notDrawn: 1 });
+describe("resolveLit", () => {
+ it("finds every lit path on the map, case aside where paths are case-insensitive", () => {
+ const o = resolveLit(layout, { ...turn, reads: [MANAGER.toUpperCase(), QUERY] });
+ expect(o.reads).toHaveLength(2);
+ expect(o.importers).toHaveLength(importers.length);
+ expect(o.edit).toBe(layout.index.get(QUERY));
+ expect(o.named).toEqual([layout.index.get(QUERY)]);
});
- it("reports what the last search matched, drawn or not", () => {
- expect(resolveOverlay(layout, initialTrail, ROOT).matched).toBeNull();
- const t = reduceTrail(initialTrail, { type: "search", paths: [`${ROOT_KEY}/${QUERY}`, "c:/elsewhere/x.py"] });
- const r = resolveOverlay(layout, t, ROOT);
- expect(r.matched).toBe(2);
- expect(r.overlay.hits).toHaveLength(1);
+ it("on a case-sensitive map only the exact path matches, except named paths, which arrive lowercased", () => {
+ const posix = layoutMap([{ file_path: "src/App.ts", score: 6, nloc: 10 }], { columns: 20, rows: 4, caseInsensitive: false });
+ expect(resolveLit(posix, { ...NO_LIT, reads: ["src/app.ts"] }).reads).toEqual([]);
+ expect(resolveLit(posix, { ...NO_LIT, reads: ["src/App.ts"], named: ["src/app.ts"] })).toMatchObject({ reads: [0], named: [0] });
});
- it("is quiet before any attention", () => {
- const r = resolveOverlay(layout, initialTrail, ROOT);
- expect(r.edit).toBeNull();
- expect(framePixels(layout, r.overlay).pixels).toEqual(layout.base);
+ it("counts touched files that are not on the map", () => {
+ expect(notOnMap(layout, turn)).toBe(0);
+ expect(notOnMap(layout, { ...turn, reads: [...turn.reads, "notes/todo.md"] })).toBe(1);
});
});
-describe("frames", () => {
- const edited = withImporters(session(["django/db/models/base.py", "django/db/models/manager.py"], QUERY));
- const { overlay } = resolveOverlay(layout, edited, ROOT);
- const rest = framePixels(layout, overlay).pixels;
-
- it("outlines a read in orange and dims its inside", () => {
- const f = layout.files[overlay.reads[0]!]!;
- expect(rest[at(f, f.px0, f.py0)]).toBe(ACCENT);
- const inside = at(f, f.px0 + 1, f.py0 + 1);
- expect(rest[inside]).toBe(mix(layout.base[inside]!, 0, 0.4));
- });
+describe("lighting", () => {
+ const { pixels } = framePixels(layout, resolveLit(layout, turn));
- it("fills the edited file pale orange inside an orange outline", () => {
- const q = layout.files[overlay.edited!]!;
- expect(rest[at(q, q.px0, q.py0)]).toBe(ACCENT);
- expect(rest[at(q, q.px0 + 1, q.py0 + 1)]).toBe(EDIT_TINT);
+ it("each role fills its whole tile in its own color, the strongest role winning", () => {
+ expect(colorsOf(layout, pixels, QUERY)).toEqual(new Set([pal.edit]));
+ expect(colorsOf(layout, pixels, MANAGER)).toEqual(new Set([pal.read]));
+ expect(colorsOf(layout, pixels, HITS[0]!)).toEqual(new Set([pal.hit]));
+ expect(colorsOf(layout, pixels, "django/db/models/base.py")).toEqual(new Set([pal.importer]));
});
- it("dots each importer with a dark companion pixel in its cell", () => {
- for (const i of overlay.callers) {
- const c = centerOf(layout, i);
- const y = Math.floor(c / layout.width);
- expect(rest[c]).toBe(ACCENT);
- expect(rest[(y ^ 1) * layout.width + (c % layout.width)]).toBe(GROUND);
+ it("a search's matches glow on whole tiles only: no lit pixel outside a lit file", () => {
+ const lit = framePixels(layout, resolveLit(layout, { ...NO_LIT, hits: HITS })).pixels;
+ const tiles = new Set<number>();
+ for (const h of HITS) {
+ const b = litPixels(layout, fileOf(layout, h));
+ for (let y = b.y0; y < b.y1; y++) for (let x = b.x0; x < b.x1; x++) tiles.add(y * layout.width + x);
}
+ lit.forEach((c, i) => expect(c === layout.base[i] || tiles.has(i)).toBe(true));
});
- it("the ripple reaches importers as it passes and rests with every one dotted", () => {
- const dotted = (t: number) =>
- overlay.callers.filter((i) => framePixels(layout, overlay, { kind: "ripple", t }).pixels[centerOf(layout, i)] === ACCENT).length;
- const counts = [0, 0.25, 0.5, 0.75, 1].map(dotted);
- expect(counts[0]).toBeLessThan(overlay.callers.length);
- for (let k = 1; k < counts.length; k++) expect(counts[k]!).toBeGreaterThanOrEqual(counts[k - 1]!);
- expect(counts[4]).toBe(overlay.callers.length);
- expect(frameCells(layout, overlay, { kind: "ripple", t: 1 })).toBe(frameCells(layout, overlay));
+ it("a fresh search glows brighter, then settles", () => {
+ const o = resolveLit(layout, { ...NO_LIT, hits: HITS });
+ const at = (t: number) => [...colorsOf(layout, framePixels(layout, o, { kind: "flash", t }).pixels, HITS[0]!)][0];
+ expect(at(0)).not.toBe(pal.hit);
+ expect(at(1)).toBe(pal.hit);
});
- it("draws a ring mid-ripple that is gone at rest", () => {
- const mid = framePixels(layout, overlay, { kind: "ripple", t: 0.5 }).pixels;
- expect(mid.filter((c, i) => c !== rest[i]).length).toBeGreaterThan(overlay.callers.length);
+ it("importers ripple out from the edit, all of them at rest", () => {
+ const o = resolveLit(layout, turn);
+ expect(rippleRadius(layout, o)).toBeGreaterThan(0);
+ expect(rippleRadius(layout, resolveLit(layout, { ...turn, importers: [] }))).toBe(0);
+ const lit = (t?: number) =>
+ importers.filter((p) => colorsOf(layout, framePixels(layout, o, t === undefined ? undefined : { kind: "ripple", t }).pixels, p).has(pal.importer)).length;
+ expect(lit(0.05)).toBeLessThan(lit());
});
- it("a search flashes, then settles to a faint tint", () => {
- const t = reduceTrail(initialTrail, { type: "search", paths: [`${ROOT_KEY}/${QUERY}`] });
- const r = resolveOverlay(layout, t, ROOT).overlay;
- const c = centerOf(layout, r.hits[0]!);
- expect(framePixels(layout, r, { kind: "flash", t: 0 }).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.85));
- expect(framePixels(layout, r, { kind: "flash", t: 1 }).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.25));
- expect(framePixels(layout, r).pixels[c]).toBe(mix(layout.base[c]!, ACCENT, 0.25));
+ it("a lit file too small for a pixel still lights one full cell where it sits", () => {
+ const tree = syntheticTree(10_000);
+ const dense = layoutMap(tree.files.slice(0, 4_000), { columns: 120, rows: 24, caseInsensitive: true });
+ expect(dense.dense).toBe(true);
+ const tiny = dense.files.find((f) => f.px1 <= f.px0 || f.py1 <= f.py0)!;
+ const b = litPixels(dense, tiny);
+ expect([b.x1 - b.x0, b.y1 - b.y0, b.y0 % 2]).toEqual([1, 2, 0]);
+ const { pixels: px } = framePixels(dense, resolveLit(dense, { ...NO_LIT, edit: tiny.path, current: tiny.path }));
+ expect([px[b.y0 * dense.width + b.x0], px[(b.y0 + 1) * dense.width + b.x0]]).toEqual([MAP_PALETTES.dark.edit, MAP_PALETTES.dark.edit]);
});
+});
- it("nothing to ripple to: radius 0, whether the edit is off the map or has no importers", () => {
- const off = resolveOverlay(layout, withImporters(session([], "setup.py")), ROOT).overlay;
- expect(off.edited).toBeNull();
- expect(rippleRadius(layout, off)).toBe(0);
- const lonely = reduceTrail(session([], QUERY), { type: "callers", edits: 1, callers: { status: "ready", paths: [] } });
- expect(rippleRadius(layout, resolveOverlay(layout, lonely, ROOT).overlay)).toBe(0);
- expect(rippleRadius(layout, overlay)).toBeGreaterThan(3);
+describe("names", () => {
+ const o = resolveLit(layout, turn);
+ const words = decode(frameCells(layout, o));
+
+ it("the edit's name in amber, opened files in the terminal's own colour, cut out of the tiles", () => {
+ const edit = o.names.find((n) => n.text === "query.py")!;
+ expect(edit.color).toBe(pal.edit);
+ expect(o.names.find((n) => n.text === "manager.py")?.color).toBe(TERMINAL_DEFAULT);
+ for (const n of o.names) {
+ const cell = (n.row * layout.columns + n.col) * 3;
+ expect(String.fromCharCode(words[cell]!)).toBe(n.text[0]);
+ expect([words[cell + 1], words[cell + 2]]).toEqual([n.color, TERMINAL_DEFAULT]);
+ }
});
- it("an edit off the map still dots its importers", () => {
- const off = resolveOverlay(layout, withImporters(session([], "setup.py")), ROOT).overlay;
- const pixels = framePixels(layout, off, { kind: "ripple", t: 0 }).pixels;
- expect(off.callers.every((c) => pixels[centerOf(layout, c)] === ACCENT)).toBe(true);
+ it("names never overlap and stay on the map", () => {
+ const busy = resolveLit(layout, { ...turn, reads: feed.files.slice(0, 60).map((f) => f.file_path) });
+ const cells = busy.names.flatMap((n) => [...n.text].map((_, k) => n.row * 1000 + n.col + k));
+ expect(new Set(cells).size).toBe(cells.length);
+ expect(busy.names.every((n) => n.col >= 0 && n.col + n.text.length <= layout.columns && n.row < layout.rows)).toBe(true);
});
+});
- it("a small edited file is all pale, unlike a small read", () => {
- const small = layout.drawn.map((i) => layout.files[i]!).find((f) => f.px1 - f.px0 < 3 && f.path.startsWith("django/"))!;
- const rel = small.path;
- const asEdit = resolveOverlay(layout, session([], rel), ROOT).overlay;
- const asRead = resolveOverlay(layout, session([rel]), ROOT).overlay;
- const p = at(small, small.px0, small.py0);
- expect(framePixels(layout, asEdit).pixels[p]).toBe(EDIT_TINT);
- expect(framePixels(layout, asRead).pixels[p]).toBe(ACCENT);
+describe("frames", () => {
+ it("an empty turn draws the base, and the ground stays the terminal's own", () => {
+ const words = decode(frameCells(layout, resolveLit(layout, NO_LIT)));
+ expect(framePixels(layout, resolveLit(layout, NO_LIT)).pixels).toEqual(layout.base);
+ expect(layout.base.includes(GROUND)).toBe(true);
+ for (let i = 0; i < words.length; i += 3) expect(words[i + 2] === GROUND).toBe(false);
});
-});
-describe("performance", () => {
- // The budget is 16 ms per frame at 180x50 (npm run bench:map measures it);
- // this guard fails only at five times that, to stay steady under CI load.
- it("lays out Django and encodes a ripple frame within 5x the frame budget", () => {
- const trail = withImporters(session(["django/db/models/base.py"], QUERY));
- const runs = 10;
+ it("a lit frame at 180x50 stays well under budget (5x the bench's 16 ms)", () => {
+ const o = resolveLit(layout, turn);
+ frameCells(layout, o, { kind: "ripple", t: 0.5 });
const start = performance.now();
- for (let k = 0; k < runs; k++) {
- const l = layoutMap(feed.files, 180, 50, true);
- frameCells(l, resolveOverlay(l, trail, ROOT).overlay, { kind: "ripple", t: 0.5 });
- }
- expect((performance.now() - start) / runs).toBeLessThan(16 * 5);
+ frameCells(layout, resolveLit(layout, turn), { kind: "ripple", t: 0.5 });
+ expect(performance.now() - start).toBeLessThan(80);
});
});
diff --git a/packages/claude-mod/test/pane-register.test.ts b/packages/claude-mod/test/pane-register.test.ts
index 6e8953add..53a5b478a 100644
--- a/packages/claude-mod/test/pane-register.test.ts
+++ b/packages/claude-mod/test/pane-register.test.ts
@@ -59,6 +59,7 @@ function fakeDollar(mcp: (tool: string, args: Record<string, unknown>) => Promis
blit: async () => ({}),
},
command: { register: async () => ({}) },
+ config: { list: async () => [] },
settings: { read: async () => ({}) },
};
return { $, calls };
@@ -105,19 +106,38 @@ describe("/lens routing and tabs", () => {
expect(d.calls.mcp).toEqual([]);
});
- it("a tab press switches the body: Map, then Ask with its field", async () => {
+ it("a tab press switches the body: Flow, Map, Ask, Recap; /lens ask opens the Ask tab", async () => {
const d = await session();
await lens(d, "recap");
const tabs = buttonsOf(await pane(d));
- expect(tabs.map((b) => [b.props.hotkey, b.props.label])).toEqual([["1", "Map"], ["2", "Ask"], ["3", "Recap"]]);
+ expect(tabs.map((b) => [b.props.hotkey, b.props.label])).toEqual([["1", "Flow"], ["2", "Map"], ["3", "Ask"], ["4", "Recap"]]);
tabs[1]!.props.onPress();
+ expect(textOf(await pane(d))).toEqual(["Lens map needs the local server: repowise serve --no-ui"]);
+ tabs[2]!.props.onPress();
+ expect(flatten(await pane(d)).find((n) => n.el === "Input")?.props).toMatchObject({ key: "lens-ask", autoFocus: true });
+ tabs[0]!.props.onPress();
+ expect(flatten(await pane(d)).some((n) => n.props.key === "lens-flow")).toBe(true);
+ await lens(d, "ask");
const ask = flatten(await pane(d)).find((n) => n.el === "Input");
expect(ask?.props).toMatchObject({ key: "lens-ask", autoFocus: true });
- tabs[0]!.props.onPress();
- expect(textOf(await pane(d))).toEqual(["Lens map needs the local server: repowise serve --no-ui"]);
});
- it("/lens ask starts the lookup inside the command's own hook and shows the reply with its evidence", async () => {
+ it("a session starts on Flow; with lens_flow off it starts on the Map and Flow leaves the bar", async () => {
+ const d = await session();
+ expect(flatten(await pane(d)).some((n) => n.props.key === "lens-flow")).toBe(true);
+ ({ hooks, events } = await load({ lens_flow: false }));
+ expect(events).not.toContain("turn.step");
+ const off = await session();
+ const shown = await pane(off);
+ expect(buttonsOf(shown).map((b) => b.props.label)).toEqual(["Map", "Ask", "Recap"]);
+ expect(textOf(shown)).toEqual(["Lens map needs the local server: repowise serve --no-ui"]);
+ // A question shows in the Ask tab, with Flow on or off.
+ await lens(off, "ask why does Session merge environment settings?");
+ await settle();
+ expect(textOf(await pane(off)).at(-1)).toContain("**Built from the index** · basis archaeology");
+ });
+
+ it("/lens ask starts the lookup inside the command's own hook; the answer lands in the Ask tab, not in Flow", async () => {
const d = await session();
await lens(d, "ask why does Session merge environment settings?");
// Started before the hook returned: approved as Lens's own call.
@@ -126,6 +146,8 @@ describe("/lens routing and tabs", () => {
const md = textOf(await pane(d)).at(-1)!;
expect(md).toContain("**Built from the index** · basis archaeology");
expect(md).toContain("`ev_8964f795d9001bd297ca`");
+ buttonsOf(await pane(d))[0]!.props.onPress();
+ expect(textOf(await pane(d))).not.toContain("get_why");
});
});
@@ -192,6 +214,7 @@ describe("the Ask field", () => {
await submit(d, "how?");
await settle();
expect(d.calls.mcp).toEqual([]);
+ await lens(d, "ask");
expect(textOf(await pane(d)).at(-1)).toBe("Could not answer: repowise MCP server name not resolved yet");
});
diff --git a/packages/claude-mod/test/pane.test.ts b/packages/claude-mod/test/pane.test.ts
index 7d0c5d7bc..a22da6ee3 100644
--- a/packages/claude-mod/test/pane.test.ts
+++ b/packages/claude-mod/test/pane.test.ts
@@ -10,7 +10,7 @@ import { bandView } from "../src/views/band";
import { BRIEF_PRESS, briefBandRow, briefText, listWithin } from "../src/views/brief";
import { ASK_CHARS, BRIEF_CHARS, savingsLine } from "../src/views/copy";
import type { Node } from "../src/views/elements";
-import { ASK_KEY, askView, paneView, recapRows, recapView, tabsView, type RecapRow } from "../src/views/pane";
+import { ASK_KEY, askView, paneView, recapRows, recapView, tabBar, tabsView, type RecapRow } from "../src/views/pane";
import { health } from "../src/views/review";
import { fixture } from "./fake-host";
@@ -37,13 +37,18 @@ describe("routing", () => {
expect(askRoute("how does filter() build SQL?")).toEqual({ tool: "get_answer", args: { question: "how does filter() build SQL?" } });
});
- it("/lens arguments: a tab, or ask with its question", () => {
+ it("/lens arguments: a tab, or a question that opens the Ask tab", () => {
expect(lensCommand("")).toEqual({ tab: null, question: null });
expect(lensCommand("recap")).toEqual({ tab: "recap", question: null });
expect(lensCommand(" MAP ")).toEqual({ tab: "map", question: null });
+ expect(lensCommand("flow")).toEqual({ tab: "flow", question: null });
expect(lensCommand("ask")).toEqual({ tab: "ask", question: null });
expect(lensCommand("ask why is QuerySet lazy?")).toEqual({ tab: "ask", question: "why is QuerySet lazy?" });
expect(lensCommand("frobnicate")).toEqual({ tab: null, question: null });
+ expect(lensCommand("trail")).toEqual({ tab: null, question: null });
+ // A tab not on the bar is not a tab.
+ expect(lensCommand("flow", ["map", "ask", "recap"])).toEqual({ tab: null, question: null });
+ expect(lensCommand("ask how?", ["map", "ask", "recap"])).toEqual({ tab: "ask", question: "how?" });
});
it("only an answer that says it had no provider is known to have used no model", () => {
@@ -120,11 +125,16 @@ describe("Ask replies as Markdown", () => {
});
describe("tabs and the Ask tab", () => {
- it("draws three tabs with the shown one at full strength", () => {
- const tabs = tabsView("ask");
- expect(texts(tabs)).toEqual(["1: Map", "2: Ask", "3: Recap"]);
+ it("draws the tab bar with the shown one at full strength; Ask is a tab", () => {
+ const tabs = tabsView("map");
+ expect(texts(tabs)).toEqual(["1: Flow", "2: Map", "3: Ask", "4: Recap"]);
if (tabs.type !== "Box") throw new Error("expected a Box");
- expect(tabs.children.map((c) => (c.type === "Button" ? c.props.dimColor === true : null))).toEqual([true, false, true]);
+ expect(tabs.children.map((c) => (c.type === "Button" ? c.props.dimColor === true : null))).toEqual([true, false, true, true]);
+ const asking = tabsView("ask");
+ if (asking.type !== "Box") throw new Error("expected a Box");
+ expect(asking.children.map((c) => (c.type === "Button" ? c.props.dimColor === true : null))).toEqual([true, true, false, true]);
+ expect(texts(tabsView("map", tabBar(false)))).toEqual(["1: Map", "2: Ask", "3: Recap"]);
+ expect(tabBar(true)).toEqual(["flow", "map", "ask", "recap"]);
});
it("the field takes the keyboard when the pane does, pre-filled only by Why", () => {
@@ -148,7 +158,7 @@ describe("tabs and the Ask tab", () => {
});
it("paneView puts the tabs over the body", () => {
- expect(texts(paneView("recap", { type: "Text", props: {}, children: ["body"] }))).toEqual(["1: Map", "2: Ask", "3: Recap", "body"]);
+ expect(texts(paneView("recap", { type: "Text", props: {}, children: ["body"] }))).toEqual(["1: Flow", "2: Map", "3: Ask", "4: Recap", "body"]);
});
});
diff --git a/packages/claude-mod/test/register.test.ts b/packages/claude-mod/test/register.test.ts
index d8f5f31f3..f932d57b8 100644
--- a/packages/claude-mod/test/register.test.ts
+++ b/packages/claude-mod/test/register.test.ts
@@ -126,7 +126,8 @@ function fakeDollar(o: DollarOptions = {}) {
return "/work/app";
},
};
- const $: ModApi = { session, fs: fsFor(o), process: processFake, http: httpFor(o, calls), mcp: mcpFor(o, calls), prompt: promptFor(calls), ui: uiFor(calls), command: { register: async () => ({}) }, settings: { read: async () => ({}) } };
+ const $: ModApi = { session, fs: fsFor(o), process: processFake, http: httpFor(o, calls), mcp: mcpFor(o, calls), prompt: promptFor(calls), ui: uiFor(calls), command: { register: async () => ({}) }, config: { list: async () => [] },
+ settings: { read: async () => ({}) } };
const hold = () => {
gate.hold = true;
gate.wait = new Promise<void>((resolve) => (release = resolve));
@@ -150,6 +151,7 @@ describe("register", () => {
"classic.PostToolUse",
"command.run:lens",
"session.start",
+ "session.end",
"tool.call",
"tool.check",
"turn.complete",
diff --git a/packages/claude-mod/test/session.test.ts b/packages/claude-mod/test/session.test.ts
index 06a2b330e..dafa9b615 100644
--- a/packages/claude-mod/test/session.test.ts
+++ b/packages/claude-mod/test/session.test.ts
@@ -1,7 +1,7 @@
import { describe, expect, it } from "vitest";
import { fromTurnComplete } from "../src/model/events";
import { initialReview } from "../src/model/review";
-import { hintFor, initialSession, reduce, type SessionAction, type SessionState } from "../src/model/session";
+import { clearedConversation, hintFor, initialSession, reduce, type SessionAction, type SessionState } from "../src/model/session";
function run(actions: SessionAction[], from: SessionState = initialSession): SessionState {
return actions.reduce(reduce, from);
@@ -40,7 +40,7 @@ describe("session reducer", () => {
review: initialReview,
lastReview: null,
touched: [],
- pane: { tab: "map", draft: "" },
+ pane: { tab: "flow", draft: "" },
ask: { phase: "idle" },
modelAsks: 0,
compacted: false,
@@ -128,3 +128,18 @@ describe("events", () => {
expect(fromTurnComplete({ agentId: "a1" })).toBeNull();
});
});
+
+describe("a /clear", () => {
+ it("keeps what the index said and the tab; drops what the conversation did", () => {
+ const ctx = { callerFiles: 3, contributors: 1, hotspot: false, recentOwner: null };
+ let s = reduce(initialSession, { type: "discovered", mode: "full", freshness: null, repoRoot: "/r" });
+ s = reduce(s, { type: "contextLoaded", file: "a.py", context: ctx });
+ s = reduce(s, { type: "touched", path: "a.py" });
+ s = reduce(s, { type: "savings", delta: { tokens: 10, dollars: 0.1 } as never });
+ s = reduce(s, { type: "tab", tab: "map", draft: "why" });
+ s = reduce(s, { type: "compacted" });
+ const c = clearedConversation(s);
+ expect([c.mode, c.repoRoot, c.contexts["a.py"], c.pane]).toEqual(["full", "/r", ctx, { tab: "map", draft: "" }]);
+ expect([c.touched, c.savings, c.compacted, c.lastReview, c.ask]).toEqual([[], null, false, null, { phase: "idle" }]);
+ });
+});
diff --git a/packages/claude-mod/test/spinner.test.ts b/packages/claude-mod/test/spinner.test.ts
index a8c63779a..540118839 100644
--- a/packages/claude-mod/test/spinner.test.ts
+++ b/packages/claude-mod/test/spinner.test.ts
@@ -36,7 +36,7 @@ describe("fileTarget", () => {
});
describe("running tool and context reducers", () => {
- const ctx = { callerFiles: 41, contributors: 3 };
+ const ctx = { callerFiles: 41, contributors: 3, hotspot: null, recentOwner: null };
it("tracks the file tool running now; an overlapping call's end does not clear it", () => {
let s = reduce(initialSession, { type: "toolStarted", tool: { id: "a", file: "x.py" } });
@@ -62,18 +62,18 @@ describe("spinner suffix", () => {
const running: SessionState = { ...initialSession, running: { id: "a", file: "django/db/models/query.py" } };
it("names the file, its caller files and contributors once the context has landed", () => {
- const s = { ...running, contexts: { "django/db/models/query.py": { callerFiles: 41, contributors: 3 } } };
+ const s = { ...running, contexts: { "django/db/models/query.py": { callerFiles: 41, contributors: 3, hotspot: null, recentOwner: null } } };
expect(spinnerSuffix(s)).toBe("query.py · 41 caller files · 3 contributors");
});
it("says nothing while the context is still on its way, or when no file tool runs", () => {
expect(spinnerSuffix(running)).toBeNull();
- expect(spinnerSuffix({ ...running, running: null, contexts: { "a.py": { callerFiles: 1, contributors: 1 } } })).toBeNull();
+ expect(spinnerSuffix({ ...running, running: null, contexts: { "a.py": { callerFiles: 1, contributors: 1, hotspot: null, recentOwner: null } } })).toBeNull();
});
it("uses singulars, thousands separators, and leaves out unknown or zero counts", () => {
- expect(spinnerLine("a.py", { callerFiles: 1, contributors: 1 })).toBe("a.py · 1 caller file · 1 contributor");
- expect(spinnerLine("src/a.py", { callerFiles: 1204, contributors: null })).toBe("a.py · 1,204 caller files");
- expect(spinnerLine("a.py", { callerFiles: 0, contributors: null })).toBe("a.py");
+ expect(spinnerLine("a.py", { callerFiles: 1, contributors: 1, hotspot: null, recentOwner: null })).toBe("a.py · 1 caller file · 1 contributor");
+ expect(spinnerLine("src/a.py", { callerFiles: 1204, contributors: null, hotspot: null, recentOwner: null })).toBe("a.py · 1,204 caller files");
+ expect(spinnerLine("a.py", { callerFiles: 0, contributors: null, hotspot: null, recentOwner: null })).toBe("a.py");
});
});
diff --git a/packages/claude-mod/test/story.test.ts b/packages/claude-mod/test/story.test.ts
new file mode 100644
index 000000000..4af9c8fdc
--- /dev/null
+++ b/packages/claude-mod/test/story.test.ts
@@ -0,0 +1,161 @@
+// The map's view of the current turn, read from Flow's record (built here
+// with Flow's own reducer from the recorded Django calls' shapes) and, with
+// Flow off, from the map's trail.
+import { describe, expect, it } from "vitest";
+import { activityOf, initialFlow, reduceFlow, toolEnded, type FlowState } from "../src/model/flow";
+import { combineCallers, litFromFlow, litFromTrail, storyFromFlow, storyFromTrail, storyTurn, withImporters } from "../src/model/story";
+import type { Callers } from "../src/model/trail";
+import { NO_LIT } from "../src/views/overlay";
+import { initialTrail, reduceTrail } from "../src/model/trail";
+import { importers } from "./django";
+
+const ROOT = "C:\\work\\django";
+const QUERY = "django/db/models/query.py";
+let n = 0;
+
+type Step = "turn" | { tool: string; file?: string; pattern?: string; hits?: string[]; edit?: [string, string] };
+
+/** The call `tool.call` would see for a step. */
+function callOf(step: Exclude<Step, "turn">) {
+ return {
+ tool: step.tool,
+ tool_use_id: `toolu_${n++}`,
+ ...(step.file === undefined ? {} : { file_path: `${ROOT}\\${step.file.replace(/\//g, "\\")}` }),
+ ...(step.pattern === undefined ? {} : { pattern: step.pattern }),
+ ...(step.edit === undefined ? {} : { old_string: step.edit[0], new_string: step.edit[1] }),
+ };
+}
+
+function nextTurn(s: FlowState): FlowState {
+ const ended = reduceFlow(s, { type: "turnEnded", at: n, durationMs: 1, end: "answer" });
+ return reduceFlow(ended, { type: "turnStarted", turnId: null, prompt: "", at: n++ });
+}
+
+/** One call, started and ended as Flow records it. */
+function called(s: FlowState, step: Exclude<Step, "turn">): FlowState {
+ const e = callOf(step);
+ const activity = activityOf(e, n, ROOT);
+ const started = activity === null ? s : reduceFlow(s, { type: "toolStarted", activity });
+ const ended = toolEnded(e, { result: step.hits === undefined ? {} : { filenames: step.hits } }, n, ROOT);
+ return ended === null ? started : reduceFlow(started, ended);
+}
+
+/** Flow after these calls, a new turn at each "turn". */
+function flow(steps: Step[]): FlowState {
+ return steps.reduce((s, step) => (step === "turn" ? nextTurn(s) : called(s, step)), initialFlow);
+}
+
+/** The recorded Django turn: two searches, two files opened, query.py edited by one line. */
+const django = flow([
+ { tool: "Read", file: "setup.py" },
+ "turn",
+ { tool: "Grep", pattern: "class QuerySet", hits: ["django\\db\\models\\query.py", "tests\\queries\\tests.py"] },
+ { tool: "Glob", pattern: "django/db/models/sql/*.py", hits: ["django\\db\\models\\sql\\query.py"] },
+ { tool: "Read", file: "django/db/models/manager.py" },
+ { tool: "Read", file: QUERY },
+ { tool: "Edit", file: QUERY, edit: ["a", "a\nb"] },
+]);
+
+describe("from Flow's record", () => {
+ it("the story is the latest turn that touched a file: searches with counts, files opened once, edits with their size", () => {
+ expect(storyFromFlow(django)).toEqual({
+ searched: [
+ { pattern: "class QuerySet", hits: 2 },
+ { pattern: "django/db/models/sql/*.py", hits: 1 },
+ ],
+ opened: [
+ { name: "manager.py", namedBy: null },
+ { name: "query.py", namedBy: null },
+ ],
+ edited: [{ name: "query.py", lines: { delta: 1 } }],
+ });
+ });
+
+ it("a new turn with no file yet keeps the last one that had any; nothing before any", () => {
+ const later = flow([{ tool: "Read", file: "a.py" }, "turn", { tool: "Bash" }]);
+ expect(storyTurn(later)?.seq).toBe(1);
+ expect(storyFromFlow(initialFlow)).toEqual({ searched: [], opened: [], edited: [] });
+ expect(litFromFlow(initialFlow)).toMatchObject({ reads: [], edit: null });
+ });
+
+ it("what the turn lit: matches, opened files, the edit and the current step, repo-relative", () => {
+ expect(litFromFlow(django)).toEqual({
+ hits: [QUERY, "tests/queries/tests.py", "django/db/models/sql/query.py"],
+ reads: ["django/db/models/manager.py", QUERY],
+ named: [],
+ importers: [],
+ edits: [QUERY],
+ edit: QUERY,
+ current: QUERY,
+ });
+ });
+
+ it("files a Repowise reply named this turn are lit, and the opened row says which tool named one", () => {
+ const turn = storyTurn(django)!;
+ const naming = { id: "toolu_rw", tool: "get_context", at: 1, turn: turn.seq };
+ const named: FlowState = {
+ ...django,
+ named: { [QUERY]: naming, "old/file.py": { ...naming, turn: turn.seq - 1 } },
+ turns: django.turns.map((t) => (t !== turn ? t : { ...t, activities: t.activities.map((a) => (a.paths[0] === QUERY ? { ...a, namedBy: naming } : a)) })),
+ };
+ expect(litFromFlow(named).named).toEqual([QUERY]);
+ expect(storyFromFlow(named).opened[1]).toEqual({ name: "query.py", namedBy: "get_context" });
+ });
+});
+
+describe("with Flow off, from the map's trail", () => {
+ let t = reduceTrail(initialTrail, { type: "read", path: "c:/work/django/django/db/models/manager.py" });
+ t = reduceTrail(t, { type: "search", paths: ["c:/work/django/tests/queries/tests.py", "c:/elsewhere/x.py"] });
+ t = reduceTrail(t, { type: "edit", path: "c:/work/django/django/db/models/query.py" });
+
+ it("lights the trail's files relative to the repo, dropping any outside it", () => {
+ expect(litFromTrail(t, ROOT, true)).toEqual({
+ hits: ["tests/queries/tests.py"],
+ reads: ["django/db/models/manager.py", QUERY],
+ named: [],
+ importers: [],
+ edits: [QUERY],
+ edit: QUERY,
+ current: QUERY,
+ });
+ });
+
+ it("tells the story without patterns or sizes, which only Flow records", () => {
+ expect(storyFromTrail(t)).toEqual({
+ searched: [{ pattern: "", hits: 2 }],
+ opened: [
+ { name: "manager.py", namedBy: null },
+ { name: "query.py", namedBy: null },
+ ],
+ edited: [{ name: "query.py", lines: null }],
+ });
+ expect(storyFromTrail(initialTrail)).toEqual({ searched: [], opened: [], edited: [] });
+ });
+});
+
+describe("withImporters", () => {
+ const lit = litFromFlow(django);
+ const asked = (answers: Record<string, Callers>) => (p: string) => answers[p] ?? null;
+
+ it("joins the importers of the turn's edit, with what it reaches", () => {
+ const { lit: joined, reach } = withImporters(lit, asked({ [QUERY]: { status: "ready", paths: importers } }));
+ expect(joined.importers).toEqual(importers);
+ expect(reach).toMatchObject({ edit: QUERY, callers: { status: "ready" } });
+ expect(reach?.opened.has("django/db/models/manager.py")).toBe(true);
+ });
+
+ it("while the lookup runs: no importers yet, the reach says loading; nothing asked, no reach", () => {
+ expect(withImporters(lit, asked({ [QUERY]: { status: "loading" } }))).toMatchObject({ lit: { importers: [] }, reach: { callers: { status: "loading" } } });
+ expect(withImporters(lit, asked({ "other.py": { status: "ready", paths: ["x"] } })).reach).toBeNull();
+ expect(withImporters(NO_LIT, asked({})).reach).toBeNull();
+ });
+
+ it("several edits: their importers as one set, the edited files themselves left out", () => {
+ const two = { ...lit, edits: ["a.py", "b.py"], edit: "b.py" };
+ const joined = withImporters(two, asked({ "a.py": { status: "ready", paths: ["x.py", "b.py"] }, "b.py": { status: "ready", paths: ["x.py", "y.py"] } }));
+ expect(joined.lit.importers).toEqual(["x.py", "y.py"]);
+ expect(combineCallers([{ status: "failed" }], new Set())).toEqual({ status: "failed" });
+ expect(combineCallers([{ status: "failed" }, { status: "loading" }], new Set())).toEqual({ status: "loading" });
+ expect(combineCallers([], new Set())).toBeNull();
+ });
+});
diff --git a/packages/claude-mod/test/synthetic.ts b/packages/claude-mod/test/synthetic.ts
new file mode 100644
index 000000000..c69c4cd11
--- /dev/null
+++ b/packages/claude-mod/test/synthetic.ts
@@ -0,0 +1,31 @@
+// A synthetic repository, deterministic (a fixed-seed generator, no
+// randomness between runs), for scale cases the recorded Django feed cannot
+// cover: n files over a few levels of folders, sizes skewed like real code
+// (many small files, a few large). Labelled synthetic wherever it is used.
+import type { MapFile } from "../src/views/map";
+
+/** A small linear congruential generator: the same sequence for the same seed. */
+function lcg(seed: number): () => number {
+ let s = seed >>> 0;
+ return () => {
+ s = (Math.imul(s, 1_664_525) + 1_013_904_223) >>> 0;
+ return s / 0x1_0000_0000;
+ };
+}
+
+const TOP = ["src", "lib", "tests", "docs", "tools", "packages", "services", "web"];
+
+/** `n` files, largest first (as the health-map feed orders them), with the repository's total. */
+export function syntheticTree(n: number, seed = 7): { files: MapFile[]; total: number } {
+ const next = lcg(seed);
+ const files: MapFile[] = [];
+ for (let i = 0; i < n; i++) {
+ const top = TOP[Math.floor(next() * TOP.length)] as string;
+ const mid = `m${Math.floor(next() * 24)}`;
+ const leaf = `d${Math.floor(next() * 12)}`;
+ const nloc = Math.max(1, Math.round(20 / (next() + 0.02) ** 1.3));
+ files.push({ file_path: `${top}/${mid}/${leaf}/f${i}.py`, score: Math.round(next() * 100) / 10, nloc });
+ }
+ files.sort((a, b) => b.nloc - a.nloc || (a.file_path < b.file_path ? -1 : 1));
+ return { files, total: n };
+}
diff --git a/packages/claude-mod/test/trail.test.ts b/packages/claude-mod/test/trail.test.ts
index 90188a574..879641b94 100644
--- a/packages/claude-mod/test/trail.test.ts
+++ b/packages/claude-mod/test/trail.test.ts
@@ -2,7 +2,8 @@ import { describe, expect, it } from "vitest";
import { absoluteKey, absolutePath, fromToolCall, relativeTo } from "../src/model/events";
import { initialTrail, reduceTrail, type TrailAction } from "../src/model/trail";
import { layoutMap } from "../src/views/map";
-import { resolveOverlay } from "../src/views/overlay";
+import { litFromTrail } from "../src/model/story";
+import { notOnMap, resolveLit } from "../src/views/overlay";
import { fixture } from "./fake-host";
/** Tool calls recorded from a headless Claude Code 2.1.288 run in a Django copy, its root renamed to C:/work/django (long strings cut). */
@@ -129,16 +130,16 @@ describe("paths", () => {
});
it("a Windows read lands on its map cell regardless of separators and case", () => {
- const layout = layoutMap([{ file_path: "django/db/models/query.py", score: 6, nloc: 10 }], 4, 2, true);
+ const layout = layoutMap([{ file_path: "django/db/models/query.py", score: 6, nloc: 10 }], { columns: 4, rows: 2, caseInsensitive: true });
const action = fromToolCall({ tool: "Read", file_path: "c:\\users\\dev\\DJANGO\\Django\\DB\\models\\query.py" }, ok, win);
const trail = reduceTrail(initialTrail, action as TrailAction);
- expect(resolveOverlay(layout, trail, "C:\\Users\\Dev\\django").overlay.reads).toEqual([0]);
+ expect(resolveLit(layout, litFromTrail(trail, "C:\\Users\\Dev\\django", true)).reads).toEqual([0]);
});
it("a POSIX read differing only in case is off the map", () => {
- const layout = layoutMap([{ file_path: "src/App.ts", score: 6, nloc: 10 }], 4, 2, false);
+ const layout = layoutMap([{ file_path: "src/App.ts", score: 6, nloc: 10 }], { columns: 4, rows: 2, caseInsensitive: false });
const trail = reduceTrail(initialTrail, { type: "read", path: "/repo/src/app.ts" });
- expect(resolveOverlay(layout, trail, "/repo").reads.notDrawn).toBe(1);
+ expect(notOnMap(layout, litFromTrail(trail, "/repo", false))).toBe(1);
});
});
diff --git a/packages/claude-mod/test/turnFacts.test.ts b/packages/claude-mod/test/turnFacts.test.ts
new file mode 100644
index 000000000..90c9d6fe0
--- /dev/null
+++ b/packages/claude-mod/test/turnFacts.test.ts
@@ -0,0 +1,145 @@
+// The turn dashboard's figures: what an edit reaches that Claude did not look
+// at (over a blast radius recorded on an indexed Django copy,
+// test/fixtures/flow/blast_query.json), the working set and how Claude came
+// to each file, the bytes that filled its context, and the Repowise answers
+// that came from the index before an edit.
+import { describe, expect, it } from "vitest";
+import { activityOf, initialFlow, reduceFlow, toolEnded, type FlowAction, type FlowState } from "../src/model/flow";
+import {
+ answeredBeforeEdit,
+ beforeAccept,
+ blastFacts,
+ contextBytes,
+ editedFiles,
+ firstEditMs,
+ openedKeys,
+ testsRun,
+ workingSet,
+ type BlastResponse,
+} from "../src/model/turnFacts";
+import { fixture } from "./fake-host";
+
+const ROOT = "C:\\work\\django";
+const QUERY = "django/db/models/query.py";
+const call = (tool: string, id: string, args: Record<string, unknown> = {}) => ({ tool, tool_use_id: id, ...args });
+const start = (tool: string, id: string, at: number, args: Record<string, unknown> = {}): FlowAction => ({
+ type: "toolStarted",
+ activity: activityOf(call(tool, id, args), at, ROOT)!,
+});
+const end = (tool: string, id: string, at: number, outcome: unknown): FlowAction => toolEnded(call(tool, id), outcome, at, ROOT)!;
+const run = (actions: FlowAction[], from: FlowState = initialFlow) => actions.reduce(reduceFlow, from);
+const abs = (rel: string) => `${ROOT}\\${rel.replace(/\//g, "\\")}`;
+const BLAST = JSON.parse(fixture("flow/blast_query.json")) as BlastResponse;
+const facts = blastFacts(QUERY, BLAST);
+
+/** get_context names query.py; Claude reads it and an importer, greps, edits query.py, runs one test folder, asks get_risk after the edit. */
+function turn(): FlowState {
+ return run([
+ { type: "turnStarted", turnId: "t1", prompt: "edit", at: 1_000 },
+ start("mcp__repowise__get_context", "c1", 2_000, { targets: [QUERY] }),
+ end("mcp__repowise__get_context", "c1", 2_400, { text: fixture("flow/get_context.json") }),
+ start("Read", "r1", 3_000, { file_path: abs(QUERY) }),
+ end("Read", "r1", 3_100, { text: "x".repeat(1_000) }),
+ start("Grep", "g1", 4_000, { pattern: "QuerySet" }),
+ end("Grep", "g1", 4_100, { result: { filenames: ["django\\contrib\\contenttypes\\fields.py"] }, text: "y".repeat(100) }),
+ start("Read", "r2", 5_000, { file_path: abs("django/contrib/contenttypes/fields.py") }),
+ end("Read", "r2", 5_100, { text: "z".repeat(500) }),
+ start("Read", "r3", 5_500, { file_path: abs("django/utils/tree.py") }),
+ end("Read", "r3", 5_600, { text: "t".repeat(50) }),
+ start("Edit", "e1", 9_000, { file_path: abs(QUERY), old_string: "a", new_string: "b" }),
+ end("Edit", "e1", 9_100, { text: "ok" }),
+ { type: "blastLanded", path: QUERY, facts },
+ start("Bash", "b1", 10_000, { command: "python tests/runtests.py queries" }),
+ end("Bash", "b1", 20_000, { text: "w".repeat(200) }),
+ start("mcp__repowise__get_risk", "c2", 21_000, { targets: [QUERY] }),
+ end("mcp__repowise__get_risk", "c2", 21_600, { text: fixture("flow/get_risk.json") }),
+ start("mcp__repowise__get_why", "c3", 22_000, { query: "why" }),
+ end("mcp__repowise__get_why", "c3", 22_500, { text: fixture("flow/get_why.json") }),
+ { type: "turnEnded", at: 30_000, durationMs: 29_000, end: "answer" },
+ ]);
+}
+const last = (s: FlowState) => s.turns.at(-1)!;
+
+describe("blast radius facts", () => {
+ it("reads direct importers, co-change partners strongest first, and the tests that reach the file, as the server gave them", () => {
+ expect(facts.importers).toHaveLength(12);
+ expect(facts.importers).not.toContain(QUERY);
+ expect(facts.cochange[0]).toEqual({ path: "tests/queries/tests.py", score: 0.8024 });
+ expect(facts.cochange.map((c) => c.score)).toEqual([...facts.cochange.map((c) => c.score)].sort((a, b) => b - a));
+ expect(facts.tests).toMatchObject({ total: 17, basis: "inferred" });
+ expect(facts.tests!.files).toHaveLength(17);
+ });
+
+ it("measured tests win over inferred; none, or no impact block, is null; another file's warnings are not this one's", () => {
+ const measured: BlastResponse = { test_impact: { files: [{ source_file: "a.py", measured_tests: ["t.py"], measured_tests_total: 1, inferred_tests_total: 9 }] } };
+ expect(blastFacts("a.py", measured).tests).toEqual({ total: 1, files: ["t.py"], basis: "measured" });
+ expect(blastFacts("a.py", { test_impact: { files: [{ source_file: "a.py" }] } }).tests).toBeNull();
+ expect(blastFacts("a.py", {})).toEqual({ importers: [], cochange: [], tests: null });
+ expect(blastFacts("a.py", { cochange_warnings: [{ changed: "b.py", missing_partner: "c.py", score: 1 }] }).cochange).toEqual([]);
+ });
+});
+
+describe("before you accept", () => {
+ it("per edited file, only what Claude did not look at: importers not opened, co-change partners not opened, tests not run", () => {
+ const s = turn();
+ const [g] = beforeAccept(s, last(s));
+ expect(g!.path).toBe(QUERY);
+ expect(g!.importers).toEqual({ total: 12, opened: 1 });
+ expect(g!.cochange.map((c) => c.path)).toEqual(["tests/queries/tests.py", "django/db/models/sql/query.py"]);
+ // `runtests.py queries` names the tests/queries folder: its test files count as run.
+ expect(g!.tests).toEqual({ total: 17, run: testsRun(s, facts.tests!.files), basis: "inferred" });
+ expect(g!.tests!.run).toBeGreaterThan(0);
+ expect(g!.tests!.run).toBeLessThan(17);
+ });
+
+ it("quiet when Claude looked at everything, or no blast radius landed", () => {
+ const small = { importers: ["django/utils/tree.py"], cochange: [{ path: "django/utils/tree.py", score: 0.5 }], tests: null };
+ const s = run([{ type: "blastLanded", path: QUERY, facts: small }], turn());
+ expect(beforeAccept(s, last(s))).toEqual([]);
+ const none = run([{ type: "turnStarted", turnId: "t", prompt: "", at: 0 }, start("Edit", "e", 1, { file_path: abs("a.py") }), end("Edit", "e", 2, {})]);
+ expect(beforeAccept(none, last(none))).toEqual([]);
+ });
+
+ it("tests count as run only when a test command names them, as whole words, never by a generic name", () => {
+ const s = (command: string) => run([start("Bash", "b", 1, { command })]);
+ const tests = ["tests/queries/tests.py", "tests/async/test_async_queryset.py"];
+ expect(testsRun(s("pytest tests/async/test_async_queryset.py"), tests)).toBe(1);
+ expect(testsRun(s("python -m pytest -k test_async_queryset"), tests)).toBe(1);
+ expect(testsRun(s("python runtests.py"), tests)).toBe(0);
+ expect(testsRun(s("cat tests/async/test_async_queryset.py"), tests)).toBe(0);
+ expect(testsRun(s("pytest test_async_querysets_more"), tests)).toBe(0);
+ expect(testsRun(s("npm test -- queries async"), tests)).toBe(2);
+ });
+
+ it("edited files once each in the order edited; a failed edit is not one", () => {
+ const s = run([start("Edit", "a", 1, { file_path: abs("b.py") }), start("Write", "b", 2, { file_path: abs("a.py") }), start("Edit", "c", 3, { file_path: abs("B.py") }), start("Edit", "d", 4, { file_path: abs("c.py") }), end("Edit", "d", 5, null)]);
+ expect(editedFiles(last(s))).toEqual(["b.py", "a.py"]);
+ expect(openedKeys(s)).toEqual(new Set(["b.py", "a.py", "c.py"]));
+ });
+});
+
+describe("the working set", () => {
+ it("edited first, then reads; each with how Claude came to it: the Repowise tool that named it, a search, or directly", () => {
+ const s = turn();
+ expect(workingSet(s, last(s))).toEqual([
+ { path: QUERY, kind: "edited", via: { kind: "repowise", tool: "get_context" } },
+ { path: "django/contrib/contenttypes/fields.py", kind: "read", via: { kind: "search" } },
+ { path: "django/utils/tree.py", kind: "read", via: { kind: "direct" } },
+ ]);
+ });
+});
+
+describe("context and timing", () => {
+ it("bytes of each kind of result Claude received this turn, and when it first edited", () => {
+ const s = turn();
+ const t = last(s);
+ const rw = t.activities.filter((a) => a.kind === "repowise").reduce((n, a) => n + (a.bytes ?? 0), 0);
+ expect(contextBytes(t)).toEqual({ repowise: rw, read: 1_550, search: 100, shell: 200, other: 2 });
+ expect(firstEditMs(t)).toBe(8_000);
+ expect(firstEditMs({ ...t, activities: [] })).toBeNull();
+ });
+
+ it("a Repowise call about a file Claude had already edited came from the index before that edit; the others did not", () => {
+ expect(answeredBeforeEdit(turn())).toEqual(new Set(["c2"]));
+ });
+});
diff --git a/plugins/claude-code/.claude-plugin/plugin.json b/plugins/claude-code/.claude-plugin/plugin.json
index dff618c92..0ed7e1fc0 100644
--- a/plugins/claude-code/.claude-plugin/plugin.json
+++ b/plugins/claude-code/.claude-plugin/plugin.json
@@ -29,11 +29,23 @@
"description": "After a turn that edits files, review the working tree with get_change_risk and show the result beneath Claude's answer.",
"default": true
},
+ "lens_flow": {
+ "type": "boolean",
+ "title": "Lens Flow tab",
+ "description": "Show a dashboard of each turn in the /lens pane's Flow tab: what an edit reaches that Claude did not look at, the files it worked from, what filled its context, and what Repowise answered.",
+ "default": true
+ },
"lens_pane_autoopen": {
"type": "boolean",
"title": "Open the Lens map on the first read",
"description": "Opens the Lens map pane when Claude first reads a file, if the terminal is wide enough to place it without asking. /lens opens it at any time.",
"default": false
+ },
+ "lens_map_health": {
+ "type": "boolean",
+ "title": "Lens map health colours",
+ "description": "Colours the Lens map's tiles by code health from the start. Off, the map is quiet tiles that light up with the files Claude touches; the Health colours button in the map turns the bands on at any time.",
+ "default": false
}
},
"keywords": [
diff --git a/plugins/claude-code/CHANGELOG.md b/plugins/claude-code/CHANGELOG.md
index b6c243b47..e21ad160c 100644
--- a/plugins/claude-code/CHANGELOG.md
+++ b/plugins/claude-code/CHANGELOG.md
@@ -2,6 +2,33 @@
All notable changes to the Repowise Claude Code plugin are documented here.
+## Unreleased
+
+### Added
+- Lens, a Claude Code mod that ships in the plugin (`hooks/lens/lens.js`,
+ registered through the `modules` entry in `hooks.json`). It shows the index
+ to the person at the keyboard: setup, freshness and savings rows above the
+ prompt, the file's caller and contributor counts in the spinner, margin notes
+ under Edit and Write repeating what the augment hook flagged, a row under
+ Bash output `repowise distill` shortened, a `get_change_risk` review beneath
+ Claude's answer after a turn that edits files (with `Run tests`, `Why` and
+ `Details` buttons), and a `/lens` pane with Flow (a dashboard of each turn
+ with Repowise), a map of the repo lit by Claude's turn with its story under
+ it, an Ask tab (`get_why` or `get_answer`) and a session recap. After a compaction it offers
+ a `Brief Claude` button. In the desktop app the map draws as SVG.
+- Six `userConfig` toggles: `lens_margin`, `lens_squeeze`, `lens_review` and
+ `lens_flow` (on by default), and `lens_pane_autoopen` and `lens_map_health`
+ (off).
+- Lens needs Claude Code 2.1.287 or later. Older versions, and sessions where
+ mods are switched off, load the rest of the plugin unchanged. Lens never
+ denies, holds or rewrites Claude's tool calls. It approves only its own
+ read-only calls to this plugin's MCP server (`get_context`,
+ `get_change_risk`, `get_why`, `get_answer`), and sends Claude nothing
+ without a button press. Ask questions that do not start with "why" go to
+ `get_answer`, which may use the model your repo configures. See
+ [docs/agent/LENS.md](../../docs/agent/LENS.md) and its
+ [footprint](../../docs/agent/LENS.md#footprint).
+
## 0.54.0
### Changed
diff --git a/plugins/claude-code/README.md b/plugins/claude-code/README.md
index 689ab9138..35c3bf373 100644
--- a/plugins/claude-code/README.md
+++ b/plugins/claude-code/README.md
@@ -125,6 +125,28 @@ No LLM, no network. (`repowise init` installs the same hooks in
`~/.claude/settings.json`; running both is safe — duplicate enrichment is
de-duplicated.)
+## Lens
+
+Lens is the part of the plugin you see, a Claude Code mod that ships in
+`hooks/lens/`. It adds the file's reach to the spinner, margin notes under
+edits, a row under output `repowise distill` shortened, a change review under
+Claude's answer after a turn that edits files, and a `/lens` pane with Flow (a dashboard
+of each turn: what an edit reaches, where Claude's context came from, what
+Repowise answered), a map of the repo lit by Claude's turn with its story
+underneath, Ask, and a session recap. Lens never blocks or rewrites Claude's
+tool calls, makes no model calls of its own, and sends Claude nothing unless you
+press a button. Ask questions that do not start with "why" go to `get_answer`,
+which may use the model your repo configures. See
+[the footprint](../../docs/agent/LENS.md#footprint) for the full list.
+
+It needs Claude Code 2.1.287 or later and an indexed repo. The map and the
+savings row also need `repowise serve --no-ui`. Six `userConfig` toggles
+control it: `lens_margin`, `lens_squeeze`, `lens_review` and `lens_flow` (on by
+default), and `lens_pane_autoopen` and `lens_map_health` (off). On an older Claude Code, or where mods are switched
+off, the rest of the plugin works as before.
+
+Guide: [docs/agent/LENS.md](../../docs/agent/LENS.md)
+
## Requirements
- Python 3.11+
diff --git a/plugins/claude-code/hooks/lens/lens.js b/plugins/claude-code/hooks/lens/lens.js
index f0d2f2b30..59b83367c 100644
--- a/plugins/claude-code/hooks/lens/lens.js
+++ b/plugins/claude-code/hooks/lens/lens.js
@@ -214,8 +214,8 @@ function isWindowsPath(p) {
return /^[A-Za-z]:[\\/]/.test(p) || p.startsWith("\\\\");
}
__name(isWindowsPath, "isWindowsPath");
-function join(dir, rel) {
- return `${dir.replace(/[\\/]+$/, "")}/${rel}`;
+function join(dir, rel2) {
+ return `${dir.replace(/[\\/]+$/, "")}/${rel2}`;
}
__name(join, "join");
function parentDir(p) {
@@ -409,6 +409,12 @@ function callTool(host, tool, args, opts = {}) {
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],
@@ -420,7 +426,9 @@ async function fetchFileContext(host, path) {
const contributors = target.ownership?.contributor_count;
return {
callerFiles: typeof callers === "number" ? callers : null,
- contributors: typeof contributors === "number" ? contributors : null
+ contributors: typeof contributors === "number" ? contributors : null,
+ hotspot: typeof target.hotspot === "boolean" ? target.hotspot : null,
+ recentOwner: recentOwner(target.ownership)
};
}
__name(fetchFileContext, "fetchFileContext");
@@ -478,1144 +486,2150 @@ function fit(text2, columns) {
return `${text2.slice(0, columns - 1).trimEnd()}…`;
}
__name(fit, "fit");
-
-// ../api-client/src/blast-radius.ts
-async function analyzeBlastRadius(repoId, body) {
- return apiPost(
- `/api/repos/${repoId}/blast-radius`,
- body
- );
-}
-__name(analyzeBlastRadius, "analyzeBlastRadius");
-
-// ../api-client/src/code-health.ts
-async function getHealthMap(repoId, opts = {}) {
- return apiGet(`/api/repos/${repoId}/health/map`, {
- cap: opts.cap,
- active: opts.active?.length ? opts.active.join(",") : void 0,
- scope: opts.scope,
- counts: opts.counts
- });
+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(getHealthMap, "getHealthMap");
+__name(cellSafe, "cellSafe");
-// src/model/events.ts
-function fromTurnComplete(e) {
- return e.agentId === void 0 ? { type: "turnCompleted" } : null;
+// ../../node_modules/d3-hierarchy/src/hierarchy/count.js
+function count(node) {
+ var sum = 0, children = node.children, i = children && children.length;
+ if (!i) sum = 1;
+ else while (--i >= 0) sum += children[i].value;
+ node.value = sum;
}
-__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(count, "count");
+function count_default() {
+ return this.eachAfter(count);
}
-__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 .*)?\.$/;
-var FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, last (.+?)(?: \(bug magnet\))?(?:; mostly in (.+?))?\.$/;
-function stripConfirmed(line2) {
- return line2.replace(/ \(confirmed across \d+ sessions\)\.$/, ".");
+__name(count_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/each.js
+function each_default(callback, that) {
+ let index = -1;
+ for (const node of this) {
+ callback.call(that, node, ++index, this);
+ }
+ return this;
}
-__name(stripConfirmed, "stripConfirmed");
-function notesFromAugment(additionalContext) {
- if (!Array.isArray(additionalContext)) return [];
- const notes = [];
- const lines = additionalContext.filter((c) => typeof c === "string").flatMap((c) => c.split(/\r?\n/));
- for (const raw of lines) {
- const line2 = stripConfirmed(raw.trim());
- const standing = STANDING.exec(line2);
- const decision = standing ?? MINED.exec(line2);
- const fixes = FIXES.exec(line2);
- if (decision !== null && !notes.some((n) => n.kind === "decision")) {
- notes.push({ kind: "decision", reviewed: standing !== null, title: decision[1] });
- } else if (fixes !== null && !notes.some((n) => n.kind === "fixes")) {
- notes.push({ kind: "fixes", count: Number(fixes[1]), age: fixes[2], symbol: fixes[3] ?? null });
+__name(each_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
+function eachBefore_default(callback, that) {
+ var node = this, nodes = [node], children, i, index = -1;
+ while (node = nodes.pop()) {
+ callback.call(that, node, ++index, this);
+ if (children = node.children) {
+ for (i = children.length - 1; i >= 0; --i) {
+ nodes.push(children[i]);
+ }
}
}
- return notes;
-}
-__name(notesFromAugment, "notesFromAugment");
-function savingsTotals(s) {
- return {
- tokens: s.saved_input_tokens,
- inferredTokens: Math.min(s.inferred_saved_input_tokens, s.saved_input_tokens),
- usd: s.priced_input_savings_usd
- };
+ return this;
}
-__name(savingsTotals, "savingsTotals");
-function savingsSince(now, base) {
- const tokens = now.tokens - base.tokens;
- const inferredTokens = now.inferredTokens - base.inferredTokens;
- const usd = now.usd - base.usd;
- if (tokens < 0 || inferredTokens < 0 || usd < 0) return null;
- return { tokens, inferredTokens: Math.min(inferredTokens, tokens), usd };
+__name(eachBefore_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
+function eachAfter_default(callback, that) {
+ var node = this, nodes = [node], next = [], children, i, n, index = -1;
+ while (node = nodes.pop()) {
+ next.push(node);
+ if (children = node.children) {
+ for (i = 0, n = children.length; i < n; ++i) {
+ nodes.push(children[i]);
+ }
+ }
+ }
+ while (node = next.pop()) {
+ callback.call(that, node, ++index, this);
+ }
+ return this;
}
-__name(savingsSince, "savingsSince");
-var OBSERVED_TOOLS = /* @__PURE__ */ new Set(["Read", "Edit", "Write", "Grep", "Glob"]);
-var OWN_CALL_PREFIX = "toolu_plugin_";
-function absolutePath(raw, ctx) {
- const absolute = ctx.isWindows ? /^[A-Za-z]:[\\/]|^\\\\/.test(raw) : raw.startsWith("/");
- const joined = absolute ? raw : `${ctx.cwd.replace(/[\\/]+$/, "")}/${raw.replace(/^\.[\\/]/, "")}`;
- return ctx.isWindows ? joined.replace(/\\/g, "/") : joined;
+__name(eachAfter_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/find.js
+function find_default(callback, that) {
+ let index = -1;
+ for (const node of this) {
+ if (callback.call(that, node, ++index, this)) {
+ return node;
+ }
+ }
}
-__name(absolutePath, "absolutePath");
-function absoluteKey(raw, ctx) {
- return normalizeRepoPath(absolutePath(raw, ctx), ctx.isWindows);
+__name(find_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/sum.js
+function sum_default(value) {
+ return this.eachAfter(function(node) {
+ var sum = +value(node.data) || 0, children = node.children, i = children && children.length;
+ while (--i >= 0) sum += children[i].value;
+ node.value = sum;
+ });
}
-__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(sum_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/sort.js
+function sort_default(compare) {
+ return this.eachBefore(function(node) {
+ if (node.children) {
+ node.children.sort(compare);
+ }
+ });
}
-__name(relativeTo, "relativeTo");
-function filenamesOf(out) {
- const names = typeof out.result === "object" ? out.result.filenames : void 0;
- return Array.isArray(names) ? names.filter((v) => typeof v === "string") : [];
+__name(sort_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/path.js
+function path_default(end) {
+ var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
+ while (start !== ancestor) {
+ start = start.parent;
+ nodes.push(start);
+ }
+ var k = nodes.length;
+ while (end !== ancestor) {
+ nodes.splice(k, 0, end);
+ end = end.parent;
+ }
+ return nodes;
}
-__name(filenamesOf, "filenamesOf");
-function isContentGrep(tool, out) {
- return tool === "Grep" && typeof out.result === "object" && out.result.mode === "content";
+__name(path_default, "default");
+function leastCommonAncestor(a, b) {
+ if (a === b) return a;
+ var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
+ a = aNodes.pop();
+ b = bNodes.pop();
+ while (a === b) {
+ c = a;
+ a = aNodes.pop();
+ b = bNodes.pop();
+ }
+ return c;
}
-__name(isContentGrep, "isContentGrep");
-function searchAction(out, ctx) {
- return { type: "search", paths: filenamesOf(out).map((f) => absoluteKey(f, ctx)) };
+__name(leastCommonAncestor, "leastCommonAncestor");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.js
+function ancestors_default() {
+ var node = this, nodes = [node];
+ while (node = node.parent) {
+ nodes.push(node);
+ }
+ return nodes;
}
-__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(ancestors_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.js
+function descendants_default() {
+ return Array.from(this);
}
-__name(fileAction, "fileAction");
-function fromToolCall(e, outcome, ctx) {
- if (!OBSERVED_TOOLS.has(e.tool) || e.tool_use_id?.startsWith(OWN_CALL_PREFIX)) 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(descendants_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.js
+function leaves_default() {
+ var leaves = [];
+ this.eachBefore(function(node) {
+ if (!node.children) {
+ leaves.push(node);
+ }
+ });
+ return leaves;
}
-__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;
- const base = cwd2 ?? repoRoot;
- if (base === null) return raw;
- const isWindows = /^[A-Za-z]:[\/]|^[\/]{2}/.test(base);
- const abs = absolutePath(raw, { cwd: base, isWindows });
- return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;
+__name(leaves_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/hierarchy/links.js
+function links_default() {
+ var root = this, links = [];
+ root.each(function(node) {
+ if (node !== root) {
+ links.push({ source: node.parent, target: node });
+ }
+ });
+ return links;
}
-__name(touchedPath, "touchedPath");
+__name(links_default, "default");
-// src/model/trail.ts
-var MAX_READS = 200;
-var initialTrail = {
- reads: [],
- readsCapped: false,
- hits: [],
- searches: 0,
- edit: null,
- edits: 0,
- callers: null
-};
-function withRead(state2, path) {
- if (state2.reads.includes(path)) return state2;
- const reads = [...state2.reads, 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":
- return withRead(state2, action.path);
- case "search":
- return { ...state2, hits: action.paths, searches: state2.searches + 1 };
- case "edit":
- return {
- ...withRead(state2, action.path),
- edit: action.path,
- edits: state2.edits + 1,
- callers: { status: "loading" }
- };
- case "callers":
- return action.edits === state2.edits ? { ...state2, callers: action.callers } : state2;
- }
+// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.js
+function* iterator_default() {
+ var node = this, current, next = [node], children, i, n;
+ do {
+ current = next.reverse(), next = [];
+ while (node = current.pop()) {
+ yield node;
+ if (children = node.children) {
+ for (i = 0, n = children.length; i < n; ++i) {
+ next.push(children[i]);
+ }
+ }
+ }
+ } while (next.length);
}
-__name(reduceTrail, "reduceTrail");
+__name(iterator_default, "default");
-// src/views/copy.ts
-var HINTS = {
- "no-server": "Lens map needs the local server: repowise serve --no-ui",
- auth: "local server needs an API key; Lens does not read keys",
- unlisted: "Lens map needs a local server for this repo: repowise serve --no-ui",
- "no-index": "index this repo for Lens: repowise init --no-prose --yes",
- "no-cli": "Lens needs the Repowise CLI: pip install repowise"
-};
-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`);
- const failures = [s.failed > 0 ? `${s.failed.toLocaleString("en-US")} failed` : "", s.errors > 0 ? countOf(s.errors, "error", "errors") : ""];
- if (s.failed + s.errors > 0) parts.push(failures.filter((f) => f !== "").join(", "));
- const more = s.refs.length > 1 ? ` (+${s.refs.length - 1} more)` : "";
- 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}`;
+// ../../node_modules/d3-hierarchy/src/hierarchy/index.js
+function hierarchy(data, children) {
+ if (data instanceof Map) {
+ data = [void 0, data];
+ if (children === void 0) children = mapChildren;
+ } else if (children === void 0) {
+ children = objectChildren;
}
- 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)}` : "";
- const head = `${countOf(d.tokens, "token", "tokens")}${inferred}${usd} saved`;
- 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`;
-var RUN_TESTS = "Run tests";
-var WHY = "Why";
-var DETAILS = "Details";
-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`}`;
+ var root = new Node(data), node, nodes = [root], child, childs, i, n;
+ while (node = nodes.pop()) {
+ if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
+ node.children = childs;
+ for (i = n - 1; i >= 0; --i) {
+ nodes.push(child = childs[i] = new Node(childs[i]));
+ child.parent = node;
+ child.depth = node.depth + 1;
+ }
+ }
+ }
+ return root.eachBefore(computeHeight);
}
-__name(noNewFindings, "noNewFindings");
-function healthImproved(resolved) {
- return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;
+__name(hierarchy, "hierarchy");
+function node_copy() {
+ return hierarchy(this).eachBefore(copyData);
}
-__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(node_copy, "node_copy");
+function objectChildren(d) {
+ return d.children;
}
-__name(notCompared, "notCompared");
-function improvedShort(resolved) {
- return `improved, ${resolved.toLocaleString("en-US")} resolved`;
+__name(objectChildren, "objectChildren");
+function mapChildren(d) {
+ return Array.isArray(d) ? d[1] : null;
}
-__name(improvedShort, "improvedShort");
-function newFindings(total, required2) {
- return `${countOf(total, "new finding", "new findings")}, ${required2 ? "review required" : "low severity"}`;
+__name(mapChildren, "mapChildren");
+function copyData(node) {
+ if (node.data.value !== void 0) node.value = node.data.value;
+ node.data = node.data.data;
}
-__name(newFindings, "newFindings");
-function resolvedToo(resolved) {
- return `${countOf(resolved, "finding", "findings")} resolved`;
+__name(copyData, "copyData");
+function computeHeight(node) {
+ var height = 0;
+ do
+ node.height = height;
+ while ((node = node.parent) && node.height < ++height);
}
-__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(computeHeight, "computeHeight");
+function Node(data) {
+ this.data = data;
+ this.depth = this.height = 0;
+ this.parent = null;
}
-__name(findingLine, "findingLine");
-function moreFindings(more) {
- return `and ${more.toLocaleString("en-US")} more (Details)`;
+__name(Node, "Node");
+Node.prototype = hierarchy.prototype = {
+ constructor: Node,
+ count: count_default,
+ each: each_default,
+ eachAfter: eachAfter_default,
+ eachBefore: eachBefore_default,
+ find: find_default,
+ sum: sum_default,
+ sort: sort_default,
+ path: path_default,
+ ancestors: ancestors_default,
+ descendants: descendants_default,
+ leaves: leaves_default,
+ links: links_default,
+ copy: node_copy,
+ [Symbol.iterator]: iterator_default
+};
+
+// ../../node_modules/d3-hierarchy/src/accessors.js
+function required(f) {
+ if (typeof f !== "function") throw new Error();
+ return f;
}
-__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(required, "required");
+
+// ../../node_modules/d3-hierarchy/src/constant.js
+function constantZero() {
+ return 0;
}
-__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(constantZero, "constantZero");
+function constant_default(x) {
+ return function() {
+ return x;
+ };
}
-__name(diffShape, "diffShape");
-function testsBasis(measured) {
- return measured ? "measured by stored coverage" : "inferred from the dependency graph, not measured";
+__name(constant_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/treemap/round.js
+function round_default(node) {
+ node.x0 = Math.round(node.x0);
+ node.y0 = Math.round(node.y0);
+ node.x1 = Math.round(node.x1);
+ node.y1 = Math.round(node.y1);
}
-__name(testsBasis, "testsBasis");
-function testsLine(t) {
- const count2 = 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: ${count2}, ${testsBasis(t.measured)}${shown}: ${t.tests.join(", ")}`;
+__name(round_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/treemap/dice.js
+function dice_default(parent, x0, y0, x1, y1) {
+ var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;
+ while (++i < n) {
+ node = nodes[i], node.y0 = y0, node.y1 = y1;
+ node.x0 = x0, node.x1 = x0 += node.value * k;
+ }
}
-__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(dice_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/treemap/slice.js
+function slice_default(parent, x0, y0, x1, y1) {
+ var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;
+ while (++i < n) {
+ node = nodes[i], node.x0 = x0, node.x1 = x1;
+ node.y0 = y0, node.y1 = y0 += node.value * k;
+ }
}
-__name(overlapLine, "overlapLine");
-function overlapShort(branches) {
- return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;
+__name(slice_default, "default");
+
+// ../../node_modules/d3-hierarchy/src/treemap/squarify.js
+var phi = (1 + Math.sqrt(5)) / 2;
+function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
+ var rows = [], nodes = parent.children, row2, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
+ while (i0 < n) {
+ dx = x1 - x0, dy = y1 - y0;
+ do
+ sumValue = nodes[i1++].value;
+ while (!sumValue && i1 < n);
+ minValue = maxValue = sumValue;
+ alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
+ beta = sumValue * sumValue * alpha;
+ minRatio = Math.max(maxValue / beta, beta / minValue);
+ for (; i1 < n; ++i1) {
+ sumValue += nodeValue = nodes[i1].value;
+ if (nodeValue < minValue) minValue = nodeValue;
+ if (nodeValue > maxValue) maxValue = nodeValue;
+ beta = sumValue * sumValue * alpha;
+ newRatio = Math.max(maxValue / beta, beta / minValue);
+ if (newRatio > minRatio) {
+ sumValue -= nodeValue;
+ break;
+ }
+ minRatio = newRatio;
+ }
+ rows.push(row2 = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
+ if (row2.dice) dice_default(row2, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
+ else slice_default(row2, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
+ value -= sumValue, i0 = i1;
+ }
+ return rows;
+}
+__name(squarifyRatio, "squarifyRatio");
+var squarify_default = (/* @__PURE__ */ __name((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);
+
+// ../../node_modules/d3-hierarchy/src/treemap/index.js
+function treemap_default() {
+ var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
+ function treemap(root) {
+ root.x0 = root.y0 = 0;
+ root.x1 = dx;
+ root.y1 = dy;
+ root.eachBefore(positionNode);
+ paddingStack = [0];
+ 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;
+ if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
+ node.x0 = x0;
+ node.y0 = y0;
+ node.x1 = x1;
+ node.y1 = y1;
+ if (node.children) {
+ p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
+ x0 += paddingLeft(node) - p;
+ y0 += paddingTop(node) - p;
+ x1 -= paddingRight(node) - p;
+ y1 -= paddingBottom(node) - p;
+ if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
+ if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
+ tile(node, x0, y0, x1, y1);
+ }
+ }
+ __name(positionNode, "positionNode");
+ treemap.round = function(x) {
+ return arguments.length ? (round = !!x, treemap) : round;
+ };
+ treemap.size = function(x) {
+ return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
+ };
+ treemap.tile = function(x) {
+ return arguments.length ? (tile = required(x), treemap) : tile;
+ };
+ treemap.padding = function(x) {
+ return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
+ };
+ treemap.paddingInner = function(x) {
+ return arguments.length ? (paddingInner = typeof x === "function" ? x : constant_default(+x), treemap) : paddingInner;
+ };
+ treemap.paddingOuter = function(x) {
+ return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
+ };
+ treemap.paddingTop = function(x) {
+ return arguments.length ? (paddingTop = typeof x === "function" ? x : constant_default(+x), treemap) : paddingTop;
+ };
+ treemap.paddingRight = function(x) {
+ return arguments.length ? (paddingRight = typeof x === "function" ? x : constant_default(+x), treemap) : paddingRight;
+ };
+ treemap.paddingBottom = function(x) {
+ return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant_default(+x), treemap) : paddingBottom;
+ };
+ treemap.paddingLeft = function(x) {
+ return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant_default(+x), treemap) : paddingLeft;
+ };
+ return treemap;
+}
+__name(treemap_default, "default");
+
+// ../types/src/health.ts
+var EXCELLENT_MIN = 8.5;
+var GOOD_MIN = 7;
+var FAIR_MIN = 5.5;
+var NEEDS_WORK_MIN = 4;
+var HEALTH_BAND_ORDER = [
+ "at_risk",
+ "needs_work",
+ "fair",
+ "good",
+ "excellent"
+];
+var HEALTH_BAND_LABEL = {
+ excellent: "Excellent",
+ good: "Good",
+ fair: "Fair",
+ needs_work: "Needs work",
+ at_risk: "At risk"
+};
+function bandForScore(score) {
+ if (score >= EXCELLENT_MIN) return "excellent";
+ if (score >= GOOD_MIN) return "good";
+ if (score >= FAIR_MIN) return "fair";
+ if (score >= NEEDS_WORK_MIN) return "needs_work";
+ return "at_risk";
+}
+__name(bandForScore, "bandForScore");
+
+// ../ui/src/brand.ts
+var BRAND = {
+ /** Accent orange — the brand fill (CTAs, owl eyes, highlights). */
+ accent: "#f59520",
+ /** Accent text on light surfaces (darkened for 4.5:1 contrast). */
+ accentTextLight: "#a16215",
+ /** Brand plum — logo strokes on light surfaces, secondary accent. */
+ plum: "#473659",
+ /** Plum near-black — primary ink on warm paper. */
+ ink: "#241b2c",
+ /** Warm paper — the light-mode page background. */
+ paper: "#fbf6f1",
+ /** Cream — the logo stroke color on dark surfaces. */
+ cream: "#fce9dd"
+};
+var LIGHT = {
+ bgRoot: "#fbf6f1",
+ bgSurface: "#ffffff",
+ bgElevated: "#fbf4ee",
+ bgInset: "#f4eae1",
+ textPrimary: "#241b2c",
+ textSecondary: "#5e5360",
+ textTertiary: "#8c7f88",
+ accentPrimary: "#a16215",
+ accentFill: "#f59520",
+ accentSecondary: "#58436c",
+ success: "#1d8155",
+ warning: "#9a6614",
+ error: "#b23a2e"
+};
+var DARK = {
+ bgRoot: "#0e0e0f",
+ bgSurface: "#141416",
+ bgElevated: "#191a1c",
+ bgInset: "#0a0a0b",
+ textPrimary: "#f2f2f3",
+ textSecondary: "#b4b4b9",
+ textTertiary: "#7c7c82",
+ accentPrimary: "#f59520",
+ accentFill: "#f59520",
+ accentSecondary: "#a98fc4",
+ success: "#34d399",
+ warning: "#f2a03d",
+ error: "#e06a5a"
+};
+var DARK_CANVAS = {
+ nodeAtRisk: "#b0544b",
+ nodeNeedsWork: "#bd7c42",
+ nodeFair: "#a89453",
+ nodeGood: "#42906f",
+ nodeExcellent: "#5cb389",
+ nodeNeutral: "#333336",
+ caution: "#d9b04a"
+};
+var DARK_CANVAS_BAND = {
+ excellent: DARK_CANVAS.nodeExcellent,
+ good: DARK_CANVAS.nodeGood,
+ fair: DARK_CANVAS.nodeFair,
+ needs_work: DARK_CANVAS.nodeNeedsWork,
+ at_risk: DARK_CANVAS.nodeAtRisk
+};
+
+// src/views/map.ts
+var UPPER_HALF = 9600;
+var LOWER_HALF = 9604;
+var SPACE = 32;
+var hex = /* @__PURE__ */ __name((s) => parseInt(s.slice(1), 16), "hex");
+var GROUND = hex(DARK.bgRoot);
+var TERMINAL_DEFAULT = 16777216;
+var LABEL_FG = hex(DARK.textSecondary);
+var NEUTRAL = hex(DARK_CANVAS.nodeNeutral);
+var BLACK = 0;
+var MAP_PALETTES = {
+ dark: {
+ tileA: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.12),
+ tileB: mix(hex(DARK.bgElevated), hex(DARK.textTertiary), 0.22),
+ folder: hex(DARK.textTertiary),
+ hit: mix(hex(DARK.bgElevated), hex(DARK.textSecondary), 0.32),
+ read: hex(DARK.textSecondary),
+ named: mix(hex(DARK.accentSecondary), hex(DARK.bgRoot), 0.45),
+ importer: hex(DARK.accentSecondary),
+ edit: hex(BRAND.accent)
+ },
+ light: {
+ tileA: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.08),
+ tileB: mix(hex(LIGHT.bgInset), hex(LIGHT.textTertiary), 0.16),
+ folder: hex(LIGHT.textTertiary),
+ hit: mix(hex(LIGHT.bgInset), hex(LIGHT.textSecondary), 0.3),
+ read: hex(LIGHT.textSecondary),
+ named: mix(hex(LIGHT.accentSecondary), hex(LIGHT.bgRoot), 0.55),
+ importer: hex(LIGHT.accentSecondary),
+ edit: hex(BRAND.accentTextLight)
+ }
+};
+var DEFAULT_STYLE = { theme: "dark", health: false };
+var DENSE_SHARE = 0.6;
+var SPLIT_SHARE = 0.25;
+var MAX_SPLITS = 8;
+var GUTTER_MIN = 6;
+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 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");
+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) {
+ const key = keyOf(f.file_path, split);
+ weight.set(key, (weight.get(key) ?? 0) + f.nloc);
+ }
+ const heavy = [...weight].filter(([key, w]) => key !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));
+ for (const [key] of heavy) {
+ const deeper = /* @__PURE__ */ new Set([...split, key]);
+ const parts = new Set(files.filter((f) => keyOf(f.file_path, split) === key).map((f) => keyOf(f.file_path, deeper)));
+ if (parts.size > 1) return key;
+ }
+ 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;
+ for (let i = 0; i < MAX_SPLITS; i++) {
+ const key = nextSplit(files, split, limit);
+ if (key === null) break;
+ split.add(key);
+ }
+ return files.map((f) => keyOf(f.file_path, split));
+}
+__name(groupKeys, "groupKeys");
+var folderDatum = /* @__PURE__ */ __name((name) => ({ name, children: [], kids: /* @__PURE__ */ new Map() }), "folderDatum");
+function insertFile(group, key, file) {
+ const rel2 = key === "" ? file.file_path : file.file_path.slice(key.length + 1);
+ let node = group;
+ for (const dir of rel2.split("/").slice(0, -1)) {
+ let next = node.kids?.get(dir);
+ if (next === void 0) {
+ next = folderDatum(dir);
+ node.kids?.set(dir, next);
+ node.children?.push(next);
+ }
+ node = next;
+ }
+ 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();
+ files.forEach((file, i) => {
+ const key = keys[i] ?? "";
+ const group = groups.get(key) ?? folderDatum(key);
+ groups.set(key, group);
+ insertFile(group, key, file);
+ });
+ const data = { name: "", children: [...groups.values()] };
+ const root = hierarchy(data).sum((d) => d.file?.nloc ?? 0).sort((a, b) => (b.value ?? 0) - (a.value ?? 0) || byName(a.data.name, b.data.name));
+ 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");
+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(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}`));
+__name(groupInterior, "groupInterior");
+function placeFile(leaf, group, inner) {
+ const file = leaf.data.file;
+ const rect = rectOf(leaf);
+ const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);
+ const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);
+ return {
+ path: file.file_path,
+ score: file.score,
+ nloc: file.nloc,
+ group,
+ rect,
+ px0: Math.max(x0, inner.x0),
+ py0: Math.max(y0, inner.y0),
+ px1: Math.min(x1, inner.x1),
+ 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 folderTiles(group, inner) {
+ const out = [];
+ for (const node of group.descendants()) {
+ if (node === group || node.children === void 0) continue;
+ const tone = (node.parent?.children ?? []).indexOf(node) % 2;
+ const [x0, x1] = pixelSpan(node.x0, node.x1);
+ const [y0, y1] = pixelSpan(node.y0, node.y1);
+ out.push({ x0: Math.max(x0, inner.x0), y0: Math.max(y0, inner.y0), x1: Math.min(x1, inner.x1), y1: Math.min(y1, inner.y1), tone });
+ }
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(folderTiles, "folderTiles");
+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;
+ const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;
+ for (let y = f.py0; y < f.py1; y++) {
+ base.fill(y === edgeY ? edge : fill, y * width2 + f.px0, y * width2 + f.px1);
+ if (edgeX >= 0) base[y * width2 + edgeX] = edge;
+ }
}
-__name(runTestsPrompt, "runTestsPrompt");
-var MAP_COPY = {
- title: "Lens",
- looking: "Lens map: looking for the local server",
- loading: "Lens map: loading the health map",
- failed: "Lens map could not load the health map; it tries again on /lens",
- desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",
- tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",
- noScore: "Not scored",
- read: "Claude read",
- edited: "edited",
- importer: "imports the edited file",
- match: "search match",
- waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens"
-};
-function mapAlt(drawn) {
- return `Code health map: ${countOf(drawn, "file", "files")} drawn, colored by health band, with the files Claude read and edited marked`;
+__name(paintFile, "paintFile");
+function labelText(key, width2) {
+ const parts = key.split("/");
+ const rungs = [key, 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(mapAlt, "mapAlt");
-function notPlacedLine(reason) {
- return `Lens map needs a wider terminal: ${reason}`;
+__name(labelText, "labelText");
+var LABEL_MIN_COLS = 12;
+var LABEL_MIN_ROWS = 3;
+var MAX_LABELS = 8;
+function labelFor(g, columns, rows) {
+ const col = Math.ceil(g.rect.x);
+ const row2 = Math.ceil(g.rect.y / 2);
+ const width2 = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;
+ const height = Math.floor((g.rect.y + g.rect.h) / 2) - row2;
+ const small = height < LABEL_MIN_ROWS || width2 < LABEL_MIN_COLS;
+ if (g.key === "" || small || row2 >= rows) return null;
+ const text2 = labelText(g.key, width2);
+ return text2 === null ? null : { row: row2, col, text: text2 };
}
-__name(notPlacedLine, "notPlacedLine");
-var SCOPE_REST = "rest empty or too small";
-function indexedPart(age) {
- return `indexed ${age}`;
+__name(labelFor, "labelFor");
+function labelsFor(groups, columns, rows) {
+ return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows)).filter((l) => l !== null).slice(0, MAX_LABELS);
}
-__name(indexedPart, "indexedPart");
-function scopeParts(s) {
- const parts = s.drawn === s.repositoryTotal ? [`${countOf(s.drawn, "file", "files")}, all drawn`] : [`${formatNumber(s.drawn)} of ${countOf(s.repositoryTotal, "file", "files")} drawn at this size`, SCOPE_REST];
- if (s.indexed !== null) parts.push(indexedPart(s.indexed));
- if (s.beyondCap > 0) parts.push(`${formatNumber(s.beyondCap)} beyond the ${formatNumber(s.cap)}-file cap`);
- return parts;
+__name(labelsFor, "labelsFor");
+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");
+ 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 layoutMap(feed, canvas) {
+ const { columns, rows, caseInsensitive } = canvas;
+ const style = canvas.style ?? DEFAULT_STYLE;
+ const width2 = columns;
+ const height = rows * 2;
+ const root = treemapOf(
+ feed.filter((f) => f.nloc > 0),
+ width2,
+ height
+ );
+ const groups = [];
+ const files = [];
+ const folders = [];
+ for (const node of root.children ?? []) {
+ const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;
+ const inner = groupInterior(rectOf(node), width2, height);
+ for (const leaf of node.leaves()) files.push(placeFile(leaf, group, inner));
+ folders.push(...folderTiles(node, inner));
+ }
+ const drawn = [];
+ const index = /* @__PURE__ */ new Map();
+ const lower = /* @__PURE__ */ new Map();
+ files.forEach((f, i) => {
+ index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);
+ lower.set(f.path.toLowerCase(), i);
+ if (f.px1 > f.px0 && f.py1 > f.py0) drawn.push(i);
+ });
+ const dense = drawn.length < files.length * DENSE_SHARE;
+ const base = paintBase({ width: width2, height, groups, folders, files, drawn }, style, dense);
+ return { columns, rows, width: width2, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base, style, dense, lower, folders };
}
-__name(scopeParts, "scopeParts");
-function readsLine(reads, matched, columns = Number.POSITIVE_INFINITY) {
- const count2 = reads.capped ? `${formatNumber(reads.count)}+` : formatNumber(reads.count);
- const full = [];
- const short = [];
- if (reads.count > 0) {
- full.push(reads.capped ? `${count2} files read` : countOf(reads.count, "file read", "files read"));
- short.push(`${count2} read`);
- }
- if (reads.notDrawn > 0) {
- full.push(`${formatNumber(reads.notDrawn)} not drawn`);
- short.push(`${formatNumber(reads.notDrawn)} not drawn`);
- }
- if (matched !== null) {
- full.push(`last search matched ${countOf(matched, "file", "files")}`);
- short.push(`search matched ${formatNumber(matched)}`);
- }
- if (full.length === 0) return null;
- const line2 = full.join(" · ");
- return line2.length <= columns ? line2 : short.join(" · ");
-}
-__name(readsLine, "readsLine");
-function callersLine(name, callers, notDrawn, columns = Number.POSITIVE_INFINITY) {
- if (callers === null || callers.status === "loading") return `edited ${name} · finding the files that import it`;
- if (callers.status === "failed") return `edited ${name} · import graph unavailable`;
- const missing = notDrawn === 0 ? "" : ` · ${formatNumber(notDrawn)} not drawn`;
- const full = `edited ${name} · ${countOf(callers.paths.length, "file imports", "files import")} it (from imports, not calls)${missing}`;
- if (full.length <= columns) return full;
- const rest = ` · ${formatNumber(callers.paths.length)} import it${missing}`;
- return `edited ${fit(name, columns - "edited ".length - rest.length)}${rest}`;
-}
-__name(callersLine, "callersLine");
-var PANE_COPY = {
- command: "Open Lens: the health map, ask the index, and the session recap",
- argumentHint: "[map | ask <question> | recap]",
- tabs: { map: "Map", ask: "Ask", recap: "Recap" },
- askLabel: "ask ",
- askPlaceholder: "why ...? asks the decision records; anything else asks the index",
- askSubmit: "ask",
- askIdle: "Ask about this repo. Answers cite the evidence they used.",
- askBusy: "still answering the last question; ask again when it lands",
- noEvidence: "no evidence cited",
- fromIndex: "Built from the index",
- fromModel: "Written by this repo's configured model, from the index"
-};
-var ASK_CHARS = 4e3;
-function askingLine(tool) {
- return tool === "get_why" ? "asking the decision records..." : "asking the index...";
+__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(askingLine, "askingLine");
-function askFailedLine(message) {
- return `Could not answer: ${message}`;
+__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++) {
+ if (marked[2 * label.row * width2 + c] || marked[(2 * label.row + 1) * width2 + c]) return true;
+ }
+ return false;
}
-__name(askFailedLine, "askFailedLine");
-function askCut(chars) {
- return `reply cut at ${formatNumber(chars)} characters`;
+__name(labelCovered, "labelCovered");
+var cellGround = /* @__PURE__ */ __name((pixel) => pixel === void 0 || pixel === GROUND ? TERMINAL_DEFAULT : pixel, "cellGround");
+function writeText(words, layout, label, colors) {
+ for (let k = 0; k < label.text.length && label.col + k < layout.columns; k++) {
+ const col = label.col + k;
+ words.set([label.text.charCodeAt(k), ...colors(col)], (label.row * layout.columns + col) * 3);
+ }
}
-__name(askCut, "askCut");
-function moreRows(more) {
- return `and ${formatNumber(more)} more`;
+__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) {
+ if (labelCovered(label, marked, layout.width)) continue;
+ writeText(words, layout, label, (col) => [fg, cellGround(pixels[2 * label.row * layout.width + col])]);
+ }
}
-__name(moreRows, "moreRows");
-var RECAP_COPY = {
- files: "Files",
- fromReview: "from the last change review",
- review: "Change review",
- health: "Code health",
- findings: "Findings",
- tests: "Tests to run",
- overlap: "Branches overlapping",
- saved: "Saved",
- decisions: "Decisions surfaced",
- noReview: "none this session",
- notCompared: "not compared",
- noTests: "none named",
- noOverlap: "none found",
- notReported: "not reported",
- noSavings: "nothing yet since this session started",
- savingsNeedServer: "needs the local server: repowise serve --no-ui",
- noDecisions: "none",
- noModel: "Lens made no model calls.",
- fromIndex: "Every figure here is read from the local index."
+__name(writeFolderLabels, "writeFolderLabels");
+function encodeCells(layout, pixels, marked, names2 = []) {
+ const { columns, rows, width: width2 } = layout;
+ const words = new Uint32Array(columns * rows * 3);
+ for (let i = 0; i < columns * rows; i++) {
+ const r = Math.floor(i / columns);
+ const c = i % columns;
+ words.set(halfCell(pixels[2 * r * width2 + c] ?? GROUND, pixels[(2 * r + 1) * width2 + c] ?? GROUND), i * 3);
+ }
+ writeFolderLabels(words, layout, pixels, marked);
+ 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.ts
+var NO_LIT = { hits: [], reads: [], named: [], importers: [], edits: [], edit: null, current: null };
+var FRAME_MS = 40;
+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");
+function indices(layout, paths, lowered = false) {
+ const out = [];
+ for (const p of paths) {
+ const i = lowered ? layout.lower.get(p) : layout.index.get(keyOf2(layout, p));
+ if (i !== void 0) out.push(i);
+ }
+ return out;
+}
+__name(indices, "indices");
+var one = /* @__PURE__ */ __name((layout, path) => path === null ? null : layout.index.get(keyOf2(layout, path)) ?? null, "one");
+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");
+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);
+ const mid = Math.floor((box2.y0 + box2.y1 - 1) / 4);
+ const tries = ROW_TRIES.flatMap((dr) => [box2.x1 + 1, box2.x0 - text2.length - 1].map((col) => ({ row: mid + dr, col })));
+ const at = tries.find((t) => freeSpan(taken, layout, t, text2.length));
+ if (at === void 0) return null;
+ 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))];
+ const taken = /* @__PURE__ */ new Set();
+ 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) {
+ const o = {
+ hits: indices(layout, lit.hits),
+ reads: indices(layout, lit.reads),
+ // Flow keeps the files a reply named lowercased.
+ named: indices(layout, lit.named, true),
+ importers: indices(layout, lit.importers),
+ edit: one(layout, lit.edit),
+ current: one(layout, lit.current)
+ };
+ return { ...o, names: namesFor(layout, o) };
+}
+__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);
+ for (let y = b.y0; y < b.y1; y++) {
+ p.px.fill(color2, y * width2 + b.x0, y * width2 + b.x1);
+ 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;
+ for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {
+ for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width2 - 1, ox + reach); x++) {
+ const d = Math.hypot(x - ox, y - oy);
+ if (d <= reach && d > reach - 2) p.px[y * width2 + x] = mix(p.px[y * width2 + x], color2, 0.5);
+ }
+ }
+}
+__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");
+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];
+ const reach = rippleReach(layout, overlay, anim);
+ fillAll(p, overlay.hits, hitColor(pal, anim));
+ fillAll(p, overlay.named, pal.named);
+ fillAll(p, reached(layout, overlay, reach), pal.importer);
+ fillAll(p, overlay.reads, pal.read);
+ fillAll(p, [overlay.edit, overlay.current].filter((i) => i !== null), pal.edit);
+ const origin = overlay.edit === null ? void 0 : layout.files[overlay.edit];
+ if (origin !== void 0 && reach < Infinity) paintRing(p, origin, reach, pal.importer);
+ 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.ts
+var Animator = class {
+ static {
+ __name(this, "Animator");
+ }
+ anim = null;
+ timer;
+ blitting = false;
+ stopped = false;
+ io = null;
+ /** The closures of the hook running now; the timer's next frame goes through them. */
+ use(io) {
+ this.io = io;
+ }
+ progress(now) {
+ const a = this.anim;
+ return a === null ? void 0 : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };
+ }
+ /**
+ * Plays `kind` for `duration` ms, replacing whatever played. `redraw` false
+ * when called from a render, which already draws the first step.
+ */
+ play(io, kind, duration, screen, redraw = true) {
+ this.stop();
+ if (this.stopped) return;
+ this.io = io;
+ this.anim = { kind, start: Date.now(), duration };
+ if (redraw) io.redraw();
+ this.timer = setInterval(() => this.tick(screen), FRAME_MS);
+ }
+ stop() {
+ clearInterval(this.timer);
+ this.timer = void 0;
+ this.anim = null;
+ }
+ /** For good: a disposed session plays nothing more. */
+ end() {
+ this.stopped = true;
+ this.stop();
+ }
+ /** A timer's frame: never throws out of the timer; a failure stops the animation. */
+ tick(screen) {
+ try {
+ this.frame(screen);
+ } catch (err) {
+ this.failed(err);
+ }
+ }
+ /** A failed frame: the animation stops and the failure goes to the debug log. */
+ failed(err) {
+ this.stop();
+ this.io?.debug(`animation failed: ${String(err)}`);
+ }
+ frame(screen) {
+ const step = this.progress(Date.now());
+ const frame = step === void 0 ? null : screen(step);
+ const io = this.io;
+ if (step === void 0 || frame === null || io === null) return this.stop();
+ if (this.blitting) return;
+ if (step.t >= 1) this.stop();
+ this.blitting = true;
+ io.blit(frame.key, frame.cells, frame.columns, frame.rows).then((r) => r.deny === void 0 || this.refused(io, r.deny)).catch((err) => this.refused(io, String(err))).finally(() => {
+ this.blitting = false;
+ });
+ }
+ /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */
+ refused(io, why) {
+ io.debug(`blit refused: ${why}`);
+ this.stop();
+ if (!this.stopped) io.redraw();
+ }
};
-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`;
+
+// src/model/replies.ts
+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");
+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, key) => targets.some((t) => key in t) ? targets.filter((t) => t[key] === true).length : null, "flagged");
+function contextFacts(r) {
+ const targets = targetsOf(r);
+ const docs = targets.map((t) => rec(t["docs"]));
+ const symbols = sumOver(docs, (d) => count2(d["symbols"]));
+ const symbolTotal = sumOver(docs, (d) => num(rec(d["symbols_truncated"])["total"]) ?? count2(d["symbols"]));
+ return [
+ ...fact("targets", targets.length),
+ ...fact("docs", docs.filter((d) => str(d["title"]) !== null).length || null),
+ ...fact("symbols", symbols, symbolTotal),
+ ...fact("callers", sumOver(targets, (t) => count2(t["callers"]))),
+ ...fact("callees", sumOver(targets, (t) => count2(t["callees"]))),
+ ...fact("decisions", sumOver(targets, (t) => count2(t["decisions"]))),
+ ...fact("hotspots", flagged(targets, "hotspot") || null)
+ ];
}
-__name(filesTouched, "filesTouched");
-function findingsCounts(resolved, total) {
- return `${formatNumber(resolved)} resolved · ${countOf(total, "new finding", "new findings")}`;
+__name(contextFacts, "contextFacts");
+function riskFacts(r) {
+ const targets = targetsOf(r);
+ return [
+ ...fact("targets", targets.length),
+ ...fact("dependents", sumOver(targets, (t) => num(t["dependents_count"]))),
+ ...fact("coChange", sumOver(targets, (t) => num(t["co_change_partners_total"]) ?? count2(t["co_change_partners"]))),
+ ...fact("contributors", sumOver(targets, (t) => num(t["contributor_count"]))),
+ ...fact("hotspots", flagged(targets, "is_hotspot") || null)
+ ];
}
-__name(findingsCounts, "findingsCounts");
-function testsToRunCount(t) {
- const count2 = countOf(t.total, t.files ? "test file" : "test", t.files ? "test files" : "tests");
- return `${count2}, ${t.measured ? "measured" : "inferred"}`;
+__name(riskFacts, "riskFacts");
+function answerFacts(r) {
+ return [
+ ...fact("citations", count2(r["citations"])),
+ ...fact("bodies", count2(r["symbol_bodies"])),
+ ...fact("rationale", count2(r["code_rationale"]), num(r["code_rationale_total"])),
+ ...fact("guesses", count2(r["best_guesses"]))
+ ];
}
-__name(testsToRunCount, "testsToRunCount");
-function decisionsSurfaced(titles) {
- return `${formatNumber(titles.length)}: ${titles.join("; ")}`;
+__name(answerFacts, "answerFacts");
+function whyFacts(r) {
+ const git2 = rec(r["git_archaeology"]);
+ return [
+ ...fact("decisions", count2(r["decisions"])),
+ ...fact("rationale", count2(r["code_rationale"]), num(r["code_rationale_total"])),
+ ...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"]);
+ return [
+ ...fact("lines", start !== null && end !== null && end >= start ? end - start + 1 : null),
+ ...fact("callers", count2(r["callers"])),
+ ...fact("callees", count2(r["callees"]))
+ ];
}
-__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(symbolFacts, "symbolFacts");
+function listFacts(r) {
+ return Object.entries(r).filter(([key, v]) => Array.isArray(v) && v.length > 0 && !key.startsWith("_")).slice(0, 3).map(([key, v]) => ({ what: key, n: v.length }));
+}
+__name(listFacts, "listFacts");
+var READERS = {
+ get_context: contextFacts,
+ get_risk: riskFacts,
+ get_answer: answerFacts,
+ get_why: whyFacts,
+ search_codebase: searchFacts,
+ get_symbol: symbolFacts
+};
+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"]);
+ const limit = num(budget["limit_chars"]);
+ const completeness = rec(meta["completeness"]);
+ const capped = bool(completeness["capped"]);
+ return {
+ commit: str(meta["indexed_commit"]),
+ ageDays: num(meta["index_age_days"]),
+ indexBehind: bool(meta["index_behind"]),
+ verified: bool(r["verified"]),
+ complete: bool(meta["complete"]) ?? (capped === null ? null : !capped),
+ confidence: str(r["confidence"]),
+ grounding: str(r["grounding"]),
+ retrieval: str(r["retrieval_quality"]),
+ budget: used !== null && limit !== null ? { used, limit } : null,
+ omittedTokens: num(rec(meta["omitted"])["tokens"]),
+ degraded: str(r["degraded"]) ?? str(meta["degraded"]),
+ semantic: bool(meta["semantic_search"])
+ };
}
-__name(recapFooter, "recapFooter");
-var BRIEF_COPY = {
- compacted: "context compacted",
- button: "Brief Claude",
- intro: "The context was compacted. This brief is built from the Repowise index and this session's edits:",
- files: "Files edited:",
- decisions: "Decisions in play:",
- review: "Open review items:"
+__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")
};
-var BRIEF_CHARS = 1200;
-function briefDecision(title, reviewed) {
- return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;
+function walkPaths(v, depth, add) {
+ if (depth > MAX_DEPTH) return;
+ if (Array.isArray(v)) return v.forEach((item) => walkPaths(item, depth + 1, add));
+ for (const [key, value] of Object.entries(rec(v))) {
+ if (key === "_meta") continue;
+ PATH_READERS[key]?.(value, add);
+ walkPaths(value, depth + 1, add);
+ }
}
-__name(briefDecision, "briefDecision");
-function briefTests(t) {
- return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
+__name(walkPaths, "walkPaths");
+function pathsOf(r) {
+ const found = /* @__PURE__ */ new Set();
+ walkPaths(r, 0, (p) => {
+ if (typeof p === "string" && p !== "" && found.size < MAX_PATHS) found.add(p.replace(/\\/g, "/"));
+ });
+ 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"]);
+ return {
+ tool,
+ bytes,
+ parsed: true,
+ inside: insideOf(tool, r),
+ behind: behindOf(r, meta),
+ paths: pathsOf(r),
+ excerpt,
+ error: errorOf(r)
+ };
}
-__name(briefTests, "briefTests");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/count.js
-function count(node) {
- var sum = 0, children = node.children, i = children && children.length;
- if (!i) sum = 1;
- else while (--i >= 0) sum += children[i].value;
- node.value = sum;
+__name(summarizeBody, "summarizeBody");
+function summarizeReply(tool, text2) {
+ const bytes = utf8Bytes(text2);
+ const excerpt = text2.slice(0, EXCERPT_CHARS);
+ const parsed = text2.length <= PARSE_CHARS ? parseObject(text2) : null;
+ if (parsed === null) return unparsed(tool, text2, bytes, excerpt);
+ 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);
+ return isRec(v) ? v : null;
+ } catch {
+ return null;
+ }
}
-__name(count, "count");
-function count_default() {
- return this.eachAfter(count);
+__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(count_default, "default");
+__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");
-// ../../node_modules/d3-hierarchy/src/hierarchy/each.js
-function each_default(callback, that) {
- let index = -1;
- for (const node of this) {
- callback.call(that, node, ++index, this);
+// src/model/flow.ts
+var MAX_TURNS = 6;
+var MAX_ACTIVITIES = 60;
+var PROMPT_CHARS = 160;
+var MAX_NAMED = 2e3;
+var MAX_ARGS = 4;
+var ARG_CHARS = 160;
+var COMMAND_CHARS = 2e3;
+var MAX_HIT_PATHS = 200;
+var REPOWISE_TOOL = /^mcp__(?:repowise|plugin_repowise_repowise|claude_ai_repowise)__(\w+)$/i;
+var OWN_CALL_PREFIX = "toolu_plugin_";
+var initialFlow = {
+ turns: [],
+ earlier: { turns: 0, repowise: 0, reads: 0, edits: 0 },
+ named: {},
+ blast: {},
+ open: null
+};
+var END_OF = { answer: "answer", aborted: "stopped", refusal: "failed", error: "failed" };
+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",
+ MultiEdit: "edit",
+ Write: "edit",
+ NotebookEdit: "edit",
+ Grep: "search",
+ Glob: "search",
+ Bash: "shell"
+};
+var ARG_KEYS = ["targets", "query", "question", "id", "file_path", "notebook_path", "pattern", "path", "command", "url", "description"];
+var PATH_ARGS = /* @__PURE__ */ new Set(["file_path", "notebook_path", "path"]);
+function shortPath(path, root) {
+ const slashed = path.replace(/\\/g, "/");
+ if (root === null) return slashed;
+ const base = root.replace(/\\/g, "/").replace(/\/+$/, "");
+ const inside2 = slashed.toLowerCase().startsWith(`${base.toLowerCase()}/`);
+ return inside2 ? slashed.slice(base.length + 1) : slashed;
+}
+__name(shortPath, "shortPath");
+function argValue(key, v, root) {
+ if (typeof v === "string") return (PATH_ARGS.has(key) ? shortPath(v, root) : v.replace(/\s+/g, " ")).slice(0, ARG_CHARS);
+ 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 key of ARG_KEYS) {
+ const value = argValue(key, e[key], root);
+ if (value !== null && out.length < MAX_ARGS) out.push([key, value]);
}
- return this;
+ return out;
}
-__name(each_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/eachBefore.js
-function eachBefore_default(callback, that) {
- var node = this, nodes = [node], children, i, index = -1;
- while (node = nodes.pop()) {
- callback.call(that, node, ++index, this);
- if (children = node.children) {
- for (i = children.length - 1; i >= 0; --i) {
- nodes.push(children[i]);
- }
- }
+__name(compactArgs, "compactArgs");
+var lineCount = /* @__PURE__ */ __name((s) => typeof s === "string" ? s.split("\n").length : null, "lineCount");
+function editLines(e) {
+ const written = e.tool === "Write" ? lineCount(e["content"]) : null;
+ if (written !== null) return { written };
+ const before = lineCount(e["old_string"]);
+ 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: [],
+ asked: [],
+ command: null,
+ isError: false,
+ bytes: null,
+ reply: null,
+ namedBy: null,
+ lines: null,
+ hits: null,
+ hitPaths: []
+};
+var agentOf = /* @__PURE__ */ __name((e) => typeof e.agentId === "string" ? e.agentId : null, "agentOf");
+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"),
+ read: fileOf,
+ edit: /* @__PURE__ */ __name((e, root) => ({ ...fileOf(e, root), lines: editLines(e) }), "edit"),
+ search: fileOf,
+ shell: /* @__PURE__ */ __name((e) => commandOf(e), "shell"),
+ other: fileOf
+};
+function searchHits(outcome, root) {
+ const result = outcome?.result;
+ if (typeof result !== "object" || result === null) return { hits: null, hitPaths: [] };
+ if (!Array.isArray(result.filenames)) return { hits: typeof result.numFiles === "number" ? result.numFiles : null, hitPaths: [] };
+ 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);
+ const text2 = outcomeText(outcome);
+ const isError = outcome === null || outcome?.isError === true;
+ const summary = rw === null || text2 === null ? null : summarizeReply(rw, text2);
+ const reply = summary === null ? null : { ...summary, paths: summary.paths.map((p) => shortPath(p, 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;
+ for (const p of paths) {
+ const key = pathKey(p);
+ if (out[key] !== void 0 || size >= MAX_NAMED) continue;
+ if (out === named2) out = { ...named2 };
+ out[key] = naming;
+ size++;
}
- return this;
+ return out;
}
-__name(eachBefore_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/eachAfter.js
-function eachAfter_default(callback, that) {
- var node = this, nodes = [node], next = [], children, i, n, index = -1;
- while (node = nodes.pop()) {
- next.push(node);
- if (children = node.children) {
- for (i = 0, n = children.length; i < n; ++i) {
- nodes.push(children[i]);
- }
+__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");
+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 answered = turn.activities.filter(isAnswered);
+ const edits = files.filter((a) => a.kind === "edit");
+ return {
+ repowise: turn.activities.filter((a) => a.kind === "repowise").length,
+ answered: answered.length,
+ answeredMs: answered.reduce((ms, a) => ms + a.endedAt - a.startedAt, 0),
+ reads: keys(files.filter((a) => a.kind === "read")).size,
+ edits: keys(edits).size,
+ opened: keys(files).size,
+ named: keys(files.filter((a) => a.namedBy !== null)).size,
+ 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;
+ const turn = state2.turns[i];
+ const activities = turn.activities.map((a) => a.id === id ? f(a) : a);
+ 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 }));
+ if (next === state2 || reply === null || isError) return next;
+ 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;
+ const at = state2.open === null ? -1 : ids2.indexOf(state2.open);
+ 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": {
+ const closed = closeTurn(state2, action.at, null, "stopped");
+ return withTurn(closed, newTurn(closed, action.turnId, action.prompt, action.at));
}
+ case "turnEnded":
+ return closeTurn(state2, action.at, action.durationMs, action.end);
+ case "toolStarted":
+ return started(state2, action.activity);
+ case "toolEnded":
+ return ended(state2, action);
+ case "blastLanded":
+ return { ...state2, blast: { ...state2.blast, [pathKey(action.path)]: action.facts } };
+ case "toggle":
+ return { ...state2, open: state2.open === action.id ? null : action.id };
+ case "step":
+ return stepped(state2, action.by);
}
- while (node = next.pop()) {
- callback.call(that, node, ++index, this);
- }
- return this;
}
-__name(eachAfter_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/find.js
-function find_default(callback, that) {
- let index = -1;
- for (const node of this) {
- if (callback.call(that, node, ++index, this)) {
- return node;
- }
+__name(reduceFlow, "reduceFlow");
+function visits(state2) {
+ const out = [];
+ let order = 0;
+ const steps = state2.turns.flatMap((t) => t.activities.map((a) => [a, t.seq]));
+ for (const [a, turn] of steps) {
+ const found = visitsOf(a, turn, order + 1);
+ if (found.length > 0) order++;
+ out.push(...found);
}
+ return out;
}
-__name(find_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/sum.js
-function sum_default(value) {
- return this.eachAfter(function(node) {
- var sum = +value(node.data) || 0, children = node.children, i = children && children.length;
- while (--i >= 0) sum += children[i].value;
- node.value = sum;
- });
+__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(sum_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/sort.js
-function sort_default(compare) {
- return this.eachBefore(function(node) {
- if (node.children) {
- node.children.sort(compare);
- }
- });
+__name(visitsOf, "visitsOf");
+function isWorking(state2) {
+ const last = state2.turns.at(-1);
+ return last !== void 0 && last.endedAt === null;
}
-__name(sort_default, "default");
+__name(isWorking, "isWorking");
+function inFlight(state2) {
+ return state2.turns.at(-1)?.activities.find((a) => a.kind === "repowise" && a.endedAt === null) ?? null;
+}
+__name(inFlight, "inFlight");
-// ../../node_modules/d3-hierarchy/src/hierarchy/path.js
-function path_default(end) {
- var start = this, ancestor = leastCommonAncestor(start, end), nodes = [start];
- while (start !== ancestor) {
- start = start.parent;
- nodes.push(start);
+// src/model/turnFacts.ts
+var COCHANGE_SHOWN = 2;
+var GENERIC = /* @__PURE__ */ new Set(["test", "tests", "spec", "specs", "__init__"]);
+var TEST_RUNNER = /\b(?:pytest|py\.test|manage\.py test|runtests|npm (?:run )?test|vitest|jest|go test|cargo test)\b/;
+function testsOf(file) {
+ if (file === void 0) return null;
+ const measured = file.measured_tests_total ?? 0;
+ if (measured > 0) return { total: measured, files: file.measured_tests ?? [], basis: "measured" };
+ 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 key = pathKey(path);
+ const importers = [...new Set((r.transitive_affected ?? []).map((t) => t.path))].filter((p) => pathKey(p) !== key);
+ const cochange = (r.cochange_warnings ?? []).filter((w) => pathKey(w.changed) === key).map((w) => ({ path: w.missing_partner, score: w.score })).sort((a, b) => b.score - a.score);
+ const tests = testsOf((r.test_impact?.files ?? []).find((f) => pathKey(f.source_file) === key));
+ return { importers, cochange, tests };
+}
+__name(blastFacts, "blastFacts");
+var allActivities = /* @__PURE__ */ __name((state2) => state2.turns.flatMap((t) => t.activities), "allActivities");
+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");
+function names(command, test) {
+ const slashed = test.replace(/\\/g, "/");
+ const parts = slashed.split("/");
+ const stem = (parts.at(-1) ?? "").replace(/\.[^.]+$/, "");
+ const folder = parts.at(-2) ?? "";
+ 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;
+ const run = t === null ? 0 : testsRun(state2, t.files);
+ return {
+ path,
+ importers: facts.importers.length > seen ? { total: facts.importers.length, opened: seen } : null,
+ cochange: facts.cochange.filter((c) => !opened.has(pathKey(c.path))).slice(0, COCHANGE_SHOWN),
+ 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");
+function editedFiles(turn) {
+ const out = /* @__PURE__ */ new Map();
+ for (const a of turn.activities) {
+ const path = a.kind === "edit" && !a.isError ? a.paths[0] : void 0;
+ if (path !== void 0 && !out.has(pathKey(path))) out.set(pathKey(path), path);
}
- var k = nodes.length;
- while (end !== ancestor) {
- nodes.splice(k, 0, end);
- end = end.parent;
+ 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, key, at) {
+ return allActivities(state2).some((a) => a.kind === "search" && a.startedAt < at && a.hitPaths.some((p) => pathKey(p) === key));
+}
+__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();
+ for (const a of turn.activities.filter((x) => isFile(x) && !x.isError && x.paths[0] !== void 0)) {
+ const key = pathKey(a.paths[0]);
+ if (!first.has(key)) first.set(key, a);
+ if (a.kind === "edit") edited.add(key);
}
- return nodes;
-}
-__name(path_default, "default");
-function leastCommonAncestor(a, b) {
- if (a === b) return a;
- var aNodes = a.ancestors(), bNodes = b.ancestors(), c = null;
- a = aNodes.pop();
- b = bNodes.pop();
- while (a === b) {
- c = a;
- a = aNodes.pop();
- b = bNodes.pop();
+ const rows = [...first].map(([key, a]) => ({ path: a.paths[0], kind: edited.has(key) ? "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",
+ read: "read",
+ search: "search",
+ shell: "shell",
+ edit: "other",
+ other: "other"
+};
+function contextBytes(turn) {
+ const out = { repowise: 0, read: 0, search: 0, shell: 0, other: 0 };
+ for (const a of turn.activities) {
+ const kind = CONTEXT_OF[a.kind];
+ if (kind !== null && a.bytes !== null) out[kind] += a.bytes;
}
- return c;
+ return out;
}
-__name(leastCommonAncestor, "leastCommonAncestor");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/ancestors.js
-function ancestors_default() {
- var node = this, nodes = [node];
- while (node = node.parent) {
- nodes.push(node);
+__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)) {
+ const key = a.kind === "edit" && a.paths[0] !== void 0 ? pathKey(a.paths[0]) : null;
+ if (key !== null && !out.has(key)) out.set(key, a.startedAt);
}
- return nodes;
+ return out;
}
-__name(ancestors_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/descendants.js
-function descendants_default() {
- return Array.from(this);
+__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");
+ return new Set(allActivities(state2).filter((a) => a.kind === "repowise" && before(a)).map((a) => a.id));
}
-__name(descendants_default, "default");
+__name(answeredBeforeEdit, "answeredBeforeEdit");
-// ../../node_modules/d3-hierarchy/src/hierarchy/leaves.js
-function leaves_default() {
- var leaves = [];
- this.eachBefore(function(node) {
- if (!node.children) {
- leaves.push(node);
- }
- });
- return leaves;
+// src/views/copy.ts
+var HINTS = {
+ "no-server": "Lens map needs the local server: repowise serve --no-ui",
+ auth: "local server needs an API key; Lens does not read keys",
+ unlisted: "Lens map needs a local server for this repo: repowise serve --no-ui",
+ "no-index": "index this repo for Lens: repowise init --no-prose --yes",
+ "no-cli": "Lens needs the Repowise CLI: pip install repowise"
+};
+function freshnessLine(f) {
+ const changed = f.changedFiles === null ? "" : ` (${countOf(f.changedFiles, "file", "files")} changed)`;
+ return `index behind HEAD${changed} · repowise update`;
}
-__name(leaves_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/links.js
-function links_default() {
- var root = this, links = [];
- root.each(function(node) {
- if (node !== root) {
- links.push({ source: node.parent, target: node });
- }
- });
- return links;
+__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(links_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/iterator.js
-function* iterator_default() {
- var node = this, current, next = [node], children, i, n;
- do {
- current = next.reverse(), next = [];
- while (node = current.pop()) {
- yield node;
- if (children = node.children) {
- for (i = 0, n = children.length; i < n; ++i) {
- next.push(children[i]);
- }
- }
- }
- } while (next.length);
+__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`);
+ const failures = [s.failed > 0 ? `${s.failed.toLocaleString("en-US")} failed` : "", s.errors > 0 ? countOf(s.errors, "error", "errors") : ""];
+ if (s.failed + s.errors > 0) parts.push(failures.filter((f) => f !== "").join(", "));
+ const more = s.refs.length > 1 ? ` (+${s.refs.length - 1} more)` : "";
+ parts.push(`repowise expand ${s.refs[0]}${more}`);
+ return parts.join(" · ");
}
-__name(iterator_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/hierarchy/index.js
-function hierarchy(data, children) {
- if (data instanceof Map) {
- data = [void 0, data];
- if (children === void 0) children = mapChildren;
- } else if (children === void 0) {
- children = objectChildren;
- }
- var root = new Node(data), node, nodes = [root], child, childs, i, n;
- while (node = nodes.pop()) {
- if ((childs = children(node.data)) && (n = (childs = Array.from(childs)).length)) {
- node.children = childs;
- for (i = n - 1; i >= 0; --i) {
- nodes.push(child = childs[i] = new Node(childs[i]));
- child.parent = node;
- child.depth = node.depth + 1;
- }
- }
+__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}`;
}
- return root.eachBefore(computeHeight);
+ 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(hierarchy, "hierarchy");
-function node_copy() {
- return hierarchy(this).eachBefore(copyData);
+__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)}` : "";
+ const head = `${countOf(d.tokens, "token", "tokens")}${inferred}${usd} saved`;
+ const full = `${head} since this session started · all agents on this repo`;
+ return full.length <= columns ? full : `${head} this session · all agents`;
}
-__name(node_copy, "node_copy");
-function objectChildren(d) {
- return d.children;
+__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`;
+var RUN_TESTS = "Run tests";
+var WHY = "Why";
+var DETAILS = "Details";
+var OVERLAP_MARK = "◦";
+function reviewFailed(message) {
+ return `Change review could not run: ${message}`;
}
-__name(objectChildren, "objectChildren");
-function mapChildren(d) {
- return Array.isArray(d) ? d[1] : null;
+__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(mapChildren, "mapChildren");
-function copyData(node) {
- if (node.data.value !== void 0) node.value = node.data.value;
- node.data = node.data.data;
+__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(copyData, "copyData");
-function computeHeight(node) {
- var height = 0;
- do
- node.height = height;
- while ((node = node.parent) && node.height < ++height);
+__name(noNewFindings, "noNewFindings");
+function healthImproved(resolved) {
+ return `improved, ${countOf(resolved, "finding", "findings")} resolved, none new`;
}
-__name(computeHeight, "computeHeight");
-function Node(data) {
- this.data = data;
- this.depth = this.height = 0;
- this.parent = null;
+__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(Node, "Node");
-Node.prototype = hierarchy.prototype = {
- constructor: Node,
- count: count_default,
- each: each_default,
- eachAfter: eachAfter_default,
- eachBefore: eachBefore_default,
- find: find_default,
- sum: sum_default,
- sort: sort_default,
- path: path_default,
- ancestors: ancestors_default,
- descendants: descendants_default,
- leaves: leaves_default,
- links: links_default,
- copy: node_copy,
- [Symbol.iterator]: iterator_default
-};
-
-// ../../node_modules/d3-hierarchy/src/accessors.js
-function required(f) {
- if (typeof f !== "function") throw new Error();
- return f;
+__name(notCompared, "notCompared");
+function improvedShort(resolved) {
+ return `improved, ${resolved.toLocaleString("en-US")} resolved`;
}
-__name(required, "required");
-
-// ../../node_modules/d3-hierarchy/src/constant.js
-function constantZero() {
- return 0;
+__name(improvedShort, "improvedShort");
+function newFindings(total2, required2) {
+ return `${countOf(total2, "new finding", "new findings")}, ${required2 ? "review required" : "low severity"}`;
}
-__name(constantZero, "constantZero");
-function constant_default(x) {
- return function() {
- return x;
- };
+__name(newFindings, "newFindings");
+function resolvedToo(resolved) {
+ return `${countOf(resolved, "finding", "findings")} resolved`;
}
-__name(constant_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/treemap/round.js
-function round_default(node) {
- node.x0 = Math.round(node.x0);
- node.y0 = Math.round(node.y0);
- node.x1 = Math.round(node.x1);
- node.y1 = Math.round(node.y1);
+__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(round_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/treemap/dice.js
-function dice_default(parent, x0, y0, x1, y1) {
- var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (x1 - x0) / parent.value;
- while (++i < n) {
- node = nodes[i], node.y0 = y0, node.y1 = y1;
- node.x0 = x0, node.x1 = x0 += node.value * k;
- }
+__name(findingLine, "findingLine");
+function moreFindings(more) {
+ return `and ${more.toLocaleString("en-US")} more (Details)`;
}
-__name(dice_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/treemap/slice.js
-function slice_default(parent, x0, y0, x1, y1) {
- var nodes = parent.children, node, i = -1, n = nodes.length, k = parent.value && (y1 - y0) / parent.value;
- while (++i < n) {
- node = nodes[i], node.x0 = x0, node.x1 = x1;
- node.y0 = y0, node.y1 = y0 += node.value * k;
- }
+__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(slice_default, "default");
-
-// ../../node_modules/d3-hierarchy/src/treemap/squarify.js
-var phi = (1 + Math.sqrt(5)) / 2;
-function squarifyRatio(ratio, parent, x0, y0, x1, y1) {
- var rows = [], nodes = parent.children, row, nodeValue, i0 = 0, i1 = 0, n = nodes.length, dx, dy, value = parent.value, sumValue, minValue, maxValue, newRatio, minRatio, alpha, beta;
- while (i0 < n) {
- dx = x1 - x0, dy = y1 - y0;
- do
- sumValue = nodes[i1++].value;
- while (!sumValue && i1 < n);
- minValue = maxValue = sumValue;
- alpha = Math.max(dy / dx, dx / dy) / (value * ratio);
- beta = sumValue * sumValue * alpha;
- minRatio = Math.max(maxValue / beta, beta / minValue);
- for (; i1 < n; ++i1) {
- sumValue += nodeValue = nodes[i1].value;
- if (nodeValue < minValue) minValue = nodeValue;
- if (nodeValue > maxValue) maxValue = nodeValue;
- beta = sumValue * sumValue * alpha;
- newRatio = Math.max(maxValue / beta, beta / minValue);
- if (newRatio > minRatio) {
- sumValue -= nodeValue;
- break;
- }
- minRatio = newRatio;
- }
- rows.push(row = { value: sumValue, dice: dx < dy, children: nodes.slice(i0, i1) });
- if (row.dice) dice_default(row, x0, y0, x1, value ? y0 += dy * sumValue / value : y1);
- else slice_default(row, x0, y0, value ? x0 += dx * sumValue / value : x1, y1);
- value -= sumValue, i0 = i1;
- }
- return rows;
+__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(squarifyRatio, "squarifyRatio");
-var squarify_default = (/* @__PURE__ */ __name((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);
-
-// ../../node_modules/d3-hierarchy/src/treemap/index.js
-function treemap_default() {
- var tile = squarify_default, round = false, dx = 1, dy = 1, paddingStack = [0], paddingInner = constantZero, paddingTop = constantZero, paddingRight = constantZero, paddingBottom = constantZero, paddingLeft = constantZero;
- function treemap(root) {
- root.x0 = root.y0 = 0;
- root.x1 = dx;
- root.y1 = dy;
- root.eachBefore(positionNode);
- paddingStack = [0];
- 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;
- if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
- node.x0 = x0;
- node.y0 = y0;
- node.x1 = x1;
- node.y1 = y1;
- if (node.children) {
- p = paddingStack[node.depth + 1] = paddingInner(node) / 2;
- x0 += paddingLeft(node) - p;
- y0 += paddingTop(node) - p;
- x1 -= paddingRight(node) - p;
- y1 -= paddingBottom(node) - p;
- if (x1 < x0) x0 = x1 = (x0 + x1) / 2;
- if (y1 < y0) y0 = y1 = (y0 + y1) / 2;
- tile(node, x0, y0, x1, y1);
- }
- }
- __name(positionNode, "positionNode");
- treemap.round = function(x) {
- return arguments.length ? (round = !!x, treemap) : round;
- };
- treemap.size = function(x) {
- return arguments.length ? (dx = +x[0], dy = +x[1], treemap) : [dx, dy];
- };
- treemap.tile = function(x) {
- return arguments.length ? (tile = required(x), treemap) : tile;
- };
- treemap.padding = function(x) {
- return arguments.length ? treemap.paddingInner(x).paddingOuter(x) : treemap.paddingInner();
- };
- treemap.paddingInner = function(x) {
- return arguments.length ? (paddingInner = typeof x === "function" ? x : constant_default(+x), treemap) : paddingInner;
- };
- treemap.paddingOuter = function(x) {
- return arguments.length ? treemap.paddingTop(x).paddingRight(x).paddingBottom(x).paddingLeft(x) : treemap.paddingTop();
- };
- treemap.paddingTop = function(x) {
- return arguments.length ? (paddingTop = typeof x === "function" ? x : constant_default(+x), treemap) : paddingTop;
- };
- treemap.paddingRight = function(x) {
- return arguments.length ? (paddingRight = typeof x === "function" ? x : constant_default(+x), treemap) : paddingRight;
- };
- treemap.paddingBottom = function(x) {
- return arguments.length ? (paddingBottom = typeof x === "function" ? x : constant_default(+x), treemap) : paddingBottom;
- };
- treemap.paddingLeft = function(x) {
- return arguments.length ? (paddingLeft = typeof x === "function" ? x : constant_default(+x), treemap) : paddingLeft;
- };
- return treemap;
+__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(treemap_default, "default");
-
-// ../types/src/health.ts
-var EXCELLENT_MIN = 8.5;
-var GOOD_MIN = 7;
-var FAIR_MIN = 5.5;
-var NEEDS_WORK_MIN = 4;
-var HEALTH_BAND_ORDER = [
- "at_risk",
- "needs_work",
- "fair",
- "good",
- "excellent"
-];
-var HEALTH_BAND_LABEL = {
- excellent: "Excellent",
- good: "Good",
- fair: "Fair",
- needs_work: "Needs work",
- at_risk: "At risk"
-};
-function bandForScore(score) {
- if (score >= EXCELLENT_MIN) return "excellent";
- if (score >= GOOD_MIN) return "good";
- if (score >= FAIR_MIN) return "fair";
- if (score >= NEEDS_WORK_MIN) return "needs_work";
- return "at_risk";
+__name(overlapLine, "overlapLine");
+function overlapShort(branches) {
+ return `${OVERLAP_MARK} ${countOf(branches, "other branch edits", "other branches edit")} these files`;
}
-__name(bandForScore, "bandForScore");
-
-// ../ui/src/brand.ts
-var BRAND = {
- /** Accent orange — the brand fill (CTAs, owl eyes, highlights). */
- accent: "#f59520",
- /** Accent text on light surfaces (darkened for 4.5:1 contrast). */
- accentTextLight: "#a16215",
- /** Brand plum — logo strokes on light surfaces, secondary accent. */
- plum: "#473659",
- /** Plum near-black — primary ink on warm paper. */
- ink: "#241b2c",
- /** Warm paper — the light-mode page background. */
- paper: "#fbf6f1",
- /** Cream — the logo stroke color on dark surfaces. */
- cream: "#fce9dd"
-};
-var DARK = {
- bgRoot: "#0e0e0f",
- bgSurface: "#141416",
- bgElevated: "#191a1c",
- bgInset: "#0a0a0b",
- textPrimary: "#f2f2f3",
- textSecondary: "#b4b4b9",
- textTertiary: "#7c7c82",
- accentPrimary: "#f59520",
- accentFill: "#f59520",
- accentSecondary: "#a98fc4",
- success: "#34d399",
- warning: "#f2a03d",
- error: "#e06a5a"
-};
-var DARK_CANVAS = {
- nodeAtRisk: "#b0544b",
- nodeNeedsWork: "#bd7c42",
- nodeFair: "#a89453",
- nodeGood: "#42906f",
- nodeExcellent: "#5cb389",
- nodeNeutral: "#333336",
- caution: "#d9b04a"
+__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",
+ loading: "Lens map: loading the map",
+ failed: "Lens map could not load; it tries again on /lens",
+ desktop: "Lens map: not drawn on this surface (terminal and desktop app only)",
+ tooLarge: "Lens map has too much detail to draw here; the terminal map shows it",
+ noScore: "Not scored",
+ waiting: "Lens map is ready; this pane is too narrow to open on its own. Run /lens",
+ healthOn: "Health colours: on",
+ healthOff: "Health colours: off",
+ quiet: "Nothing lit yet this turn. Files Claude searches, opens and edits light up here."
};
-var DARK_CANVAS_BAND = {
- excellent: DARK_CANVAS.nodeExcellent,
- good: DARK_CANVAS.nodeGood,
- fair: DARK_CANVAS.nodeFair,
- needs_work: DARK_CANVAS.nodeNeedsWork,
- at_risk: DARK_CANVAS.nodeAtRisk
+var STORY_COPY = {
+ searched: "SEARCHED",
+ opened: "OPENED",
+ edited: "EDITED",
+ reaches: "REACHES"
};
-
-// src/views/map.ts
-var UPPER_HALF = 9600;
-var hex = /* @__PURE__ */ __name((s) => parseInt(s.slice(1), 16), "hex");
-var ACCENT = hex(BRAND.accent);
-var GROUND = hex(DARK.bgRoot);
-var LABEL_FG = hex(DARK.textSecondary);
-var NEUTRAL = hex(DARK_CANVAS.nodeNeutral);
-var BLACK = 0;
-var SPLIT_SHARE = 0.25;
-var MAX_SPLITS = 8;
-var GUTTER_MIN = 6;
-var EDGE_MIN = 3;
-function colorForScore(score) {
- return score === null ? NEUTRAL : hex(DARK_CANVAS_BAND[bandForScore(score)]);
+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(colorForScore, "colorForScore");
-function mix(a, b, amount) {
- const ch = /* @__PURE__ */ __name((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(mapAlt, "mapAlt");
+function notPlacedLine(reason) {
+ return `Lens map needs a wider terminal: ${reason}`;
}
-__name(mix, "mix");
-var byName = /* @__PURE__ */ __name((a, b) => a < b ? -1 : a > b ? 1 : 0, "byName");
-function dirsOf(path) {
- return path.split("/").slice(0, -1);
+__name(notPlacedLine, "notPlacedLine");
+var SCOPE_REST = "rest too small to draw";
+function indexedPart(age) {
+ return `indexed ${age}`;
}
-__name(dirsOf, "dirsOf");
-function keyOf(path, split2) {
- const dirs = dirsOf(path);
- let depth = Math.min(1, dirs.length);
- while (depth < dirs.length && split2.has(dirs.slice(0, depth).join("/"))) depth++;
- return dirs.slice(0, depth).join("/");
+__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")} not on the map`);
+ return parts;
}
-__name(keyOf, "keyOf");
-function nextSplit(files, split2, limit) {
- const weight = /* @__PURE__ */ new Map();
- for (const f of files) {
- const key = keyOf(f.file_path, split2);
- weight.set(key, (weight.get(key) ?? 0) + f.nloc);
- }
- const heavy = [...weight].filter(([key, w]) => key !== "" && w > limit).sort((a, b) => b[1] - a[1] || byName(a[0], b[0]));
- for (const [key] of heavy) {
- const deeper = /* @__PURE__ */ new Set([...split2, key]);
- const parts = new Set(files.filter((f) => keyOf(f.file_path, split2) === key).map((f) => keyOf(f.file_path, deeper)));
- if (parts.size > 1) return key;
- }
- return null;
+__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 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]",
+ tabs: { flow: "Flow", map: "Map", ask: "Ask", recap: "Recap" },
+ askLabel: "ask ",
+ askPlaceholder: "why ...? asks the decision records; anything else asks the index",
+ askSubmit: "ask",
+ askIdle: "Ask about this repo. Answers cite the evidence they used.",
+ askBusy: "still answering the last question; ask again when it lands",
+ noEvidence: "no evidence cited",
+ fromIndex: "Built from the index",
+ fromModel: "Written by this repo's configured model, from the index"
+};
+var ASK_CHARS = 4e3;
+function askingLine(tool) {
+ return tool === "get_why" ? "asking the decision records..." : "asking the index...";
}
-__name(nextSplit, "nextSplit");
-function groupKeys(files) {
- const split2 = /* @__PURE__ */ new Set();
- const limit = files.reduce((sum, f) => sum + f.nloc, 0) * SPLIT_SHARE;
- for (let i = 0; i < MAX_SPLITS; i++) {
- const key = nextSplit(files, split2, limit);
- if (key === null) break;
- split2.add(key);
- }
- return files.map((f) => keyOf(f.file_path, split2));
+__name(askingLine, "askingLine");
+function askFailedLine(message) {
+ return `Could not answer: ${message}`;
}
-__name(groupKeys, "groupKeys");
-function treemapOf(files, width, height) {
- const keys = groupKeys(files);
- const groups = /* @__PURE__ */ new Map();
- files.forEach((file, i) => {
- const key = keys[i] ?? "";
- groups.set(key, [...groups.get(key) ?? [], { name: file.file_path, file }]);
- });
- const data = { name: "", children: [...groups].map(([name, children]) => ({ name, children })) };
- 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([width, height])(root);
+__name(askFailedLine, "askFailedLine");
+function askCut(chars) {
+ return `reply cut at ${formatNumber(chars)} characters`;
}
-__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");
-function pixelSpan(from, to) {
- return [Math.ceil(from - 0.5), Math.ceil(to - 0.5)];
+__name(askCut, "askCut");
+function moreRows(more) {
+ return `and ${formatNumber(more)} more`;
}
-__name(pixelSpan, "pixelSpan");
-function groupInterior(rect, width, 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 < width ? x1 - 1 : x1, y1: gutter && y1 < height ? y1 - 1 : y1 };
+__name(moreRows, "moreRows");
+var RECAP_COPY = {
+ files: "Files",
+ fromReview: "from the last change review",
+ review: "Change review",
+ health: "Code health",
+ findings: "Findings",
+ tests: "Tests to run",
+ overlap: "Branches overlapping",
+ saved: "Saved",
+ decisions: "Decisions surfaced",
+ noReview: "none this session",
+ notCompared: "not compared",
+ noTests: "none named",
+ noOverlap: "none found",
+ notReported: "not reported",
+ noSavings: "nothing yet since this session started",
+ savingsNeedServer: "needs the local server: repowise serve --no-ui",
+ noDecisions: "none",
+ noModel: "Lens made no model calls.",
+ fromIndex: "Every figure here is read from the local index."
+};
+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(groupInterior, "groupInterior");
-function placeFile(leaf, group, inner) {
- const file = leaf.data.file;
- const rect = rectOf(leaf);
- const [x0, x1] = pixelSpan(rect.x, rect.x + rect.w);
- const [y0, y1] = pixelSpan(rect.y, rect.y + rect.h);
- return {
- path: file.file_path,
- score: file.score,
- nloc: file.nloc,
- group,
- rect,
- px0: Math.max(x0, inner.x0),
- py0: Math.max(y0, inner.y0),
- px1: Math.min(x1, inner.x1),
- py1: Math.min(y1, inner.y1)
- };
+__name(filesTouched, "filesTouched");
+function findingsCounts(resolved, total2) {
+ return `${formatNumber(resolved)} resolved · ${countOf(total2, "new finding", "new findings")}`;
}
-__name(placeFile, "placeFile");
-function paintFile(base, width, f) {
- const fill = colorForScore(f.score);
- const edge = mix(fill, BLACK, 0.3);
- const edgeX = f.px1 - f.px0 >= EDGE_MIN ? f.px1 - 1 : -1;
- const edgeY = f.py1 - f.py0 >= EDGE_MIN ? f.py1 - 1 : -1;
- for (let y = f.py0; y < f.py1; y++) {
- base.fill(y === edgeY ? edge : fill, y * width + f.px0, y * width + f.px1);
- if (edgeX >= 0) base[y * width + edgeX] = edge;
- }
+__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(paintFile, "paintFile");
-function labelText(key, width) {
- const parts = key.split("/");
- const rungs = [key, parts.slice(-2).join("/"), parts[parts.length - 1] ?? ""];
- const text2 = rungs.find((r) => r.length > 0 && r.length <= width);
- return text2 !== void 0 && /^[\x20-\x7e]+$/.test(text2) ? text2 : null;
+__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(labelText, "labelText");
-function labelFor(g, columns, rows) {
- const col = Math.ceil(g.rect.x);
- const row = Math.ceil(g.rect.y / 2);
- const width = Math.min(columns, Math.floor(g.rect.x + g.rect.w)) - col - 1;
- const height = Math.floor((g.rect.y + g.rect.h) / 2) - row;
- if (g.key === "" || height < 2 || row >= rows) return null;
- const text2 = labelText(g.key, width);
- return text2 === null ? null : { row, col, text: text2 };
+__name(recapFooter, "recapFooter");
+var BRIEF_COPY = {
+ compacted: "context compacted",
+ button: "Brief Claude",
+ intro: "The context was compacted. This brief is built from the Repowise index and this session's edits:",
+ files: "Files edited:",
+ decisions: "Decisions in play:",
+ review: "Open review items:"
+};
+var BRIEF_CHARS = 1200;
+function briefDecision(title, reviewed) {
+ return reviewed ? `${title} (standing decision)` : `${title} (found in the code, not yet reviewed)`;
}
-__name(labelFor, "labelFor");
-function labelsFor(groups, columns, rows) {
- return [...groups].sort((a, b) => b.nloc - a.nloc).map((g) => labelFor(g, columns, rows)).filter((l) => l !== null);
+__name(briefDecision, "briefDecision");
+function briefTests(t) {
+ return `tests to run, ${testsBasis(t.measured)}: ${t.tests.join(" ")}`;
}
-__name(labelsFor, "labelsFor");
-function layoutMap(feed, columns, rows, caseInsensitive) {
- const width = columns;
- const height = rows * 2;
- const root = treemapOf(
- feed.filter((f) => f.nloc > 0),
- width,
- height
- );
- const groups = [];
- const files = [];
- for (const node of root.children ?? []) {
- const group = groups.push({ key: node.data.name, rect: rectOf(node), nloc: node.value ?? 0 }) - 1;
- const inner = groupInterior(rectOf(node), width, height);
- for (const leaf of node.children ?? []) files.push(placeFile(leaf, group, inner));
- }
- const base = new Uint32Array(width * height).fill(GROUND);
- const drawn = [];
- const index = /* @__PURE__ */ new Map();
- files.forEach((f, i) => {
- if (f.px1 <= f.px0 || f.py1 <= f.py0) return;
- drawn.push(i);
- index.set(caseInsensitive ? f.path.toLowerCase() : f.path, i);
- paintFile(base, width, f);
- });
- return { columns, rows, width, height, groups, files, drawn, index, caseInsensitive, labels: labelsFor(groups, columns, rows), base };
+__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.",
+ notConnected: "Repowise is not connected in this repo, so only Claude's own steps show here.",
+ beforeAccept: "BEFORE YOU ACCEPT",
+ workingSet: "WORKING SET",
+ context: "CONTEXT",
+ calls: "REPOWISE CALLS",
+ asOfIndex: "as of the last index",
+ edited: "edited",
+ read: "read",
+ search: "search",
+ direct: "direct",
+ hotspot: "hotspot",
+ subagent: "subagent",
+ asking: "asking...",
+ error: "error",
+ beforeEdit: "from the index before this edit",
+ howAnswered: "how it was answered",
+ excerpt: "reply begins",
+ thenOpened: "Claude then opened",
+ nothingOpened: "nothing yet",
+ noRepowise: "No Repowise calls",
+ editNamed: "edit landed in a file Repowise named",
+ next: "Next call",
+ previous: "Previous call"
+};
+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` : "";
+ if (t.opened > 0) parts.push(`Claude opened ${countOf(t.opened, "file", "files")}${named2}`);
+ if (t.editNamed) parts.push(FLOW_COPY.editNamed);
+ return parts.join(" · ");
}
-__name(layoutMap, "layoutMap");
-function labelCovered(label, marked, width) {
- if (marked === void 0) return false;
- for (let c = label.col; c < label.col + label.text.length; c++) {
- if (marked[2 * label.row * width + c] || marked[(2 * label.row + 1) * width + c]) return true;
- }
- return false;
+__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 = [];
+ if (k.hotspot === true) parts.push(FLOW_COPY.hotspot);
+ if (k.callerFiles !== null && k.callerFiles > 0) parts.push(countOf(k.callerFiles, "file uses it", "files use it"));
+ if (k.recentOwner !== null) parts.push(`recent owner ${k.recentOwner.name} ${Math.round(k.recentOwner.share * 100)} %`);
+ return parts;
}
-__name(labelCovered, "labelCovered");
-function encodeCells(layout, pixels, marked) {
- const { columns, rows, width } = layout;
- const words = new Uint32Array(columns * rows * 3);
- for (let i = 0; i < columns * rows; i++) {
- const r = Math.floor(i / columns);
- const c = i % columns;
- words[i * 3] = UPPER_HALF;
- words[i * 3 + 1] = pixels[2 * r * width + c] ?? GROUND;
- words[i * 3 + 2] = pixels[(2 * r + 1) * width + c] ?? GROUND;
- }
- for (const label of layout.labels) {
- if (labelCovered(label, marked, width)) continue;
- for (let k = 0; k < label.text.length && label.col + k < columns; k++) {
- const o = (label.row * columns + label.col + k) * 3;
- words.set([label.text.charCodeAt(k), LABEL_FG, GROUND], o);
- }
- }
- return new Uint8Array(words.buffer).toBase64();
+__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"],
+ symbols: ["symbol", "symbols"],
+ callers: ["caller", "callers"],
+ callees: ["callee", "callees"],
+ decisions: ["decision", "decisions"],
+ hotspots: ["hotspot", "hotspots"],
+ dependents: ["direct dependent", "direct dependents"],
+ coChange: ["co-change partner", "co-change partners"],
+ contributors: ["contributor", "contributors"],
+ citations: ["cited file", "cited files"],
+ bodies: ["symbol body", "symbol bodies"],
+ rationale: ["rationale comment", "rationale comments"],
+ guesses: ["best guess", "best guesses"],
+ commits: ["commit", "commits"],
+ results: ["result", "results"],
+ lines: ["line", "lines"]
+};
+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 BEHIND = [
+ (b) => named(b.commit, (c) => `indexed at ${c}`),
+ (b) => named(b.ageDays, ageText),
+ (b) => named(b.verified, (v) => v ? "verified against the code" : "not verified"),
+ (b) => when(b.complete === false, "partial: the server capped it"),
+ (b) => named(b.confidence, (c) => `confidence ${c}`),
+ (b) => named(b.grounding, (g) => `grounding ${g.replace(/_/g, " ")}`),
+ (b) => named(b.retrieval, (r) => `retrieval ${r}`),
+ (b, bytes) => named(b.budget, (budget) => `reply ${bytes === null ? countOf(budget.used, "character", "characters") : sizeText(bytes)} (cap ${countOf(budget.limit, "character", "characters")})`),
+ (b) => named(b.omittedTokens, (t) => `${countOf(t, "token", "tokens")} left out, restorable`),
+ (b) => named(b.degraded, (d) => `degraded: ${d}`),
+ (b) => when(b.semantic === false, "semantic search off")
+];
+function behindParts(b, bytes = null) {
+ return BEHIND.map((part) => part(b, bytes)).filter((p) => p !== null);
}
-__name(encodeCells, "encodeCells");
+__name(behindParts, "behindParts");
// src/views/elements.ts
function text(value, props = {}) {
@@ -1669,273 +2683,850 @@ function materialize(node, table, presses = {}) {
}
__name(materialize, "materialize");
-// src/views/overlay.ts
-var EDIT_TINT = mix(ACCENT, 16777215, 0.45);
-var READ_DIM = 0.4;
-var PATH_AMOUNT = 0.85;
-var MATCH_FLASH = 0.85;
-var MATCH_REST = 0.25;
-var RING_AMOUNT = 0.5;
-var SMALL = 3;
-function lookup(layout, rel) {
- return layout.index.get(layout.caseInsensitive ? rel.toLowerCase() : rel);
-}
-__name(lookup, "lookup");
-function locate(layout, abs, root) {
- const rel = relativeTo(abs, root, layout.caseInsensitive);
- return rel === null ? void 0 : lookup(layout, rel);
-}
-__name(locate, "locate");
-function split(items, find) {
- const found = [];
+// src/views/mapPane.ts
+var MAP_KEY = "lens-map";
+var HEALTH_KEY = "lens-map-health";
+var MAX_COLUMNS = 512;
+var MAX_ROWS = 256;
+var MIN_ROWS = 4;
+var GAP = 2;
+var SEP = " · ";
+var STORY_ROWS = 4;
+var SCOPE_ROWS = 2;
+var TOGGLE_ROWS = 1;
+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 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 }
+];
+function packRows(items, width2, columns, gap) {
+ const rows = [];
+ let used = Infinity;
for (const item of items) {
- const i = find(item);
- if (i !== void 0) found.push(i);
- }
- return { found, missing: items.length - found.length };
-}
-__name(split, "split");
-function resolveOverlay(layout, trail, repoRoot) {
- const reads = split(trail.reads, (p) => locate(layout, p, repoRoot));
- const hits = split(trail.hits, (p) => locate(layout, p, repoRoot)).found;
- const callers = split(trail.callers?.status === "ready" ? trail.callers.paths : [], (p) => lookup(layout, p));
- const edited = trail.edit === null ? null : locate(layout, trail.edit, repoRoot) ?? null;
- const edit = trail.edit === null ? null : { name: trail.edit.slice(trail.edit.lastIndexOf("/") + 1), callers: trail.callers, notDrawn: callers.missing };
- return {
- overlay: { reads: reads.found, hits, edited, callers: callers.found },
- reads: { count: trail.reads.length, capped: trail.readsCapped, notDrawn: reads.missing },
- matched: trail.searches === 0 ? null : trail.hits.length,
- edit
- };
+ const w = width2(item);
+ const last = rows[rows.length - 1];
+ if (last === void 0 || used + gap + w > columns) {
+ rows.push([item]);
+ used = w;
+ } else {
+ last.push(item);
+ used += gap + w;
+ }
+ }
+ return rows;
}
-__name(resolveOverlay, "resolveOverlay");
-function center(f) {
- return [Math.floor((f.px0 + f.px1 - 1) / 2), Math.floor((f.py0 + f.py1 - 1) / 2)];
+__name(packRows, "packRows");
+var swatchWidth = /* @__PURE__ */ __name((s) => s.label.length + 2, "swatchWidth");
+function legendRows(columns, health2 = false) {
+ const bands = health2 ? packRows(BAND_SWATCHES, swatchWidth, columns, GAP).length : 0;
+ return STORY_ROWS + bands + SCOPE_ROWS + TOGGLE_ROWS;
}
-__name(center, "center");
-function distance(a, b) {
- const [ax, ay] = center(a);
- const [bx, by] = center(b);
- return Math.hypot(ax - bx, ay - by);
+__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(distance, "distance");
-function rippleRadius(layout, overlay) {
- const origin = overlay.edited === null ? void 0 : layout.files[overlay.edited];
- if (!origin || overlay.callers.length === 0) return 0;
- return Math.max(...overlay.callers.map((i) => distance(origin, layout.files[i]))) + 3;
+__name(mapSize, "mapSize");
+function swatchRows(items, columns) {
+ return packRows(items, swatchWidth, columns, GAP).map(
+ (row2) => box(
+ { flexDirection: "row", columnGap: GAP },
+ row2.map((s) => box({ flexDirection: "row" }, [text(s.glyph, { color: s.color }), text(` ${s.label}`, { dimColor: true })]))
+ )
+ );
}
-__name(rippleRadius, "rippleRadius");
-function inside(layout, x, y) {
- return x >= 0 && y >= 0 && x < layout.width && y < layout.height;
+__name(swatchRows, "swatchRows");
+function scopeRows(scope, columns) {
+ const rows = /* @__PURE__ */ __name((parts2) => packRows(parts2, (p) => p.length, columns, SEP.length), "rows");
+ let parts = scopeParts(scope);
+ for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {
+ if (rows(parts).length <= 2) break;
+ parts = parts.filter((p) => p !== optional);
+ }
+ return rows(parts).slice(0, 2).map((row2) => row2.join(SEP));
}
-__name(inside, "inside");
-function set(p, x, y, color2) {
- if (!inside(p.layout, x, y)) return;
- const width = p.layout.width;
- p.px[y * width + x] = color2;
- p.marked[y * width + x] = 1;
+__name(scopeRows, "scopeRows");
+function storyRow(head, segs, columns) {
+ let room = Math.max(0, columns - HEAD);
+ const parts = [text(head.padEnd(HEAD), { dimColor: true })];
+ for (const s of segs) {
+ if (room <= 0) break;
+ const shown = fit(s.text, room);
+ room -= shown.length;
+ parts.push(text(shown, s.color === void 0 ? {} : { color: s.color }));
+ }
+ 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 }];
+ const paths = [...reach.callers.paths].sort((a, b) => Number(reach.opened.has(b.toLowerCase())) - Number(reach.opened.has(a.toLowerCase())));
+ 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 = [
+ [STORY_COPY.searched, searchedSegs(story)],
+ [STORY_COPY.opened, openedSegs(story, hexOf(pal.importer))],
+ [STORY_COPY.edited, editedSegs(story, hexOf(pal.edit))],
+ [STORY_COPY.reaches, reach === null ? [] : reachSegs(reach, hexOf(pal.importer))]
+ ];
+ return rows.filter(([, segs]) => segs.length > 0).map(([head, segs]) => storyRow(head, segs, columns));
}
-__name(set, "set");
-function fillFile(p, f, color2) {
- const w = p.layout.width;
- for (let y = f.py0; y < f.py1; y++) for (let x = f.px0; x < f.px1; x++) set(p, x, y, color2(p.px[y * w + x] ?? GROUND));
+__name(storyView, "storyView");
+function legendView(parts, style, columns) {
+ const story = storyView(parts.story, parts.reach, style, columns);
+ const quiet = story.length === 0 ? [text(fit(MAP_COPY.quiet, columns), { dimColor: true, wrap: "truncate-end" })] : story;
+ return [
+ ...quiet,
+ ...style.health ? swatchRows(BAND_SWATCHES, columns) : [],
+ ...scopeRows(parts.scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" })),
+ button(HEALTH_KEY, "h", style.health ? MAP_COPY.healthOn : MAP_COPY.healthOff, true)
+ ];
}
-__name(fillFile, "fillFile");
-function outlineFile(p, f, color2) {
- for (let x = f.px0; x < f.px1; x++) {
- set(p, x, f.py0, color2);
- set(p, x, f.py1 - 1, color2);
+__name(legendView, "legendView");
+function mapPaneView(layout, cells, parts) {
+ return box({ key: "lens-map-pane", flexDirection: "column" }, [
+ raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),
+ ...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.ts
+var EYES = { open: "◉", shut: "─", side: "◐", happy: "^", still: "•" };
+var BLINK = [...Array(9).fill(EYES.open), EYES.shut];
+var BLINK_MS = 250;
+var EYES_OF = {
+ asleep: EYES.shut,
+ asking: EYES.side,
+ happy: EYES.happy,
+ stopped: EYES.still
+};
+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");
+ return [text("{"), eye(), text(","), eye(), text("}")];
+}
+__name(owl, "owl");
+
+// src/views/theme.ts
+var DARK_THEME = { plum: DARK.accentSecondary, amber: BRAND.accent };
+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_NEXT = "lens-flow-next";
+var FLOW_PREV = "lens-flow-prev";
+var HAPPY_MS = 3e3;
+var NARROW = 80;
+var MIN_BODY = 3;
+var ACTIVE_MARK = "▸";
+var GUTTER = 2;
+var CLOCK_W = 6;
+var DETAIL_W = 20;
+var DETAIL_INDENT = GUTTER + CLOCK_W;
+var EMPTY_W = 70;
+var WORKING_ROWS = 6;
+var FILE_W = 44;
+var KIND_W = 8;
+var VIA_W = 13;
+var BAR_W = 60;
+var BUILT_FROM = 2;
+var TARGET_MIN = 28;
+var SEP2 = " · ";
+var EXCERPT_LINE = 160;
+var rowKey = /* @__PURE__ */ __name((id) => `${FLOW_KEY}-${id}`, "rowKey");
+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");
+function segNode(s) {
+ if (s.press !== void 0) return { type: "Button", props: { key: s.press, label: s.t, plain: true } };
+ const props = {};
+ if (s.color !== void 0) props.color = s.color;
+ 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);
+ const gap = right.length > 0 ? Math.max(2, columns - width(fitted) - width(right)) : 0;
+ 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 dimLine = /* @__PURE__ */ __name((t, columns) => text(fit(t, columns), { dimColor: true, wrap: "truncate-end" }), "dimLine");
+var pad = /* @__PURE__ */ __name((n) => ({ t: " ".repeat(n) }), "pad");
+function wrapWords(words, columns) {
+ return packRows(words.split(" "), (w) => w.length, Math.max(1, columns), 1).map((r) => r.join(" "));
+}
+__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";
+ if (isWorking(state2)) return inFlight(state2) === null ? "watching" : "asking";
+ 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) }];
+ const end = turn.end ?? "answer";
+ 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);
+ const face = box({ flexDirection: "row" }, owl(st, owlEyes(st, v.now, v.still), theme2.amber));
+ const room = v.columns - OWL_WIDTH - 1;
+ const said = notice(v.mode);
+ const tail = said === null ? [] : [dimLine(said, v.columns)];
+ if (turn === void 0) {
+ const [first = "", ...rest] = wrapWords(FLOW_COPY.empty, Math.min(EMPTY_W, room));
+ return [box({ flexDirection: "row", columnGap: 1 }, [face, text(first)]), ...rest.map((l) => text(`${" ".repeat(OWL_WIDTH + 1)}${l}`)), ...tail];
}
- for (let y = f.py0; y < f.py1; y++) {
- set(p, f.px0, y, color2);
- set(p, f.px1 - 1, y, color2);
- }
-}
-__name(outlineFile, "outlineFile");
-var isSmall = /* @__PURE__ */ __name((f) => f.px1 - f.px0 < SMALL || f.py1 - f.py0 < SMALL, "isSmall");
-function paintPath(p, overlay) {
- const files = p.layout.files;
- for (let k = 1; k < overlay.reads.length; k++) {
- const [ax, ay] = center(files[overlay.reads[k - 1]]);
- const [bx, by] = center(files[overlay.reads[k]]);
- const steps = Math.max(Math.abs(bx - ax), Math.abs(by - ay));
- for (let s = 1; s < steps; s += 3) {
- const x = Math.round(ax + (bx - ax) * s / steps);
- const y = Math.round(ay + (by - ay) * s / steps);
- set(p, x, y, mix(p.px[y * p.layout.width + x] ?? GROUND, ACCENT, PATH_AMOUNT));
+ const prompt = turn.prompt.replace(/\s+/g, " ").trim();
+ return [
+ box({ flexDirection: "row", columnGap: 1 }, [face, row(statusSegs(turn, v.now, theme2), room)]),
+ text(fit(answerLine(turnTotals(turn)), v.columns), { wrap: "truncate-end" }),
+ ...prompt === "" ? [] : [dimLine(`"${prompt}"`, v.columns)],
+ ...tail
+ ];
+}
+__name(header, "header");
+var fileName = /* @__PURE__ */ __name((path) => path.split("/").at(-1) ?? path, "fileName");
+function gapLines(g) {
+ const out = [];
+ if (g.importers !== null) out.push(importersLine(g.importers.total, g.importers.opened));
+ if (g.cochange.length > 0) out.push(cochangeLine(g.cochange));
+ 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),
+ ...gapLines(g).map((l) => dimLine(` ${l}`, v.columns))
+ ]);
+ 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));
+ const t = {
+ cards: new Map(Object.entries(v.contexts).map(([p, c]) => [pathKey(p), c])),
+ columns: v.columns,
+ fileW: Math.min(FILE_W, longest, Math.max(8, v.columns - 2 - KIND_W - VIA_W - 4)),
+ theme: theme2
+ };
+ const rows = files.slice(0, WORKING_ROWS).map((f) => workingRow(f, t));
+ const more = files.length > WORKING_ROWS ? [dimLine(` ${moreFiles(files.length - WORKING_ROWS)}`, v.columns)] : [];
+ 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);
+ if (total2 === 0) return [];
+ const cells = cellsOf(bytes, total2, Math.min(BAR_W, columns - 4));
+ const bar = row([pad(2), ...cells.map(([k, n]) => shadeSeg(k, n, theme2))], columns);
+ const legend = cells.map(([k]) => `${SHADE[k]} ${contextPart(k, bytes[k])}`);
+ const first = firstEditMs(turn);
+ const parts = first === null ? legend : [...legend, firstEditText(first)];
+ const lines = packRows(parts, (p) => p.length, Math.max(10, columns - 2), 2).map((r) => dimLine(` ${r.join(" ")}`, columns));
+ 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 }];
+ const segs = [...lead(a, ctx), { t: a.tool, press: rowKey(a.id) }, pad(2), { t: what, flex: true }, ...sub];
+ 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 [];
+ const excerpt = reply.excerpt === "" ? [] : [labeled(FLOW_COPY.excerpt, reply.excerpt.replace(/\s+/g, " ").slice(0, EXCERPT_LINE), ctx, a.id)];
+ 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)) {
+ const by = a.namedBy?.id;
+ const path = a.paths[0];
+ if (by === void 0 || path === void 0) continue;
+ const list2 = out.get(by) ?? [];
+ if (!list2.includes(path)) list2.push(path);
+ out.set(by, list2);
+ }
+ return out;
+}
+__name(openedAfter, "openedAfter");
+var isCall = /* @__PURE__ */ __name((a) => a.kind === "repowise", "isCall");
+function callLines(state2, turn, v, theme2) {
+ const ctx = {
+ turn,
+ columns: v.columns,
+ active: isWorking(state2) ? inFlight(state2)?.id ?? null : null,
+ open: state2.open,
+ theme: theme2,
+ beforeEdit: answeredBeforeEdit(state2),
+ opened: openedAfter(state2)
+ };
+ const calls = turn.activities.filter(isCall).flatMap((a) => [callLine(a, ctx), ...detailLines(a, ctx)]);
+ const dropped = turn.dropped > 0 && calls.length > 0 ? [{ node: dimLine(` ${droppedSteps(turn.dropped)}`, v.columns) }] : [];
+ 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");
+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);
+ let start = 0;
+ 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);
+ let end = lines.length;
+ while (end > start + 1 && total(lines.slice(start, end)) > room - 2) end--;
+ const shown = new Set(lines.slice(start, end).map((l) => l.id));
+ const above = stepsOutside(lines.slice(0, start), shown);
+ const below2 = stepsOutside(lines.slice(end), shown);
+ const note = /* @__PURE__ */ __name((n, say) => n === 0 ? [] : [{ node: dimLine(say(n), Number.POSITIVE_INFINITY) }], "note");
+ return [...note(above, hiddenSteps), ...lines.slice(start, end), ...note(below2, laterSteps)];
+}
+__name(windowed, "windowed");
+function earlierTurns(state2, columns) {
+ const out = state2.turns.slice(0, -1).reverse().map((t) => dimLine(` ${turnFooter(t.seq, t.durationMs, turnTotals(t), t.end)}`, columns));
+ if (state2.earlier.turns > 0) out.push(dimLine(` ${earlierLine(state2.earlier)}`, columns));
+ 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)];
+ const turn = state2.turns.at(-1);
+ const fixed = turn === void 0 ? [] : dashboard(state2, turn, v, theme2);
+ const after = [...closing(turn, v.columns), ...earlierTurns(state2, v.columns), ...navRow(state2)];
+ 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]);
+}
+__name(flowView, "flowView");
+
+// src/flow-controller.ts
+var 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;
+ still = false;
+ io = null;
+ lastDraw = Number.NEGATIVE_INFINITY;
+ /** When the first redraw no Flow render has answered was asked for; null once one did. */
+ unansweredSince = null;
+ pending;
+ ticker;
+ happy;
+ setReducedMotion(on) {
+ this.still = on;
+ }
+ /** Another tab is shown, or the pane is gone: nothing of Flow is on screen. */
+ hide() {
+ this.shown = false;
+ this.stopTick();
+ }
+ dispatch(io, action) {
+ this.io = io;
+ const next = reduceFlow(this.state, action);
+ if (next === this.state) return;
+ this.state = next;
+ if (action.type === "turnEnded") this.afterTurn();
+ this.request();
+ }
+ /** The tab's tree at `now`; a render marks Flow on screen and keeps the owl's clock going while Claude works. */
+ paneTree(io, pane, now) {
+ this.io = io;
+ this.shown = true;
+ this.unansweredSince = null;
+ this.ensureTick();
+ return flowView(this.state, { ...pane, now, still: this.still });
+ }
+ dispose() {
+ this.hide();
+ clearTimeout(this.pending);
+ clearTimeout(this.happy);
+ this.pending = void 0;
+ this.happy = void 0;
+ this.io = null;
+ }
+ /** A redraw now, or once the throttle allows; nothing while Flow is not on screen. */
+ request() {
+ if (!this.shown || this.pending !== void 0) return;
+ const wait = this.lastDraw + REDRAW_MS - Date.now();
+ if (wait <= 0) return this.draw();
+ this.pending = setTimeout(() => this.timer(() => (this.pending = void 0, true)), wait);
+ }
+ /** A timer's body: its step says whether to redraw; a failure is logged, never thrown into the runtime. */
+ timer(step) {
+ try {
+ if (step()) this.draw();
+ } catch (err) {
+ this.io?.debug(`flow timer failed: ${String(err)}`);
+ }
+ }
+ /** Redraws, unless redraws have gone unanswered for a while: then the pane is gone and Flow stops asking. */
+ draw() {
+ const now = Date.now();
+ if (this.unansweredSince !== null && now - this.unansweredSince >= GONE_MS) return this.hide();
+ if (!this.shown || this.io === null) return;
+ this.lastDraw = now;
+ this.unansweredSince ??= now;
+ this.io.redraw();
+ }
+ /** The owl is happy for a moment, then sleeps: one redraw when that moment ends. */
+ afterTurn() {
+ this.stopTick();
+ clearTimeout(this.happy);
+ this.happy = setTimeout(() => this.timer(() => (this.happy = void 0, true)), HAPPY_MS);
+ }
+ ensureTick() {
+ if (this.ticker !== void 0 || !this.shown || !isWorking(this.state)) return;
+ this.ticker = setInterval(() => this.timer(() => this.tick()), this.still ? STILL_TICK_MS : BLINK_MS);
+ }
+ /** Redraw while Claude works; stop once it is done. Off screen, `draw` stops it. */
+ tick() {
+ if (isWorking(this.state)) return true;
+ this.stopTick();
+ return false;
+ }
+ stopTick() {
+ clearInterval(this.ticker);
+ this.ticker = void 0;
+ }
+};
+
+// src/model/events.ts
+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 .*)?\.$/;
+var FIXES = /^\[repowise\] .+? has been bug-fixed (\d+)x in the last 6 months, last (.+?)(?: \(bug magnet\))?(?:; mostly in (.+?))?\.$/;
+function stripConfirmed(line2) {
+ return line2.replace(/ \(confirmed across \d+ sessions\)\.$/, ".");
+}
+__name(stripConfirmed, "stripConfirmed");
+function notesFromAugment(additionalContext) {
+ if (!Array.isArray(additionalContext)) return [];
+ const notes = [];
+ const lines = additionalContext.filter((c) => typeof c === "string").flatMap((c) => c.split(/\r?\n/));
+ for (const raw of lines) {
+ const line2 = stripConfirmed(raw.trim());
+ const standing = STANDING.exec(line2);
+ const decision = standing ?? MINED.exec(line2);
+ const fixes = FIXES.exec(line2);
+ if (decision !== null && !notes.some((n) => n.kind === "decision")) {
+ notes.push({ kind: "decision", reviewed: standing !== null, title: decision[1] });
+ } else if (fixes !== null && !notes.some((n) => n.kind === "fixes")) {
+ notes.push({ kind: "fixes", count: Number(fixes[1]), age: fixes[2], symbol: fixes[3] ?? null });
}
}
+ return notes;
+}
+__name(notesFromAugment, "notesFromAugment");
+function savingsTotals(s) {
+ return {
+ tokens: s.saved_input_tokens,
+ inferredTokens: Math.min(s.inferred_saved_input_tokens, s.saved_input_tokens),
+ 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;
+ const usd = now.usd - base.usd;
+ 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) {
+ const absolute = ctx.isWindows ? /^[A-Za-z]:[\\/]|^\\\\/.test(raw) : raw.startsWith("/");
+ 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(paintPath, "paintPath");
-function paintHits(p, overlay, amount) {
- for (const i of overlay.hits) fillFile(p, p.layout.files[i], (c) => mix(c, ACCENT, amount));
+__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(paintHits, "paintHits");
-function paintReads(p, overlay) {
- for (const i of overlay.reads) {
- const f = p.layout.files[i];
- fillFile(p, f, (c) => mix(c, 0, READ_DIM));
- outlineFile(p, f, ACCENT);
- }
+__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(paintReads, "paintReads");
-function paintEdited(p, f) {
- fillFile(p, f, () => EDIT_TINT);
- if (!isSmall(f)) outlineFile(p, f, ACCENT);
+__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;
+ const base = cwd2 ?? repoRoot;
+ if (base === null) return raw;
+ const isWindows = /^[A-Za-z]:[\/]|^[\/]{2}/.test(base);
+ const abs = absolutePath(raw, { cwd: base, isWindows });
+ return (repoRoot === null ? null : relativeTo(abs, repoRoot, isWindows)) ?? abs;
}
-__name(paintEdited, "paintEdited");
-function paintRing(p, origin, reach) {
- const [ox, oy] = center(origin);
- const { width, height } = p.layout;
- for (let y = Math.max(0, Math.floor(oy - reach)); y <= Math.min(height - 1, oy + reach); y++) {
- for (let x = Math.max(0, Math.floor(ox - reach)); x <= Math.min(width - 1, ox + reach); x++) {
- const d = Math.hypot(x - ox, y - oy);
- if (d <= reach && d > reach - 2) set(p, x, y, mix(p.px[y * width + x] ?? GROUND, ACCENT, RING_AMOUNT));
- }
+__name(touchedPath, "touchedPath");
+
+// src/model/story.ts
+var NO_STORY = { searched: [], opened: [], edited: [] };
+var nameOf = /* @__PURE__ */ __name((path) => path.slice(path.lastIndexOf("/") + 1), "nameOf");
+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");
+function storyTurn(state2) {
+ for (let i = state2.turns.length - 1; i >= 0; i--) {
+ const t = state2.turns[i];
+ if (t.activities.some(isFileStep)) return t;
}
+ return null;
}
-__name(paintRing, "paintRing");
-function paintCallers(p, overlay, origin, reach) {
- for (const i of overlay.callers) {
- const f = p.layout.files[i];
- if (origin !== void 0 && distance(origin, f) > reach) continue;
- const [x, y] = center(f);
- set(p, x, y, ACCENT);
- set(p, x, y ^ 1, GROUND);
+__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) {
+ const path = a.paths[0];
+ if (!isOpen(a) || path === void 0 || seen.has(path)) continue;
+ seen.set(path, { name: nameOf(path), namedBy: a.namedBy?.tool ?? null });
}
+ return [...seen.values()];
}
-__name(paintCallers, "paintCallers");
-function matchAmount(anim) {
- return anim?.kind === "flash" ? MATCH_REST + (MATCH_FLASH - MATCH_REST) * (1 - anim.t) : MATCH_REST;
+__name(openedOf, "openedOf");
+function storyFromFlow(state2) {
+ const turn = storyTurn(state2);
+ if (turn === null) return NO_STORY;
+ const steps = turn.activities.filter(isFileStep);
+ return {
+ searched: steps.filter((a) => a.kind === "search").map((a) => ({ pattern: argOf(a, ["pattern", "query"]), hits: a.hits })),
+ opened: openedOf(steps),
+ edited: steps.filter((a) => a.kind === "edit" && a.paths[0] !== void 0).map((a) => ({ name: nameOf(a.paths[0]), lines: a.lines }))
+ };
}
-__name(matchAmount, "matchAmount");
-function rippleReach(layout, overlay, anim) {
- return anim?.kind === "ripple" && anim.t < 1 ? rippleRadius(layout, overlay) * anim.t : Infinity;
+__name(storyFromFlow, "storyFromFlow");
+function litFromFlow(state2) {
+ const turn = storyTurn(state2);
+ if (turn === null) return NO_LIT;
+ const mine = visits(state2).filter((v) => v.turn === turn.seq);
+ const opened = mine.filter((v) => v.kind !== "search-hit");
+ const edits = opened.filter((v) => v.kind === "edit");
+ return {
+ hits: mine.filter((v) => v.kind === "search-hit").map((v) => v.path),
+ reads: [...new Set(opened.map((v) => v.path))],
+ named: Object.entries(state2.named).filter(([, n]) => n.turn === turn.seq).map(([key]) => key),
+ importers: [],
+ edits: [...new Set(edits.map((v) => v.path))],
+ edit: edits.at(-1)?.path ?? null,
+ current: opened.at(-1)?.path ?? null
+ };
}
-__name(rippleReach, "rippleReach");
-function framePixels(layout, overlay, anim) {
- const p = { layout, px: layout.base.slice(), marked: new Uint8Array(layout.width * layout.height) };
- const origin = overlay.edited === null ? void 0 : layout.files[overlay.edited];
- const reach = rippleReach(layout, overlay, anim);
- paintPath(p, overlay);
- paintHits(p, overlay, matchAmount(anim));
- paintReads(p, overlay);
- if (origin !== void 0) paintEdited(p, origin);
- if (origin !== void 0 && reach < Infinity) paintRing(p, origin, reach);
- paintCallers(p, overlay, origin, reach);
- return { pixels: p.px, marked: p.marked };
+__name(litFromFlow, "litFromFlow");
+var rel = /* @__PURE__ */ __name((abs, root, ci) => relativeTo(abs, root, ci), "rel");
+function litFromTrail(trail, root, caseInsensitive) {
+ const all = /* @__PURE__ */ __name((paths) => paths.map((p) => rel(p, root, caseInsensitive)).filter((p) => p !== null), "all");
+ 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(framePixels, "framePixels");
-function frameCells(layout, overlay, anim) {
- const { pixels, marked } = framePixels(layout, overlay, anim);
- return encodeCells(layout, pixels, marked);
+__name(litFromTrail, "litFromTrail");
+function storyFromTrail(trail) {
+ return {
+ searched: trail.searches === 0 ? [] : [{ pattern: "", hits: trail.hits.length }],
+ opened: trail.reads.map((p) => ({ name: nameOf(p), namedBy: null })),
+ edited: trail.edit === null ? [] : [{ name: nameOf(trail.edit), lines: null }]
+ };
}
-__name(frameCells, "frameCells");
-var FRAME_MS = 40;
-var FLASH_MS = 600;
-var RIPPLE_MS = 1200;
+__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);
+ const callers = combineCallers(answers, new Set(lit.edits.map((p) => p.toLowerCase())));
+ if (callers === null) return { lit, reach: null };
+ 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/views/mapPane.ts
-var MAP_KEY = "lens-map";
-var MAX_COLUMNS = 512;
-var MAX_ROWS = 256;
-var MIN_ROWS = 4;
-var GAP = 2;
-var SEP = " · ";
-var FACT_ROWS = 4;
-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 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 }
-];
-var READ = { glyph: "□", color: BRAND.accent, label: MAP_COPY.read };
-var EDITED = { glyph: "◆", color: hexOf(EDIT_TINT), label: MAP_COPY.edited };
-var IMPORTER = { glyph: "·", color: BRAND.accent, label: MAP_COPY.importer };
-var MATCH = { glyph: "▪", color: BRAND.accent, label: MAP_COPY.match };
-function packRows(items, width, columns, gap) {
- const rows = [];
- let used = Infinity;
- for (const item of items) {
- const w = width(item);
- const last = rows[rows.length - 1];
- if (last === void 0 || used + gap + w > columns) {
- rows.push([item]);
- used = w;
- } else {
- last.push(item);
- used += gap + w;
- }
- }
- return rows;
-}
-__name(packRows, "packRows");
-var swatchWidth = /* @__PURE__ */ __name((s) => s.label.length + 2, "swatchWidth");
-function legendRows(columns) {
- const swatchRows2 = /* @__PURE__ */ __name((items) => packRows(items, swatchWidth, columns, GAP).length, "swatchRows");
- return swatchRows2(BAND_SWATCHES) + swatchRows2([READ, EDITED, IMPORTER, MATCH]) + FACT_ROWS;
-}
-__name(legendRows, "legendRows");
-function mapSize(pane) {
- const columns = Math.max(1, Math.min(MAX_COLUMNS, pane.bodyColumns));
- const wanted = pane.placement === "dock" ? pane.bodyRows - legendRows(columns) : 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(
- (row) => box(
- { flexDirection: "row", columnGap: GAP },
- row.map((s) => box({ flexDirection: "row" }, [text(s.glyph, { color: s.color }), text(` ${s.label}`, { dimColor: true })]))
- )
+// ../api-client/src/blast-radius.ts
+async function analyzeBlastRadius(repoId, body) {
+ return apiPost(
+ `/api/repos/${repoId}/blast-radius`,
+ body
);
}
-__name(swatchRows, "swatchRows");
-function marksOf(resolved) {
- const marks = [READ, EDITED];
- if (resolved.overlay.callers.length > 0) marks.push(IMPORTER);
- if (resolved.overlay.hits.length > 0) marks.push(MATCH);
- return marks;
-}
-__name(marksOf, "marksOf");
-function scopeRows(scope, columns) {
- const rows = /* @__PURE__ */ __name((parts2) => packRows(parts2, (p) => p.length, columns, SEP.length), "rows");
- let parts = scopeParts(scope);
- for (const optional of [SCOPE_REST, scope.indexed === null ? null : indexedPart(scope.indexed)]) {
- if (rows(parts).length <= 2) break;
- parts = parts.filter((p) => p !== optional);
- }
- return rows(parts).slice(0, 2).map((row) => row.join(SEP));
-}
-__name(scopeRows, "scopeRows");
-function factRows(resolved, scope, columns) {
- const facts = [];
- const reads = readsLine(resolved.reads, resolved.matched, columns);
- if (reads !== null) facts.push(reads);
- if (resolved.edit !== null) facts.push(callersLine(resolved.edit.name, resolved.edit.callers, resolved.edit.notDrawn, columns));
- return [...facts, ...scopeRows(scope, columns)];
-}
-__name(factRows, "factRows");
-function legendView(resolved, scope, columns) {
- return [
- ...swatchRows(BAND_SWATCHES, columns),
- ...swatchRows(marksOf(resolved), columns),
- ...factRows(resolved, scope, columns).map((f) => text(fit(f, columns), { dimColor: true, wrap: "truncate-end" }))
- ];
+__name(analyzeBlastRadius, "analyzeBlastRadius");
+
+// ../api-client/src/code-health.ts
+async function getHealthMap(repoId, opts = {}) {
+ return apiGet(`/api/repos/${repoId}/health/map`, {
+ cap: opts.cap,
+ active: opts.active?.length ? opts.active.join(",") : void 0,
+ scope: opts.scope,
+ counts: opts.counts
+ });
}
-__name(legendView, "legendView");
-function mapPaneView(layout, cells, resolved, scope) {
- return box({ key: "lens-map-pane", flexDirection: "column" }, [
- raster({ key: MAP_KEY, columns: layout.columns, rows: layout.rows, cells }),
- ...legendView(resolved, scope, layout.columns)
- ]);
+__name(getHealthMap, "getHealthMap");
+
+// src/model/trail.ts
+var MAX_READS = 200;
+var initialTrail = {
+ reads: [],
+ readsCapped: false,
+ hits: [],
+ searches: 0,
+ edit: null,
+ edits: 0,
+ callers: null
+};
+function withRead(state2, path) {
+ if (state2.reads.includes(path)) return state2;
+ const reads = [...state2.reads, path];
+ if (reads.length <= MAX_READS) return { ...state2, reads };
+ return { ...state2, reads: reads.slice(reads.length - MAX_READS), readsCapped: true };
}
-__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(withRead, "withRead");
+function reduceTrail(state2, action) {
+ switch (action.type) {
+ case "read":
+ return withRead(state2, action.path);
+ case "search":
+ return { ...state2, hits: action.paths, searches: state2.searches + 1 };
+ case "edit":
+ return {
+ ...withRead(state2, action.path),
+ edit: action.path,
+ edits: state2.edits + 1,
+ callers: { status: "loading" }
+ };
+ case "callers":
+ return action.edits === state2.edits ? { ...state2, callers: action.callers } : state2;
+ }
}
-__name(noticeView, "noticeView");
+__name(reduceTrail, "reduceTrail");
// src/views/mapSvg.ts
var SVG_CHARS = 131072;
@@ -1947,15 +3538,23 @@ function desktopSize(size) {
return { columns: Math.min(DESKTOP_MAX_COLUMNS, size.columns), rows: Math.min(DESKTOP_MAX_ROWS, size.rows) };
}
__name(desktopSize, "desktopSize");
-function mapSvg(layout, resolved) {
- const { width, height } = layout;
- const { pixels } = framePixels(layout, resolved.overlay);
+var textAt = /* @__PURE__ */ __name((l, fill) => `<text x="${l.col}" y="${2 * l.row + 1.6}" fill="${color(fill)}">${escape(l.text)}</text>`, "textAt");
+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);
const runs = /* @__PURE__ */ new Map();
for (let y = 0; y < height; y++) {
- for (let x = 0; x < width; ) {
- const c = pixels[y * width + x] ?? GROUND;
+ for (let x = 0; x < width2; ) {
+ const c = pixels[y * width2 + x] ?? GROUND;
let end = x + 1;
- while (end < width && pixels[y * width + end] === c) end++;
+ while (end < width2 && pixels[y * width2 + end] === c) end++;
if (c !== GROUND) {
const list2 = runs.get(c) ?? [];
list2.push(`M${x} ${y}.5h${end - x}`);
@@ -1965,14 +3564,13 @@ function mapSvg(layout, resolved) {
}
}
const paths = [...runs].map(([c, d]) => `<path stroke="${color(c)}" d="${d.join("")}"/>`).join("");
- const labels = layout.labels.map((l) => `<text x="${l.col}" y="${2 * l.row + 1.6}">${escape(l.text)}</text>`).join("");
- return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" shape-rendering="crispEdges"><rect width="${width}" height="${height}" fill="${color(GROUND)}"/><g stroke-width="1" fill="none">${paths}</g><g font-family="monospace" font-size="1.7" fill="${color(LABEL_FG)}">${labels}</g></svg>`;
+ 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, resolved, scope) {
- const source = mapSvg(layout, resolved);
+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(resolved, scope, layout.columns)]);
+ return box({ key: "lens-map-pane", flexDirection: "column" }, [picture, ...legendView(parts, layout.style, layout.columns)]);
}
__name(svgPaneView, "svgPaneView");
@@ -1981,63 +3579,21 @@ var MAP_CAP = 4e3;
var MAP_TIMEOUT_MS = 15e3;
var CALLERS_TIMEOUT_MS = 2e4;
var CALLERS_DEPTH = 1;
-function scopeFacts(layout, data, repo) {
+var NO_TURN = /* @__PURE__ */ __name(() => ({ lit: NO_LIT, story: NO_STORY }), "NO_TURN");
+function scopeFacts(layout, data, repo, offMap) {
return {
drawn: layout.drawn.length,
+ shown: data.files.length,
repositoryTotal: data.repository_total,
indexed: formatRelativeTimeOrNull(repo.updatedAt, "") || null,
beyondCap: data.omitted.files,
- cap: data.cap
+ dense: layout.dense,
+ notOnMap: offMap
};
}
__name(scopeFacts, "scopeFacts");
-var Animator = class {
- static {
- __name(this, "Animator");
- }
- anim = null;
- timer;
- blitting = false;
- stopped = false;
- progress(now) {
- const a = this.anim;
- return a === null ? void 0 : { kind: a.kind, t: Math.min(1, (now - a.start) / a.duration) };
- }
- play(io, kind, screen) {
- this.stop();
- if (this.stopped) return;
- this.anim = { kind, start: Date.now(), duration: kind === "flash" ? FLASH_MS : RIPPLE_MS };
- io.redraw();
- this.timer = setInterval(() => this.tick(io, screen), FRAME_MS);
- }
- stop() {
- clearInterval(this.timer);
- this.timer = void 0;
- this.anim = null;
- }
- /** For good: a disposed map plays nothing more. */
- end() {
- this.stopped = true;
- this.stop();
- }
- tick(io, screen) {
- const step = this.progress(Date.now());
- const frame = step === void 0 ? null : screen(step);
- if (step === void 0 || frame === null) return this.stop();
- if (this.blitting) return;
- if (step.t >= 1) this.stop();
- this.blitting = true;
- io.blit(frame.cells, frame.columns, frame.rows).then((r) => r.deny === void 0 || this.refused(io, r.deny)).catch((err) => this.refused(io, String(err))).finally(() => {
- this.blitting = false;
- });
- }
- /** Resized, closed or refused under the animation: stop and let a redraw show the resting frame. */
- refused(io, why) {
- io.debug(`blit refused: ${why}`);
- this.stop();
- if (!this.stopped) io.redraw();
- }
-};
+var keyParts = /* @__PURE__ */ __name((k) => [k.data, k.columns, k.rows, k.style.theme, k.style.health], "keyParts");
+var sameKey = /* @__PURE__ */ __name((a, b) => keyParts(a).every((v, i) => v === keyParts(b)[i]), "sameKey");
var LensMap = class {
static {
__name(this, "LensMap");
@@ -2050,17 +3606,46 @@ var LensMap = class {
feed = { status: "idle" };
requested = false;
autoOpenTried = false;
- /** The latest edit's absolute path with its case, for the importers request. */
+ /** The latest edit's absolute path with its case. */
editPath = null;
- /** The edit whose importers were asked for, so each is asked once. */
- callersAsked = 0;
+ /**
+ * Every file edited this session (absolute, case kept), and the importers
+ * of each, asked once per distinct path. Ceiling: never asked again, so an
+ * index update mid-session is not seen; nothing tells Lens it changed.
+ */
+ edited = /* @__PURE__ */ new Set();
+ importers = /* @__PURE__ */ new Map();
drawn = null;
layoutCache = null;
- animator = new Animator();
reducedMotion = false;
+ /** Health colours on the tiles: off by default (`lens_map_health`), toggled from the pane. */
+ health;
+ /** Read at every frame, so an animation sees the turn as it is now. */
+ turn;
autoOpenOnRead;
- constructor(autoOpenOnRead) {
+ /** The pane's one animator, shared with the trail: whichever tab is shown drives it. */
+ animator;
+ constructor(autoOpenOnRead, animator2 = new Animator(), health2 = false, turn = NO_TURN) {
this.autoOpenOnRead = autoOpenOnRead;
+ this.animator = animator2;
+ this.health = health2;
+ this.turn = turn;
+ }
+ /** The importers of a repo-relative path, as far as they are known; null when never asked. */
+ importersOf(path) {
+ return this.importers.get(this.keyOf(path)) ?? null;
+ }
+ keyOf(rel2) {
+ return this.repo?.caseInsensitive === false ? rel2 : rel2.toLowerCase();
+ }
+ /** The pane's toggle: health colours on the tiles, or the quiet ghost map. */
+ toggleHealth(io) {
+ this.health = !this.health;
+ io.redraw();
+ }
+ /** What the turn lit, with the latest edit's importers joined as they stand now. */
+ lighting() {
+ return withImporters(this.turn().lit, (p) => this.importersOf(p));
}
/** The band row the map wants shown, if any. */
bandLine() {
@@ -2074,12 +3659,25 @@ var LensMap = class {
this.disposed = true;
this.animator.end();
}
+ /**
+ * A `/clear`: the conversation's trail and edits go, so nothing of it stays
+ * lit. The feed, the repo and the importers already asked for (index data,
+ * by path) stay, and so does an open pane.
+ */
+ clearConversation(io) {
+ this.trail = initialTrail;
+ this.edited.clear();
+ this.editPath = null;
+ this.band = null;
+ io.redraw();
+ }
setRepo(io, repo) {
this.repo = repo;
this.fetchWanted(io);
}
/** One observed tool call; `editPath` is the edited file's absolute path, case kept. */
observe(io, action, editPath) {
+ if (action.type === "edit" && editPath !== null) this.edited.add(editPath);
if (action.type === "edit") this.editPath = editPath;
this.apply(io, action);
if (action.type === "edit") this.fetchWanted(io);
@@ -2106,17 +3704,20 @@ var LensMap = class {
/** The pane's tree; starts the feed fetch when the map is wanted and not yet asked for. */
paneTree(io, pane) {
this.drawn = null;
- const notice = this.noticeFor(io, pane);
- if (notice !== null) return noticeView(notice, pane.bodyColumns);
+ const notice2 = this.noticeFor(io, pane);
+ if (notice2 !== null) return noticeView(notice2, pane.bodyColumns);
const { data } = this.feed;
const repo = this.repo;
const desktop = pane.surface === "desktop";
- const layout = this.layoutFor(data, desktop ? desktopSize(mapSize(pane)) : mapSize(pane), repo.caseInsensitive);
- const resolved = resolveOverlay(layout, this.trail, repo.root);
- const scope = scopeFacts(layout, data, repo);
- if (desktop) return svgPaneView(layout, resolved, scope);
+ const style = { theme: pane.theme, health: this.health };
+ const size = mapSize(pane, this.health);
+ const layout = this.layoutFor({ data, ...desktop ? desktopSize(size) : size, style }, repo.caseInsensitive);
+ const { lit, reach } = this.lighting();
+ const overlay = resolveLit(layout, lit);
+ const parts = { story: this.turn().story, reach, scope: scopeFacts(layout, data, repo, notOnMap(layout, lit)) };
+ if (desktop) return svgPaneView(layout, overlay, parts);
this.drawn = { layout, root: repo.root };
- return mapPaneView(layout, frameCells(layout, resolved.overlay, this.animator.progress(Date.now())), resolved, scope);
+ return mapPaneView(layout, frameCells(layout, overlay, mapStep(this.animator.progress(Date.now()))), parts);
}
/** Why there is no map to draw yet (and the feed fetch started when wanted), or null once it can be drawn. */
noticeFor(io, pane) {
@@ -2128,17 +3729,13 @@ var LensMap = class {
if (status === "ready") return null;
return status === "failed" ? MAP_COPY.failed : MAP_COPY.loading;
}
- layoutFor(data, size, caseInsensitive) {
- const cached = this.cachedLayout(data, size);
- if (cached !== null) return cached;
- const layout = layoutMap(data.files, size.columns, size.rows, caseInsensitive);
- this.layoutCache = { data, columns: size.columns, rows: size.rows, layout };
- return layout;
- }
- cachedLayout(data, size) {
+ /** The layout for this feed, size and style; laid out again only when one of them changed. */
+ layoutFor(key, caseInsensitive) {
const c = this.layoutCache;
- const same = c !== null && c.data === data && c.columns === size.columns && c.rows === size.rows;
- return same ? c.layout : null;
+ if (c !== null && sameKey(c.key, key)) return c.layout;
+ const layout = layoutMap(key.data.files, { columns: key.columns, rows: key.rows, caseInsensitive, style: key.style });
+ this.layoutCache = { key, layout };
+ return layout;
}
apply(io, action) {
const next = reduceTrail(this.trail, action);
@@ -2148,11 +3745,11 @@ var LensMap = class {
else if (action.type === "callers" && action.callers.status === "ready") this.animate(io, "ripple");
else io.redraw();
}
- /** The feed and the latest edit's importers, once the map is wanted and the repo known. */
+ /** The feed and the importers of every edited file not yet asked for, once the map is wanted and the repo known. */
fetchWanted(io) {
if (!this.requested || this.repo === null) return;
this.loadFeed(io, this.repo);
- this.loadCallers(io, this.repo);
+ for (const path of this.edited) this.loadCallers(io, this.repo, path);
}
loadFeed(io, repo) {
if (this.feed.status !== "idle") return;
@@ -2166,21 +3763,30 @@ var LensMap = class {
if (!this.disposed) io.redraw();
});
}
- loadCallers(io, repo) {
- const edits = this.trail.edits;
- if (this.editPath === null || this.callersAsked === edits) return;
- this.callersAsked = edits;
- const rel = relativeTo(this.editPath, repo.root, repo.caseInsensitive);
- if (rel === null) return this.apply(io, { type: "callers", edits, callers: { status: "failed" } });
- const request = { changed_files: [rel], max_depth: CALLERS_DEPTH };
+ /** One edited file's importers, asked once; the answer is kept by path. */
+ loadCallers(io, repo, abs) {
+ const rel2 = relativeTo(abs, repo.root, repo.caseInsensitive);
+ const key = rel2 === null ? null : this.keyOf(rel2);
+ if (rel2 === null || key === null || this.importers.has(key)) return;
+ this.importers.set(key, { status: "loading" });
+ const request = { changed_files: [rel2], max_depth: CALLERS_DEPTH };
withTimeout(analyzeBlastRadius(repo.id, request), CALLERS_TIMEOUT_MS, "importers").then((r) => {
- const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel);
- if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "ready", paths } });
+ const paths = [...new Set(r.transitive_affected.map((t) => t.path))].filter((p) => p !== rel2);
+ if (this.disposed) return;
+ this.landed(io, abs, { status: "ready", paths });
+ io.blastLanded?.(rel2, r);
}).catch((err) => {
io.debug(`importers failed: ${String(err)}`);
- if (!this.disposed) this.apply(io, { type: "callers", edits, callers: { status: "failed" } });
+ if (!this.disposed) this.landed(io, abs, { status: "failed" });
});
}
+ /** An answer for one edited file: kept by path; for the latest edit, also the trail's (which ripples). */
+ landed(io, abs, callers) {
+ const rel2 = this.repo === null ? null : relativeTo(abs, this.repo.root, this.repo.caseInsensitive);
+ if (rel2 !== null) this.importers.set(this.keyOf(rel2), callers);
+ if (abs === this.editPath) this.apply(io, { type: "callers", edits: this.trail.edits, callers });
+ else io.redraw();
+ }
/** The first read opens the map when the toggle is on and the pane would be placed; never forced. */
async autoOpen(io) {
if (!this.mayAutoOpen()) return;
@@ -2204,24 +3810,32 @@ var LensMap = class {
canAnimate(kind) {
const on = this.drawn;
if (this.reducedMotion || on === null) return false;
- return kind === "flash" || rippleRadius(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay) > 0;
+ return kind === "flash" || rippleRadius(on.layout, resolveLit(on.layout, this.lighting().lit)) > 0;
}
- /** A flash or a ripple when it would show; otherwise (reduced motion, nothing on screen) the resting frame. */
+ /**
+ * A flash or a ripple when it would show; otherwise (reduced motion, nothing
+ * on screen) the resting frame, leaving another tab's animation playing.
+ */
animate(io, kind) {
- this.animator.stop();
if (!this.canAnimate(kind)) return io.redraw();
- this.animator.play(io, kind, (step) => this.frame(step));
+ this.animator.play(io, kind, kind === "flash" ? FLASH_MS : RIPPLE_MS, (step) => this.frame(step));
}
/** The current trail on the drawn map at one step, or null once the map is off screen. */
frame(step) {
const on = this.drawn;
- if (on === null) return null;
- const cells = frameCells(on.layout, resolveOverlay(on.layout, this.trail, on.root).overlay, step);
- return { cells, columns: on.layout.columns, rows: on.layout.rows };
+ const anim = mapStep(step);
+ if (on === null || anim === void 0) return null;
+ const cells = frameCells(on.layout, resolveLit(on.layout, this.lighting().lit), anim);
+ return { key: MAP_KEY, cells, columns: on.layout.columns, rows: on.layout.rows };
}
};
+function mapStep(step) {
+ return step !== void 0 && (step.kind === "flash" || step.kind === "ripple") ? step : void 0;
+}
+__name(mapStep, "mapStep");
// src/model/ask.ts
+var 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 } };
}
@@ -2235,18 +3849,13 @@ function mayHaveUsedModel(a) {
return a.tool === "get_answer" && a.reply.degraded !== "no-llm-provider";
}
__name(mayHaveUsedModel, "mayHaveUsedModel");
-function lensCommand(args) {
+function lensCommand(args, tabs = TAB_BAR) {
const [word = "", ...rest] = args.trim().split(/\s+/);
const question = rest.join(" ");
- switch (word.toLowerCase()) {
- case "map":
- case "recap":
- return { tab: word.toLowerCase(), question: null };
- case "ask":
- return { tab: "ask", question: question === "" ? null : question };
- default:
- return { tab: null, question: null };
- }
+ const named2 = word.toLowerCase();
+ if (named2 === "ask") return { tab: "ask", question: question === "" ? null : question };
+ const tab = tabs.find((t) => t === named2);
+ return { tab: tab ?? null, question: null };
}
__name(lensCommand, "lensCommand");
function whyDraft(decision) {
@@ -2327,7 +3936,7 @@ var initialSession = {
review: initialReview,
lastReview: null,
touched: [],
- pane: { tab: "map", draft: "" },
+ pane: { tab: "flow", draft: "" },
ask: { phase: "idle" },
modelAsks: 0,
compacted: false
@@ -2338,6 +3947,11 @@ function hintFor(mode, liteReason) {
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": {
@@ -2459,10 +4073,10 @@ function isClear(risk) {
return risk.directive?.status === "clear_in_analyzed_scope";
}
__name(isClear, "isClear");
-function header(risk, changed) {
+function header2(risk, changed) {
return `Change review (${reviewScope(risk.ref ?? "working tree", risk.working_tree !== false, changed)})`;
}
-__name(header, "header");
+__name(header2, "header");
function findingSegments(hd) {
const rows = hd?.top_findings ?? [];
const segments = rows.map(findingLine);
@@ -2487,10 +4101,10 @@ function overlapSegments(risk) {
}
__name(overlapSegments, "overlapSegments");
function cardSegments(risk) {
- if (isClear(risk) && overlap(risk) === null) return [header(risk, null), `health: ${health(risk).words}`];
+ if (isClear(risk) && overlap(risk) === null) return [header2(risk, null), `health: ${health(risk).words}`];
const hd = risk.health_delta;
return [
- header(risk, hd?.scope?.changed ?? null),
+ header2(risk, hd?.scope?.changed ?? null),
`Health: ${health(risk).words}`,
...findingSegments(hd),
...scopeSegments(hd),
@@ -2649,7 +4263,7 @@ function bandView(state2, viewport, extra = []) {
const actions = [review, briefBandRow(state2, viewport.columns, review !== null)].filter((n) => n !== null);
const own = [...bandRows(state2, viewport.columns), ...extra].slice(0, Math.max(0, MAX_BAND_ROWS - actions.length));
if (own.length === 0 && actions.length === 0) return null;
- const nodes = own.map((row) => text(fit(row, viewport.columns), { dimColor: true, wrap: "truncate-end" }));
+ 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");
@@ -2675,11 +4289,11 @@ function ids(refs) {
return found.length === 0 ? "" : ` · ${found.map(code).join(" ")}`;
}
__name(ids, "ids");
-function list(head, rows, row, total) {
+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(total ?? 0, rows.length) - shown.length;
- return [`**${head}**`, ...shown.map((r) => `- ${row(r)}`), ...more > 0 ? [`- ${moreRows(more)}`] : []];
+ 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) {
@@ -2728,14 +4342,17 @@ _${askCut(ASK_CHARS)}_`;
__name(replyMarkdown, "replyMarkdown");
// src/views/pane.ts
-var TABS = ["map", "ask", "recap"];
-var TAB_PRESS = { map: "lens-tab-map", ask: "lens-tab-ask", recap: "lens-tab-recap" };
+function 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 ASK_KEY = "lens-ask";
var TAB_ROWS = 1;
-function tabsView(current) {
+function tabsView(current, tabs = TAB_BAR) {
return box(
{ key: "lens-tabs", flexDirection: "row", columnGap: 2 },
- TABS.map((tab, i) => button(TAB_PRESS[tab], String(i + 1), PANE_COPY.tabs[tab], tab !== current))
+ tabs.map((tab, i) => button(tabPress(tab), String(i + 1), PANE_COPY.tabs[tab], tab !== current))
);
}
__name(tabsView, "tabsView");
@@ -2808,18 +4425,18 @@ function recapRows(state2, touched) {
__name(recapRows, "recapRows");
function recapView(state2, touched, columns) {
const rows = recapRows(state2, touched);
- const width = Math.max(...rows.map((r) => typeof r === "string" ? 0 : r[0].length)) + 2;
+ const width2 = Math.max(...rows.map((r) => typeof r === "string" ? 0 : r[0].length)) + 2;
const drawn = rows.map(
(r) => typeof r === "string" ? dim(r, columns) : box({ flexDirection: "row" }, [
- text(r[0].padEnd(width), { dimColor: true }),
- text(fit(r[1], Math.max(1, columns - width)), { wrap: "truncate-end" })
+ text(r[0].padEnd(width2), { dimColor: true }),
+ text(fit(r[1], Math.max(1, columns - width2)), { wrap: "truncate-end" })
])
);
return box({ key: "lens-recap", flexDirection: "column" }, [...drawn, dim(recapFooter(state2.modelAsks), columns)]);
}
__name(recapView, "recapView");
-function paneView(tab, body) {
- return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab), body]);
+function paneView(tab, body, tabs = TAB_BAR) {
+ return box({ key: "lens-pane", flexDirection: "column" }, [tabsView(tab, tabs), body]);
}
__name(paneView, "paneView");
@@ -2926,6 +4543,13 @@ var MCP_SERVER_KEY = "repowise";
var PANE_ID = "lens";
var PANE_ROWS = 29;
var ASK_TIMEOUT_MS = 3e4;
+var flowOn = true;
+var flow = new LensFlow();
+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;
@@ -2940,11 +4564,13 @@ var contextAsked = /* @__PURE__ */ new Set();
var reviewOn = true;
var reviewGeneration = 0;
var editsThisTurn = 0;
-var started = null;
+var started2 = null;
var autoOpenOn = false;
+var healthOn = false;
var discovery = null;
var cwd = null;
var map = new LensMap(false);
+var animator = new Animator();
var ERROR_CELLS = 160;
function bind($) {
const host = {
@@ -2972,17 +4598,22 @@ function bind($) {
call: /* @__PURE__ */ __name((server, tool, args) => $.mcp.call(server, tool, args), "call")
}
};
- return {
+ 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((cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key: MAP_KEY, cells, columns, rows }), "blit"),
+ blit: /* @__PURE__ */ __name((key, cells, columns, rows) => $.ui.blit({ requestId: PANE_ID, key, cells, columns, rows }), "blit"),
// Focus only when asked (/lens, a press): an automatic open leaves the prompt the keyboard.
- openPane: /* @__PURE__ */ __name((focus) => $.ui.open(
+ // 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(
focus ? { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS, focus: true } : { id: PANE_ID, title: MAP_COPY.title, rows: PANE_ROWS }
- ), "openPane"),
+ )), "openPane"),
closePane: /* @__PURE__ */ __name(() => $.ui.close({ id: PANE_ID }), "closePane")
};
+ animator.use(bound);
+ return bound;
}
__name(bind, "bind");
function mapRepo(d) {
@@ -3050,11 +4681,15 @@ async function onSessionStart($, e, next) {
generation++;
cwd = typeof e.cwd === "string" ? e.cwd : null;
map.dispose();
- map = new LensMap(autoOpenOn);
- state = initialSession;
+ animator.end();
+ animator = new Animator();
+ map = new LensMap(autoOpenOn, animator, healthOn, mapTurn);
+ flow.dispose();
+ flow = new LensFlow();
+ state = freshSession();
reviewGeneration++;
editsThisTurn = 0;
- started = null;
+ started2 = null;
contextAsked.clear();
squeezes.clear();
savingsBase = null;
@@ -3063,7 +4698,10 @@ async function onSessionStart($, e, next) {
warmMcp(b.host);
refresh(b);
await $.command.register({ name: "lens", description: PANE_COPY.command, argumentHint: PANE_COPY.argumentHint, immediate: true });
- map.setReducedMotion((await $.settings.read())["prefersReducedMotion"] === true);
+ readTheme($);
+ reducedMotion = (await $.settings.read())["prefersReducedMotion"] === true;
+ map.setReducedMotion(reducedMotion);
+ flow.setReducedMotion(reducedMotion);
} catch (err) {
b.debug(`session.start failed: ${String(err)}`);
}
@@ -3081,6 +4719,7 @@ function noteTurnEnd(b, e) {
try {
const action = fromTurnComplete(e);
if (action === null) return;
+ noteFlow(b, () => ({ type: "turnEnded", at: Date.now(), durationMs: e.durationMs ?? null, end: turnEnd(e.reason, e.isAborted) }));
map.turnEnded();
dispatch(b, action);
refresh(b);
@@ -3115,19 +4754,19 @@ function startReview(b) {
void review.outcome.then(() => {
review.settled = true;
});
- started = review;
+ started2 = review;
return review;
}
__name(startReview, "startReview");
function reviewAfterEdit(b) {
editsThisTurn++;
dispatch(b, { type: "fileEdited" });
- if (started !== null && started.gen === reviewGeneration && !started.settled) return;
+ if (started2 !== null && started2.gen === reviewGeneration && !started2.settled) return;
startReview(b);
}
__name(reviewAfterEdit, "reviewAfterEdit");
function coveringReview() {
- const s = started;
+ const s = started2;
return s !== null && s.gen === reviewGeneration && s.covers === editsThisTurn ? s : null;
}
__name(coveringReview, "coveringReview");
@@ -3148,11 +4787,12 @@ async function finishReview(b) {
}
__name(finishReview, "finishReview");
async function onTurnStart($, e, next) {
+ noteFlow(bind($), () => ({ type: "turnStarted", turnId: e.turnId ?? null, prompt: e.text ?? "", at: Date.now() }));
try {
if (reviewOn) {
reviewGeneration++;
editsThisTurn = 0;
- started = null;
+ started2 = null;
}
dispatch(bind($), reviewOn ? { type: "turnStarted" } : { type: "briefDone" });
} catch (err) {
@@ -3195,6 +4835,29 @@ function pressBrief($) {
}
}
__name(pressBrief, "pressBrief");
+async function onSessionEnd($, e, next) {
+ if (e.reason !== "clear") return next(e);
+ const b = bind($);
+ try {
+ animator.end();
+ flow.dispose();
+ flow = new LensFlow();
+ flow.setReducedMotion(reducedMotion);
+ map.clearConversation(b);
+ state = clearedConversation(state);
+ reviewGeneration++;
+ editsThisTurn = 0;
+ started2 = null;
+ squeezes.clear();
+ savingsBase = null;
+ savingsAskedAt = Number.NEGATIVE_INFINITY;
+ b.redraw();
+ } catch (err) {
+ b.debug(`clear failed: ${String(err)}`);
+ }
+ return next(e);
+}
+__name(onSessionEnd, "onSessionEnd");
async function onPostCompact($, e, next) {
try {
dispatch(bind($), { type: "compacted" });
@@ -3212,11 +4875,14 @@ function startAsk(b, question) {
dispatch(b, { type: "asked", question: q, tool });
const gen = generation;
callTool(b.host, tool, args, { timeoutMs: ASK_TIMEOUT_MS }).then((reply) => {
- if (gen === generation) dispatch(b, { type: "answered", question: q, answer: askReply(tool, reply) });
+ if (gen !== generation) return;
+ const answer = askReply(tool, reply);
+ dispatch(b, { type: "answered", question: q, answer });
}).catch((err) => {
b.debug(`ask failed: ${String(err)}`);
const message = fit((err instanceof Error ? err.message : String(err)).split("\n")[0] ?? "", ERROR_CELLS);
- if (gen === generation) dispatch(b, { type: "askFailed", question: q, tool, message });
+ if (gen !== generation) return;
+ dispatch(b, { type: "askFailed", question: q, tool, message });
});
}
__name(startAsk, "startAsk");
@@ -3231,7 +4897,7 @@ async function onAskInput($, e, next) {
__name(onAskInput, "onAskInput");
function pressDetails($) {
try {
- for (const row of directiveRows(state.review.outcome) ?? []) $.ui.log(row, { to: "transcript" });
+ for (const row2 of directiveRows(state.review.outcome) ?? []) $.ui.log(row2, { to: "transcript" });
} catch (err) {
bind($).debug(`details failed: ${String(err)}`);
}
@@ -3276,17 +4942,53 @@ __name(fetchContext, "fetchContext");
async function onToolCall($, e, next) {
const b = bind($);
const file = fileToolStarted(b, e);
- let result;
+ noteFlow(b, () => {
+ const activity = activityOf(e, Date.now(), flowRoot());
+ return activity === null ? null : { type: "toolStarted", activity };
+ });
+ let result = null;
try {
result = await next(e);
} finally {
if (file !== null) dispatch(b, { type: "toolEnded", id: e.tool_use_id });
+ noteFlow(b, () => toolEnded(e, result, Date.now(), flowRoot()));
}
editLanded(b, e, result);
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 {
+ const a = action();
+ if (a !== null) flow.dispatch(b, a);
+ } catch (err) {
+ flowFailed(b, err);
+ }
+}
+__name(noteFlow, "noteFlow");
+function flowFailed(b, err) {
+ try {
+ b.debug(`flow failed: ${String(err)}`);
+ } catch {
+ flowOn = false;
+ }
+}
+__name(flowFailed, "flowFailed");
function observeTrail($, b, e, result) {
if (!OBSERVED_TOOLS.has(e.tool)) return;
try {
@@ -3409,7 +5111,8 @@ __name(onToolUse, "onToolUse");
async function onLensCommand($, e) {
const b = bind($);
try {
- const asked = lensCommand(e.args ?? "");
+ readTheme($);
+ const asked = lensCommand(e.args ?? "", tabBar(flowOn));
if (asked.tab !== null) dispatch(b, { type: "tab", tab: asked.tab });
if (discovery === null || mapRepo(discovery) === null) refresh(b);
await map.request(b);
@@ -3423,6 +5126,18 @@ 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(([key, id]) => [key, () => pressFlow($, key, id)]));
+}
+__name(flowRowPresses, "flowRowPresses");
+function pressFlow($, key, id) {
+ noteFlow(bind($), () => id !== null ? { type: "toggle", id } : { type: "step", by: key === FLOW_NEXT ? 1 : -1 });
+}
+__name(pressFlow, "pressFlow");
function selectTab($, tab) {
try {
dispatch(bind($), { type: "tab", tab });
@@ -3431,24 +5146,56 @@ function selectTab($, tab) {
}
}
__name(selectTab, "selectTab");
-function tabBody(b, e) {
+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")
+};
+function mapTurn() {
+ if (flowOn) return { lit: litFromFlow(flow.state), story: storyFromFlow(flow.state) };
+ const root = state.repoRoot;
+ const lit = root === null ? NO_LIT : litFromTrail(map.trail, root, isWindowsPath(root));
+ return { lit, story: storyFromTrail(map.trail) };
+}
+__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 pressHealth($) {
+ try {
+ map.toggleHealth(bind($));
+ } catch (err) {
+ bind($).debug(`health toggle failed: ${String(err)}`);
+ }
+}
+__name(pressHealth, "pressHealth");
+function tabBody(b, e) {
const tab = state.pane.tab;
if (tab !== "map") map.offScreen();
- if (tab === "ask") return askView(state, bodyColumns);
- if (tab === "recap") return recapView(state, { count: map.trail.reads.length, capped: map.trail.readsCapped }, bodyColumns);
- const d = discovery;
- const notice = d === null ? MAP_COPY.looking : HINTS[hintFor(d.mode, d.liteReason) ?? "no-index"];
- const bodyRows = scroll.bodyRows - TAB_ROWS;
- return map.paneTree(b, { surface: e.surface, notice, bodyColumns, placement, bodyRows });
+ if (tab !== "flow") flow.hide();
+ const rows = (e.props.placement === "dock" ? e.props.scroll.bodyRows : PANE_ROWS) - TAB_ROWS;
+ return TAB_BODIES[tab](b, e, rows);
}
__name(tabBody, "tabBody");
async function onPane($, e, next) {
if (e.requestId !== PANE_ID) return next(e);
const b = bind($);
try {
- const presses = Object.fromEntries(TABS.map((tab) => [TAB_PRESS[tab], () => selectTab($, tab)]));
- return materialize(paneView(state.pane.tab, tabBody(b, e)), $.ui.resolve(e), presses);
+ const bar = tabBar(flowOn);
+ const presses = { ...tabPresses($, bar), ...flowRowPresses($), [HEALTH_KEY]: () => pressHealth($) };
+ return materialize(paneView(state.pane.tab, tabBody(b, e), bar), $.ui.resolve(e), presses);
} catch (err) {
b.debug(`pane render failed: ${String(err)}`);
return next(e);
@@ -3458,7 +5205,11 @@ __name(onPane, "onPane");
function register(on, options = {}) {
reviewOn = options["lens_review"] !== false;
autoOpenOn = options["lens_pane_autoopen"] === true;
+ healthOn = options["lens_map_health"] === true;
+ flowOn = options["lens_flow"] !== false;
+ state = freshSession();
on("session.start", onSessionStart);
+ on("session.end", onSessionEnd);
on("turn.start", onTurnStart);
on("turn.complete", onTurnComplete);
on("ui.render", { component: "AbovePrompt" }, onBand);
diff --git a/tests/unit/cli/test_claude_plugin.py b/tests/unit/cli/test_claude_plugin.py
index 193810140..4bb940f1e 100644
--- a/tests/unit/cli/test_claude_plugin.py
+++ b/tests/unit/cli/test_claude_plugin.py
@@ -53,8 +53,11 @@ def test_claude_plugin_lens_module() -> None:
("lens_margin", True, "!== false"),
("lens_squeeze", True, "!== false"),
("lens_review", True, "!== false"),
+ ("lens_flow", True, "!== false"),
# Off by default: the map opens unasked only for someone who turned this on.
("lens_pane_autoopen", False, "=== true"),
+ # Off by default: the map is quiet tiles; health colours are a button away.
+ ("lens_map_health", False, "=== true"),
],
)
def test_claude_plugin_lens_toggles(field: str, default: bool, read_as: str) -> None:
@@ -71,7 +74,7 @@ def test_claude_plugin_lens_toggles(field: str, default: bool, read_as: str) ->
def test_claude_plugin_lens_toggles_are_all_tested() -> None:
config = _load_json(PLUGIN_ROOT / ".claude-plugin" / "plugin.json")["userConfig"]
- assert set(config) == {"lens_margin", "lens_squeeze", "lens_review", "lens_pane_autoopen"}
+ assert set(config) == {"lens_margin", "lens_squeeze", "lens_review", "lens_flow", "lens_pane_autoopen", "lens_map_health"}
def test_claude_plugin_mcp_uses_repowise() -> None: