Upgrade Claude from text search to code understanding.

While Constellation's MCP server provides raw code intelligence capabilities, this plugin enhances your Claude Code experience with:
| Feature | Benefit |
|---|---|
| Slash Commands | Quick access to common workflows |
| Contextual Skills | Claude automatically loads relevant knowledge, including proactive impact analysis before risky changes |
| Safety Hooks | Nudges Claude toward code_intel over text search at session start, in subagents, in the search tools' descriptions, and before symbol-like searches inside indexed projects, and adds a one-line code_intel hint to the result of a symbol search |
Execute powerful analysis with simple slash commands:
| Command | Description |
|---|---|
/constellation:status | Check API connectivity and authentication with a ping (no index details) |
/constellation:diagnose | Quick health check for connectivity and authentication |
/constellation:impact <symbol> [file-path] | Analyze blast radius before changing a symbol |
/constellation:deps <file> [--reverse] | Map dependencies or find what depends on a file |
/constellation:unused | Discover orphaned exports and dead code |
/constellation:architecture | Get a high-level overview of your codebase structure |
Claude automatically activates specialized knowledge based on your questions:
| Skill | Triggers When You Ask About... |
|---|---|
| constellation-troubleshooting | Error codes, connectivity issues, debugging problems |
| impact-analysis | Renaming, refactoring, deleting, or moving symbols/files; "what would break if...", "is X dead code", "what depends on X" |
Example Trigger:
You: "Rename AuthService to AuthenticationService"
Claude: "Before renaming, let me analyze the potential impact..."
[impact-analysis skill activates, runs api.impactAnalysis, reports risk + dependents]
Event hooks enable intelligent, transparent assistance. They run in-process inside Claude Code, declared by the plugin's hooks module (hooks/register.ts):
| Hook | Event (matcher) | Behavior | |||
|---|---|---|---|---|---|
| Session Awareness | classic.SessionStart | Injects code_intel MCP tool awareness at session start, including after clear, resume, and compact | |||
| Subagent Awareness | classic.SubagentStart | Injects code_intel awareness into spawned subagents (built-ins like Explore/Plan don't inherit project AGENTS.md) | |||
| Search Tool Nudge | tool.call (`Grep\ | Glob`) | Reminds Claude to prefer code_intel when a Grep pattern looks like a symbol (AuthService, class UserService, getUser\(), or a Glob has a PascalCase or camelCase file stem (/UserService.ts), and the search is inside an indexed project. Quoted phrases, error text, TODO-style markers, regex with character classes or alternation, and extension globs such as /*.ts get no reminder | ||
| Bash Search Nudge | tool.call (Bash) | Parses the leading command, up to the first unquoted `\ | , ;, && or \ | \ | (or the command after a leading cd <dir> &&). When it is grep, egrep, rg, ag, ack or git grep (also after git -C <dir> or variable assignments such as LC_ALL=C) and the pattern looks like a symbol, adds the same reminder when the searched directory is inside an indexed project. Flags and their values (-t ts, -A 3, -g '*.ts') are skipped, and language keywords such as import are not symbols. A grep after a pipe, awk, and findstr` no longer trigger a reminder |
| Tool description guidance | tool.describe (`Grep\ | Glob\ | Bash`) | Appends a short rule to the description of the search tools: use code_intel for symbol definitions, references, dependents, call graphs and impact, and keep text search for literal text. Applied once per session; if the session starts outside an indexed project, it is added once the working directory moves into one, and then kept, so moving around never rewrites the prompt cache. Native macOS and Linux builds have no Grep or Glob tool, so there it is the Bash description that carries the rule | |
| Reminder budget | turn.start, tool.call (code_intel), classic.SessionStart (clear, resume, fork) | Caps the search reminders at nudgeLimit per session (default 3), counted separately for each subagent, and skips a reminder when code_intel was already called earlier in the same turn. See Reminder limit | |||
| Adoption counter | tool.call (code_intel), tool.call (`Grep\ | Glob\ | Bash), ui.render (Spinner, only with showAdoption`) | Counts Claude's code_intel calls and, with a key and inside an indexed project, its text searches (symbol-like or literal), for the session and per day, on this machine only. Shown on the Stats tab of /constellation and, with showAdoption on, beside the spinner. See Adoption counter | |
| Search result hint | tool.call (`Grep\ | Bash`) | After a symbol search with Grep, or with grep, egrep, rg, ag, ack or git grep in the shell, looks the symbol up with code_intel and adds one line to the search result, for example ✦ >_CONSTELLATION://CODE_INTEL · AuthService (class) is defined at src/auth/auth.service.ts:12, with 4 usages. Use code_intel for references, callers, and impact. See Search result hint |
All hooks are gated on CONSTELLATION_ACCESS_KEY being set and starting with ak: (no key means a silent no-op, so the plugin doesn't nag in environments where Constellation isn't configured), with one exception: the adoption counter counts a code_intel call with or without a key. The counter only counts and adds nothing to Claude's context. The tool description guidance, the search nudges, the search result hint and the counting of text searches also require a constellation.json in the searched directory (the call's path for Grep and Glob when set, else the working directory) or a parent, so they stay out of projects that are not indexed. Subagents such as Explore see the same rewritten descriptions. The reminders are added to what the call already returns, so a permission decision made by another hook is kept.
The search reminders are limited so they stay useful instead of repeating on every search:
nudgeLimit reminders (default 3). Only searches that would have drawn a reminder count against it. Each subagent has its own limit, because its context starts empty.code_intel was already called earlier in the same turn, a symbol search in that turn gets no reminder and uses none of the limit./clear and when a session is resumed or forked.Set nudgeLimit with /config (it appears under the Constellation plugin) or run claude plugin configure constellation. A value of 0 turns the search reminders off while keeping the awareness text and the description guidance.
When Claude searches for a symbol with Grep, or with grep, egrep, rg, ag, ack or git grep in the shell, the search runs first and its result is kept as it is. The plugin then looks the symbol up with code_intel (the most used exact-name match, exported symbols first, with its usage count from the graph) and adds one line after the result, so Claude learns the graph has the answer without being told off for searching. It applies to subagent searches too.
/clear, /resume or /branch. Two searches running at once show it once.code_intel was already called earlier in the same turn, for patterns that are not symbol-like (the same rules as the reminders), and outside indexed projects.nudgeLimit: the hint has its own once-per-symbol rule and never uses the reminder count.Turn it off by setting augmentGrep to false with /config or claude plugin configure constellation.
The plugin counts how often Claude uses code_intel beside how often it searches text, so you can see whether the reminders work. The counts stay on your machine: they are never sent to Constellation or anywhere else.
code_intel call Claude or a subagent makes (with the time the call reported), and each search Claude or a subagent runs with Grep, Glob, or grep, egrep, rg, ag, ack or git grep in the shell, as symbol-like or literal by the same rules as the reminders. A search counts only where code_intel could have answered it: with an access key set, and inside an indexed project (a constellation.json in the searched directory or a parent).code_intel lookups (the search result hint, the impact features, the /constellation pane), a search another plugin runs, a search with no access key or outside an indexed project, a call or search that was refused, and shell commands that are not searches.code_intel calls out of code_intel calls plus symbol-like searches. Literal searches are shown but left out of it, because code_intel could not have answered them./constellation (or /constellation stats) shows this session, today and the last 30 days. Set showAdoption to true with /config or claude plugin configure constellation to also show the session's counts beside the spinner. It is off by default./constellation stats reads them. The session's counts start over after /clear and when a session is resumed or forked; the daily totals stay.The hooks above come from a hooks module (hooks/register.ts) that Claude Code loads and runs in-process, in the same session, instead of starting a separate node process per event. The module makes no network requests of its own. It runs git only through Claude Code's process call, in the project root: git rev-parse, git symbolic-ref and git diff --name-only when Claude runs gh pr create, and git rev-parse and git rev-list --count for the index freshness indicator; the search result hint and the /constellation command query through the plugin's own MCP server. It uses only the Claude Code calls listed under Data Handling.
/constellation command: a pane with Status, Diagnose, Deps, Unused, Explore and Stats tabs (keys 1 to 6, r to refresh, Esc to close), run as /constellation [status|diagnose|deps <file>|unused [kind]|explore [query]|stats]. The Stats tab shows the adoption counter for this session, today and the last 30 days, all three read at the same moment (Refresh reads them again); it sends no query and opens without a key or an indexed project. It starts no model turn and works while Claude is mid-turn. Where the session cannot draw a pane (for example VS Code), it answers with a few lines of text instead. The Markdown /constellation:* commands remain.p (switch project) in the pane's header forgets it and shows the list again./constellation pane, the code_intel tool rows and the lines above the prompt follow Claude Code's theme (/theme). Dark themes get the Constellation palette; on light themes only gold and green change, to Claude Code's warning and success colors; ANSI and color-blind themes get Claude Code's own theme colors. Every status also carries a word and a symbol, so nothing depends on color alone. An open pane picks up a theme change the next time you run /constellation.impactGate option, set with /config or claude plugin configure constellation, is off by default. dialog asks you before an edit Claude Code would run without asking, to a file whose impact is at or above impactThreshold, offering Proceed, Proceed and don't ask again for this file, or Cancel; an edit already headed to the permission prompt gets a one-line impact summary beside it instead. In auto mode, where such an edit goes to the auto-mode classifier rather than to you, both dialog and native ask you first, and the classifier still decides after you choose Proceed. native sends that edit to Claude Code's own permission prompt, with the summary as a toast. require-analysis refuses Claude's first edit to such a file once, with the impact report as the reason, unless Claude already ran a code_intel impact query (impactAnalysis, traceSymbolUsage or getDependents) naming the file or a symbol its dependents import; the retry goes through. It is the mode for CI and headless runs, where no one can answer a dialog or a prompt. impactThreshold is high (the default) or critical. Dependents come from the last indexed commit, so a branch with unindexed changes can show fewer or more than the working tree has. Counts can also fall short where imports go through tsconfig path aliases or export * barrels. Any failure to read the impact, or a lookup that takes more than 3 seconds, lets the edit through; in require-analysis that edit was the file's one check, so later edits to it go through as well.✦ >_CONSTELLATION://CODE_INTEL · index 4 commits behind · indexed 2h ago, with the brand mark in blue. A failed ping shows its error and the next step instead. Nothing is shown when the index matches HEAD. The check runs at session start, after Claude runs a git commit, pull, checkout, merge or rebase, when the working directory changes and every 5 minutes. A session that cannot draw gets one log line. Turn it off with the showFreshness option (on by default), set with /config or claude plugin configure constellation; off, the plugin also skips the git checks and the ping behind the line.code_intel calls and results in the transcript get compact rows, for example ✦ >_CONSTELLATION://CODE_INTEL · impactAnalysis · constellation-core and ✗ HIGH · 23 dependents · 140 ms · as of abc1234. The result row summarizes what came back; an error shows its headline and the next step, for example ✗ AUTH_ERROR · Your access key wasn't accepted · const auth. An interrupted call, a result too large to read and a failure without an error code keep Claude Code's own row. Colors follow Claude Code's theme. With --verbose, Claude Code's own drawing also shows under the row. Turn the compact rows off with the compactToolRows option (on by default) to keep Claude Code's own rows.turnSummary option, on by default. After a turn that changed files, one line appears under Claude's answer, for example ✦ >_CONSTELLATION://CODE_INTEL · 3 files changed (1 new) · 12 downstream dependents (4 test files) · as of fba36d5. It counts edits made by subagents too. A file created this turn counts as new and is not queried. Only files in one project are counted and queried: the project of the first edited file inside one, so plan or scratch files and files in other projects are left out. A count of 100+ means a file has at least that many dependents. Files deleted with a shell rm are not tracked. Dependents come from the indexed commit (the 7-character commit is shown) and undercount imports through tsconfig path aliases and export * barrels.prImpact option, inform (the default), require or off. When Claude runs gh pr create or gh pr new (recognized anywhere in a && or ; chain or on a later line), the plugin lists the branch's changed files, their downstream dependents (those importing the most changed files first), the affected test files and the changed files' exported symbols that other files import. A PR for another branch (--head) or repository (--repo or GH_REPO), or after a cd the shell expands (~, $VAR, -), is left alone. Without --base, the base is the remote's default branch (origin/HEAD, else origin/main or origin/master when it exists); in a fork that is the fork's default branch, so pass --base there. A body file the same command writes is checked through the command text; a body file that cannot be read counts as having no heading. inform lets the command run and logs the section; require refuses the command once per branch per session, with the section as the reason, until the PR body has an ## Impact heading. It fails open: a git or code_intel error lets the command run. Dependents come from the indexed commit (shown as its 7-character commit) and undercount imports through tsconfig path aliases and export * barrels.showAdoption option, off by default. When on, the line that animates while a turn runs also shows the session's counts, for example Sauteing · ✦ 5 code_intel / 1 grep…: code_intel calls first, then symbol-like text searches, for the main conversation and subagents together. Nothing is added until one of the two is above zero, and the line is redrawn only when one of the two changes. Only the text after the spinner's word changes; the word, the timer and the token count stay Claude Code's own.hooks/hooks.json keeps an empty "hooks" block beside "modules", so older builds should still read it as a valid hooks file and simply run no hooks. This has not been tested on an older build./plugin, start Claude Code with --safe-mode, or set disableAllHooks in your settings.What the plugin runs, reads, and sends:
| Component | Runs / reads | Sends |
|---|---|---|
| MCP server | Started with npx -y @constellationdev/mcp@<pinned version>, which downloads the package from the npm registry. Reads constellation.json and the current git branch from your project, and reads lines from local source files to attach code snippets to query results | Queries (symbol names, file paths, project ID, branch) to the Constellation API at https://api.constellationdev.io, or the self-hosted URL you configure via CONSTELLATION_API_URL or constellation.json, authenticated with CONSTELLATION_ACCESS_KEY. Source code is never sent to the Constellation API. Code snippets are returned only to Claude in the local session |
| MCP server usage metrics | Runs after each code_intel call. On by default; set CONSTELLATION_USAGE_METRICS=false to turn it off | A usage event (project ID, branch, which API methods ran, estimated token counts, durations) to the same Constellation API at /intel/v1/usage, or to USAGE_ENDPOINT_URL if you set it, authenticated with CONSTELLATION_ACCESS_KEY. Contains no source code, snippets, or symbol contents |
| Hooks (hooks/register.ts) | Run in-process in Claude Code. Calls: $.clock.after (retries a failed search result hint or impact lookup after a minute, re-reads a file's impact after five minutes, runs the session start's connection check and freshness ping, and runs reload-plugins once the current handler has returned), $.clock.every (the 5-minute git-only freshness re-check), $.clock.now (tells when the code_intel rows last read the theme and verbose settings, when the onboarding band last read the theme, and which local day an adoption count belongs to), $.clock.sleep (the search result hint's 2.5 second deadline, the impact gate's 3 second one, the turn summary's 2 second one and the PR impact section's 8 second one, and the one second the Stats tab waits for adoption counts still being saved), $.command.register (adds the /constellation command), $.command.run (runs reload-plugins after sign-in, or once when the session start's ping with a stored key is refused, so every plugin reloads and the Constellation MCP server starts with the key), $.config.list (reads Claude Code's theme to choose the pane's, code_intel rows' and freshness band's colors, and the verbose setting to show Claude Code's own code_intel rows under the summaries; the rows read both at most once a second, and again when either changes in /config; the onboarding band reads the theme at most once a second), $.env.get (reads CONSTELLATION_ACCESS_KEY and checks it starts with ak:), $.env.set (sets CONSTELLATION_ACCESS_KEY to the stored key), $.fs.exists (checks for constellation.json in the searched directory and its parents, the project root walk for the freshness indicator, whether a file about to be edited already exists, and, for the onboarding, the .git and constellation.json walk-up from the working directory and whether /bin/sh exists), $.fs.read (reads the --body-file of gh pr create to check for an Impact heading, and, before the session start's ping with a stored key, the project's constellation.json, and, for the freshness indicator, the same file when the working directory moves into another project root: the ping is skipped when its apiUrl is not https://api.constellationdev.io or the file cannot be read), $.mcp.call and $.mcp.connect (run the onboarding's ping, which is also the freshness indicator's ping at session start and, when a key is configured and constellation.json uses the default API, on a move into another project root, the search result hint's, the /constellation command's, the impact gate's, the turn summary's and the PR impact section's code_intel queries through the plugin's MCP server), $.process.run (the onboarding's login-shell printenv CONSTELLATION_ACCESS_KEY key read-back at the start of an interactive session, or C:\Windows\System32\reg.exe query where there is no /bin/sh (Windows), and, when you press Sign in or Index this project, command -v constellation in a plain and then a login /bin/sh, each printing that shell's PATH; the read-back's o
hooks/register.ts 31 lines1import type { Register } from 'claude-code';
2import { registerAdoption } from './adoption';
3import { registerAugment } from './augment';
4import { registerBudget } from './budget';
5import { registerCommand } from './command';
6import { registerDescribe } from './describe';
7import { registerFreshness } from './freshness';
8import { registerImpactGate } from './impact';
9import { registerNudges } from './nudge';
10import { registerOnboarding } from './onboarding';
11import { registerPrImpact } from './primpact';
12import { registerSession } from './session';
13import { registerToolRows } from './toolrows';
14import { registerTurnSummary } from './turnsummary';
15
16export const register: Register = (on, options) => {
17 registerBudget(on, options);
18 registerNudges(on);
19 registerAdoption(on, options);
20 registerDescribe(on);
21 registerAugment(on, options);
22 registerSession(on);
23 registerCommand(on);
24 registerImpactGate(on, options);
25 registerTurnSummary(on, options);
26 registerPrImpact(on, options);
27 registerToolRows(on, options);
28 registerOnboarding(on);
29 registerFreshness(on, options);
30};
31hooks/adoption.ts 409 lines1import type { On, PluginOptions } from 'claude-code';
2import { isRecord, num } from './lib';
3
4/** How often code_intel was called, how long those calls took, and how many text searches ran beside them. */
5export type Counts = {
6 /** code_intel calls the agent made. */
7 codeIntel: number;
8 /** The time those calls reported, summed, in milliseconds. */
9 codeIntelMs: number;
10 /** Text searches for something that looks like a symbol. */
11 symbol: number;
12 /** Text searches for literal text. */
13 literal: number;
14};
15
16/** Counts for the main conversation and for every subagent together. */
17export type Buckets = { main: Counts; subagents: Counts };
18
19/** One counted call: whose it was and what it adds. */
20export type Note = { isMain: boolean; counts: Counts };
21
22/** Totals for the local day of the clock value given, and for the 30 days ending with it. */
23export type Stats = { today: Counts; last30: Counts };
24
25const FIELDS = ['codeIntel', 'codeIntelMs', 'symbol', 'literal'] as const;
26
27/** Every stored key starts with this, then the local date and the session id. */
28const PREFIX = 'adoption:';
29const DATED_KEY = /^adoption:(\d{4}-\d{2}-\d{2}):/;
30
31/** How many days, today included, the stored counts are kept and summed. */
32const KEPT_DAYS = 30;
33
34/** The brand mark that leads the spinner's counts. */
35const MARK = '✦';
36
37function zero(): Counts {
38 return { codeIntel: 0, codeIntelMs: 0, symbol: 0, literal: 0 };
39}
40
41function empty(): Buckets {
42 return { main: zero(), subagents: zero() };
43}
44
45function add(into: Counts, counts: Counts): void {
46 for (const field of FIELDS) into[field] += counts[field];
47}
48
49/** This session's totals. Module state only: a reload of the hooks module starts them over. */
50let session = empty();
51
52/** Whether the spinner shows the session's counts: the `showAdoption` option, read when the hooks register. */
53let shown = false;
54
55/**
56 * This session's stored entry per day key, as a promise so that calls arriving
57 * together share one read of the store. Kept across `resetAdoption()`: the
58 * stored day totals belong to the day, not the conversation.
59 */
60const days = new Map<string, Promise<Buckets>>();
61
62/**
63 * The last save queued per day key. Each save waits for the one before it, so
64 * two saves of one entry never land out of order and the last one carries
65 * every count.
66 */
67const writes = new Map<string, Promise<void>>();
68
69/** The background work still running: what `settled()` waits for. */
70const running = new Set<Promise<void>>();
71
72/** Whether this load already deleted the entries past their kept days. */
73let pruned = false;
74
75function note(isMain: boolean, counts: Counts): Note {
76 add(isMain ? session.main : session.subagents, counts);
77 return { isMain, counts };
78}
79
80/** Counts one code_intel call in the session totals, with its time when the answer carried one. */
81export function noteCodeIntelCall(isMain: boolean, timeMs?: number): Note {
82 return note(isMain, { ...zero(), codeIntel: 1, codeIntelMs: typeof timeMs === 'number' ? timeMs : 0 });
83}
84
85/** Counts one text search in the session totals, as symbol-like or literal. */
86export function noteSearch(isMain: boolean, symbolLike: boolean): Note {
87 return note(isMain, { ...zero(), symbol: symbolLike ? 1 : 0, literal: symbolLike ? 0 : 1 });
88}
89
90/** This session's totals, as copies. */
91export function sessionCounts(): Buckets {
92 return { main: { ...session.main }, subagents: { ...session.subagents } };
93}
94
95/** The main conversation's counts and the subagents' together. */
96export function total(buckets: Buckets): Counts {
97 const sum = zero();
98 add(sum, buckets.main);
99 add(sum, buckets.subagents);
100 return sum;
101}
102
103/**
104 * The share of symbol lookups that went to code_intel: its calls over its calls
105 * plus the symbol-like text searches. Literal searches are not lookups
106 * code_intel could have answered, so they never enter it. Undefined with nothing to divide.
107 */
108export function ratio(counts: Counts): number | undefined {
109 const lookups = counts.codeIntel + counts.symbol;
110 return lookups === 0 ? undefined : counts.codeIntel / lookups;
111}
112
113/**
114 * What the spinner adds before its own suffix: the session's code_intel calls
115 * and symbol-like text searches, main conversation and subagents together.
116 * Empty while both are 0.
117 */
118export function suffixText(): string {
119 const { codeIntel, symbol } = total(session);
120 return codeIntel === 0 && symbol === 0 ? '' : ` · ${MARK} ${codeIntel} code_intel / ${symbol} grep`;
121}
122
123/** True when the spinner shows the counts, so a new count asks for a redraw. */
124export function showsAdoption(): boolean {
125 return shown;
126}
127
128/** Thousands separators for a count, as `3,079`. */
129function grouped(n: number): string {
130 return n.toLocaleString('en-US');
131}
132
133function calls(n: number): string {
134 return `${grouped(n)} code_intel call${n === 1 ? '' : 's'}`;
135}
136
137function searches(n: number, what: string): string {
138 return `${grouped(n)} ${what} search${n === 1 ? '' : 'es'}`;
139}
140
141/** Milliseconds under a second, else seconds to one decimal, as `1.2 s`. */
142function duration(ms: number): string {
143 return ms < 1000 ? `${Math.round(ms)} ms` : `${(ms / 1000).toFixed(1)} s`;
144}
145
146/** What the percentage in a row of figures is. */
147export const SHARE_LABEL = 'structural lookups';
148export const SHARE_NOTE = 'Structural lookups: code_intel calls out of code_intel calls plus symbol-like text searches. Literal searches are left out.';
149/** Said in place of the stored rows when the store cannot be read. */
150export const UNREAD_NOTE = 'The stored history could not be read.';
151
152/** One row's counts in words: the calls with their summed time, both kinds of search, and the ratio as a percentage. */
153export type Figures = { calls: string; symbol: string; literal: string; share: string };
154
155function percent(counts: Counts): string {
156 const share = ratio(counts);
157 return share === undefined ? 'n/a' : `${Math.round(share * 100)}%`;
158}
159
160export function figures(counts: Counts): Figures {
161 return {
162 calls: `${calls(counts.codeIntel)} (${duration(counts.codeIntelMs)})`,
163 symbol: searches(counts.symbol, 'symbol-like'),
164 literal: searches(counts.literal, 'literal'),
165 share: percent(counts),
166 };
167}
168
169/** One row of the Stats tab: its name, its counts and, for the session, the main and subagent split. */
170export type StatRow = { label: string; counts: Counts; split?: string };
171
172/** The session row, then today and the last 30 days when the stored counts were read. */
173export function statRows(buckets: Buckets, stored: Stats | undefined): StatRow[] {
174 const part = (name: string, counts: Counts) => `${name}: ${calls(counts.codeIntel)}, ${searches(counts.symbol, 'symbol-like')}`;
175 return [
176 { label: 'This session', counts: total(buckets), split: `${part('main', buckets.main)} · ${part('subagents', buckets.subagents)}` },
177 ...(stored === undefined
178 ? []
179 : [
180 { label: 'Today', counts: stored.today },
181 { label: 'Last 30 days', counts: stored.last30 },
182 ]),
183 ];
184}
185
186/**
187 * The same rows as bare figures, the words left to a table's head, for a
188 * surface without a monospace grid (the Desktop app). The session's main and
189 * subagent split are rows of their own under it.
190 */
191export function statsCells(buckets: Buckets, stored: Stats | undefined): { label: string; figures: Figures }[] {
192 const row = (label: string, c: Counts) => ({
193 label,
194 figures: { calls: `${grouped(c.codeIntel)} (${duration(c.codeIntelMs)})`, symbol: grouped(c.symbol), literal: grouped(c.literal), share: percent(c) },
195 });
196 return statRows(buckets, stored).flatMap((r) =>
197 r.split === undefined ? [row(r.label, r.counts)] : [row(r.label, r.counts), row('↳ main', buckets.main), row('↳ subagents', buckets.subagents)],
198 );
199}
200
201/** The same rows as plain lines, for the command's text reply. */
202export function statsLines(buckets: Buckets, stored: Stats | undefined): string[] {
203 const lines = statRows(buckets, stored).map((row) => {
204 const f = figures(row.counts);
205 const split = row.split === undefined ? '' : ` (${row.split})`;
206 return `${row.label}: ${f.calls} · ${f.symbol} · ${f.literal} · ${f.share} ${SHARE_LABEL}${split}`;
207 });
208 return stored === undefined ? [...lines, UNREAD_NOTE] : lines;
209}
210
211/** `YYYY-MM-DD` for a local year, month (from 0) and day; a day outside the month rolls over. */
212function localDate(year: number, month: number, day: number): string {
213 const date = new Date(year, month, day, 12);
214 const pad = (n: number) => String(n).padStart(2, '0');
215 return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}`;
216}
217
218/** The first and last local dates the stored counts are summed over at `nowMs`. */
219function keptDates(nowMs: number): { oldest: string; today: string } {
220 const now = new Date(nowMs);
221 const [year, month, day] = [now.getFullYear(), now.getMonth(), now.getDate()];
222 return { oldest: localDate(year, month, day - (KEPT_DAYS - 1)), today: localDate(year, month, day) };
223}
224
225/**
226 * The store key of one session's counts for the local day of `nowMs`. One key
227 * per session: the store has no atomic update, so two sessions writing one key
228 * would lose each other's counts.
229 */
230export function dayKey(nowMs: number, sessionId: string): string {
231 return `${PREFIX}${keptDates(nowMs).today}:${sessionId}`;
232}
233
234function countsOf(value: unknown): Counts | undefined {
235 if (!isRecord(value)) return undefined;
236 const counts = zero();
237 for (const field of FIELDS) {
238 const n = num(value[field]);
239 if (n === undefined) return undefined;
240 counts[field] = n;
241 }
242 return counts;
243}
244
245/** A stored entry, or undefined when the value is not one. */
246function bucketsOf(value: unknown): Buckets | undefined {
247 if (!isRecord(value)) return undefined;
248 const main = countsOf(value.main);
249 const subagents = countsOf(value.subagents);
250 return main === undefined || subagents === undefined ? undefined : { main, subagents };
251}
252
253/** The local date in a stored key, or undefined when the key is not this module's. */
254function dateOf(key: string): string | undefined {
255 return DATED_KEY.exec(key)?.[1];
256}
257
258/** Deletes the entries dated before `oldest`. A delete that fails is left for the next time. */
259async function prune(oldest: string, keys: readonly string[], del: (key: string) => Promise<void>): Promise<void> {
260 await Promise.allSettled(
261 keys
262 .filter((key) => {
263 const date = dateOf(key);
264 return date !== undefined && date < oldest;
265 })
266 .map(async (key) => del(key)),
267 );
268}
269
270/**
271 * Adds `counted` to this session's entry under `key` and saves it. The first
272 * call for a key reads what the store already holds (`(k) => $.store.get(k)`),
273 * so a reloaded module or a resumed session adds to its earlier counts; a read
274 * that fails is tried again by the next call. `save` is `(k, v) => $.store.set(k, v)`.
275 * Saves of one key run one after another, in the order the counts arrived.
276 */
277export async function persist(
278 counted: Note,
279 key: string,
280 load: (key: string) => Promise<unknown>,
281 save: (key: string, entry: Buckets) => Promise<void>,
282): Promise<void> {
283 let seeded = days.get(key);
284 if (seeded === undefined) {
285 seeded = load(key).then((stored) => bucketsOf(stored) ?? empty());
286 days.set(key, seeded);
287 seeded.catch(() => {
288 if (days.get(key) === seeded) days.delete(key);
289 });
290 }
291 const entry = await seeded;
292 add(counted.isMain ? entry.main : entry.subagents, counted.counts);
293 const write = (writes.get(key) ?? Promise.resolve()).catch(() => undefined).then(() => save(key, entry));
294 writes.set(key, write);
295 await write;
296}
297
298/** The store as the counting hooks hand it over: each member a closure that spells its own `$` call. */
299export type StorePort = {
300 /** `() => $.clock.now()` */
301 now: () => Promise<number>;
302 /** `() => $.session.id()` */
303 sessionId: () => Promise<string>;
304 /** `(k) => $.store.get(k)` */
305 get: (key: string) => Promise<unknown>;
306 /** `(k, entry) => $.store.set(k, entry)` */
307 set: (key: string, entry: Buckets) => Promise<void>;
308 /** `() => $.store.keys()` */
309 keys: () => Promise<readonly string[]>;
310 /** `(k) => $.store.delete(k)` */
311 del: (key: string) => Promise<void>;
312};
313
314/**
315 * Saves `counted` under this session's key for the local day and, on the first
316 * call of a load, deletes the entries past their kept days. Never rejects: a
317 * store that fails leaves the session totals as they were.
318 */
319export async function save(counted: Note, store: StorePort): Promise<void> {
320 const isFirst = !pruned;
321 pruned = true;
322 try {
323 const now = await store.now();
324 await Promise.allSettled([
325 (async () => persist(counted, dayKey(now, await store.sessionId()), store.get, store.set))(),
326 isFirst ? (async () => prune(keptDates(now).oldest, await store.keys(), store.del))() : undefined,
327 ]);
328 } catch {
329 // No clock: nothing is stored for this count.
330 }
331}
332
333/**
334 * Starts `work` and returns at once, so a tool's answer never waits on the
335 * store. A failure is dropped. `settled()` waits for it.
336 */
337export function background(work: () => Promise<void>): void {
338 const task = (async () => work())().catch(() => undefined);
339 running.add(task);
340 void task.finally(() => running.delete(task));
341}
342
343/** Resolves once no background work is running, including work started while it waited. */
344export async function settled(): Promise<void> {
345 while (running.size > 0) await Promise.all(running);
346}
347
348/**
349 * Sums every session's stored counts for today and for the last 30 days, today
350 * included, and deletes the entries older than that. `keys`, `get` and `del`
351 * are `await $.store.keys()`, `(k) => $.store.get(k)` and `(k) => $.store.delete(k)`.
352 * A key or value that is not this module's is left alone and not counted, and
353 * so is an entry whose read fails.
354 */
355export async function loadStats(
356 nowMs: number,
357 keys: readonly string[],
358 get: (key: string) => Promise<unknown>,
359 del: (key: string) => Promise<void>,
360): Promise<Stats> {
361 const { oldest, today } = keptDates(nowMs);
362 const stats: Stats = { today: zero(), last30: zero() };
363 const kept = keys.flatMap((key) => {
364 const date = dateOf(key);
365 return date === undefined || date < oldest ? [] : [{ key, date }];
366 });
367 const [entries] = await Promise.all([Promise.allSettled(kept.map(async ({ key }) => bucketsOf(await get(key)))), prune(oldest, keys, del)]);
368 entries.forEach((read, i) => {
369 if (read.status !== 'fulfilled' || read.value === undefined) return;
370 const counts = total(read.value);
371 add(stats.last30, counts);
372 if (kept[i]?.date === today) add(stats.today, counts);
373 });
374 return stats;
375}
376
377/** Starts the session totals over, for a new conversation (`/clear`, `/resume`, `/branch`). The stored day totals stay. */
378export function resetAdoption(): void {
379 session = empty();
380}
381
382/**
383 * Drops the day entries held in memory and the saves still queued, as a reload
384 * of the hooks module does; the next count reads the store again and prunes it.
385 */
386export function forgetDays(): void {
387 days.clear();
388 writes.clear();
389 running.clear();
390 pruned = false;
391}
392
393/**
394 * Starts the counts over for this load and, with `showAdoption` on, puts the
395 * session's counts on the spinner, before the engine's own suffix. Unset reads
396 * as off. Counting never depends on the option.
397 */
398export function registerAdoption(on: On, options: PluginOptions): void {
399 resetAdoption();
400 forgetDays();
401 shown = options.showAdoption === true;
402 if (!shown) return;
403
404 on('ui.render', { component: 'Spinner' }, async (_$, e, next) => {
405 const text = suffixText();
406 return text === '' ? next(e) : next({ ...e, props: { ...e.props, suffix: text + e.props.suffix } });
407 });
408}
409hooks/augment.ts 165 lines1import type { EngineInterface, On, PluginOptions } from 'claude-code';
2import { agentKey, usedCodeIntelThisTurn } from './budget';
3import { searchTarget } from './classify';
4import { codeIntel, isConfigured, projectRoot, withinDeadline } from './lib';
5import { branded } from './theme';
6
7/**
8 * How long a finished search waits for its code_intel lookup before it returns
9 * the search result alone. The lookup starts with the search, so it has the
10 * search's own time as well. Allows for a cold start of the MCP server.
11 */
12export const SOFT_DEADLINE_MS = 2500;
13
14/** How long a lookup that failed (server down, sign-in, timeout) is remembered before it is tried again. */
15export const FAILURE_BACKOFF_MS = 60_000;
16
17/** What the lookup reports for an exact-name symbol match. */
18export type Found = {
19 name: string;
20 kind: string;
21 filePath: string;
22 line: number;
23 /** The graph's usage count of the symbol. */
24 usages: number;
25 /** How many symbols carry the name; the one reported is the most used. */
26 definitions: number;
27};
28
29/**
30 * Lookups by project root and identifier: in flight, or settled to a match,
31 * null (no exact match) or undefined (failed). A failure is dropped after
32 * `FAILURE_BACKOFF_MS`, so a down server costs one lookup a minute, not one per search.
33 */
34const lookups = new Map<string, Promise<Found | null | undefined>>();
35
36/**
37 * Lines already shown, by agent, project root and identifier. Claimed before the
38 * lookup is awaited, so parallel searches show one line, and released when no
39 * line is shown.
40 */
41const shown = new Set<string>();
42
43/** The part of code_intel's `api` the lookup uses. */
44export type LookupApi = {
45 searchSymbols: (params: {
46 query: string;
47 limit: number;
48 includeUsageCount: boolean;
49 isExported?: boolean;
50 }) => Promise<{ symbols: ReadonlyArray<{ name: string; kind: string; filePath: string; line: number; usageCount?: number }> }>;
51};
52
53/**
54 * The most used exact-name match for `name`, searched among exported symbols
55 * first, then among used symbols that are not exported (an unused one there is
56 * usually a fixture, not what the search means), or null when nothing matches.
57 * `searchSymbols` matches substrings, so the exact name can sit far down a
58 * page; a full page is read.
59 *
60 * Runs inside code_intel: `lookupCode` sends its source, so it may use only
61 * its arguments.
62 */
63export async function lookupSymbol(api: LookupApi, name: string): Promise<Found | null> {
64 const exact = async (isExported?: boolean) =>
65 (await api.searchSymbols({ query: name, limit: 100, includeUsageCount: true, ...(isExported ? { isExported } : {}) })).symbols.filter(
66 (s) => s.name === name,
67 );
68 let hits = await exact(true);
69 if (hits.length === 0) hits = (await exact()).filter((s) => (s.usageCount ?? 0) > 0);
70 const hit = hits.reduce<(typeof hits)[number] | null>((a, b) => (a === null || (b.usageCount ?? 0) > (a.usageCount ?? 0) ? b : a), null);
71 if (hit === null) return null;
72 return { name: hit.name, kind: hit.kind, filePath: hit.filePath, line: hit.line, usages: hit.usageCount ?? 0, definitions: hits.length };
73}
74
75/** The code_intel program that runs `lookupSymbol` for `name`. */
76export function lookupCode(name: string): string {
77 return `return await (${lookupSymbol.toString()})(api, ${JSON.stringify(name)});`;
78}
79
80/** The lookup's result read into `Found`, or null when it is not one. */
81function foundOf(value: unknown): Found | null {
82 if (typeof value !== 'object' || value === null) return null;
83 const name: unknown = Reflect.get(value, 'name');
84 const kind: unknown = Reflect.get(value, 'kind');
85 const filePath: unknown = Reflect.get(value, 'filePath');
86 const line: unknown = Reflect.get(value, 'line');
87 const usages: unknown = Reflect.get(value, 'usages');
88 const definitions: unknown = Reflect.get(value, 'definitions');
89 if (typeof name !== 'string' || typeof kind !== 'string' || typeof filePath !== 'string') return null;
90 if (typeof line !== 'number' || typeof usages !== 'number' || typeof definitions !== 'number') return null;
91 return { name, kind, filePath, line, usages, definitions };
92}
93
94/** The one line a search result gains. */
95export function augmentLine({ name, kind, filePath, line, usages, definitions }: Found): string {
96 const others = definitions > 1 ? `, the most used of ${definitions} symbols with that name` : '';
97 const count = `${usages} ${usages === 1 ? 'usage' : 'usages'}`;
98 return branded(`${name} (${kind}) is defined at ${filePath}:${line}${others}, with ${count}. Use code_intel for references, callers, and impact.`);
99}
100
101/** The lookup for `name` in the project at `root`, shared with any already in flight or settled. */
102function lookup($: EngineInterface, root: string, name: string): Promise<Found | null | undefined> {
103 const key = `${root}\0${name}`;
104 let pending = lookups.get(key);
105 if (pending === undefined) {
106 const started: Promise<Found | null | undefined> = codeIntel(
107 { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
108 lookupCode(name),
109 { cwd: root },
110 ).then((envelope) => {
111 if (envelope.success) return foundOf(envelope.result);
112 // Only this failure is dropped: after a reset a newer lookup may hold the key.
113 $.clock.after(FAILURE_BACKOFF_MS, () => {
114 if (lookups.get(key) === started) lookups.delete(key);
115 });
116 return undefined;
117 });
118 lookups.set(key, started);
119 pending = started;
120 }
121 return pending;
122}
123
124export function registerAugment(on: On, options: PluginOptions): void {
125 lookups.clear();
126 shown.clear();
127 if (options.augmentGrep === false) return;
128
129 on('tool.call', { tool: /^(Grep|Bash)$/ }, async ($, e, next) => {
130 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return next(e);
131 const { symbol, path } = searchTarget(e);
132 if (symbol === null || usedCodeIntelThisTurn(e)) return next(e);
133 const root = await projectRoot(await $.session.cwd(), (p) => $.fs.exists(p), path);
134 if (root === null) return next(e);
135 const seen = `${agentKey(e)}\0${root}\0${symbol}`;
136 if (shown.has(seen)) return next(e);
137
138 shown.add(seen);
139 const pending = lookup($, root, symbol);
140 const r = await next(e);
141 if (r.deny !== undefined || r.isError) {
142 shown.delete(seen);
143 return r;
144 }
145 const found = await withinDeadline((ms, o) => $.clock.sleep(ms, o), pending, SOFT_DEADLINE_MS, next.signal);
146 if (found === null || found === undefined) {
147 shown.delete(seen);
148 return r;
149 }
150 return { ...r, context: [...(r.context ?? []), augmentLine(found)] };
151 });
152}
153
154/** Forgets every lookup and shown line, for a new conversation (`/clear`, `/resume`, `/branch`). */
155export function resetAugment(): void {
156 lookups.clear();
157 shown.clear();
158}
159
160/** Forgets the lines shown to the subagent `agentId` when its run ends; lookups stay shared. */
161export function forgetAgentLines(agentId: string): void {
162 const prefix = `${agentId}\0`;
163 for (const key of shown) if (key.startsWith(prefix)) shown.delete(key);
164}
165hooks/budget.ts 160 lines1import type { On, PluginOptions } from 'claude-code';
2import { background, noteCodeIntelCall, save, showsAdoption } from './adoption';
3import { observeEnvelope } from './freshness';
4import { absolute, canDraw, isConfigured, parseToolText, projectRoot, stringArg } from './lib';
5import { observeCodeIntel } from './onboarding';
6import { noteCodeIntel } from './risk';
7
8/** How many nudges one agent gets when the option is unset. */
9const DEFAULT_NUDGE_LIMIT = 3;
10
11/** The agent key of the main conversation. */
12export const MAIN = 'main';
13
14type AgentBudget = {
15 /** Nudges spent so far. */
16 nudges: number;
17 /** The turn in which the agent last called code_intel. */
18 codeIntelTurn?: string;
19};
20
21/**
22 * Per agent, what its budget has spent. Module state only: a reload of the
23 * hooks module starts every budget over, which is acceptable.
24 */
25const budgets = new Map<string, AgentBudget>();
26
27/**
28 * The main conversation's current turn, from `turn.start`. A subagent's run is
29 * one turn (its loop's `turn.complete` closes the run, and `forgetAgentBudget`
30 * then drops its state), so its turn is its `agentId`.
31 */
32let mainTurn: string | undefined;
33
34let nudgeLimit = DEFAULT_NUDGE_LIMIT;
35
36/** The agent a tool call belongs to: `agentId` in a subagent, else the main conversation. */
37export function agentKey(e: object): string {
38 return stringArg(e, 'agentId') ?? MAIN;
39}
40
41function budgetOf(key: string): AgentBudget {
42 let budget = budgets.get(key);
43 if (budget === undefined) {
44 budget = { nudges: 0 };
45 budgets.set(key, budget);
46 }
47 return budget;
48}
49
50/** The turn the agent `key` is in, or undefined before the main conversation's first turn. */
51function turnOf(key: string): string | undefined {
52 return key === MAIN ? mainTurn : key;
53}
54
55/** True when the agent that made the tool call `e` already called code_intel in its current turn. */
56export function usedCodeIntelThisTurn(e: object): boolean {
57 const key = agentKey(e);
58 const turn = turnOf(key);
59 return turn !== undefined && budgets.get(key)?.codeIntelTurn === turn;
60}
61
62/** True when the agent that made `e` has a nudge left. Spends nothing. */
63export function hasNudgeLeft(e: object): boolean {
64 return (budgets.get(agentKey(e))?.nudges ?? 0) < nudgeLimit;
65}
66
67/** Spends one nudge from the budget of the agent that made `e`; false, spending nothing, once it is used up. */
68export function spendNudge(e: object): boolean {
69 const budget = budgetOf(agentKey(e));
70 if (budget.nudges >= nudgeLimit) return false;
71 budget.nudges += 1;
72 return true;
73}
74
75export function registerBudget(on: On, options: PluginOptions): void {
76 const limit = options.nudgeLimit;
77 nudgeLimit = typeof limit === 'number' ? limit : DEFAULT_NUDGE_LIMIT;
78 budgets.clear();
79 mainTurn = undefined;
80
81 on('turn.start', async (_$, e, next) => {
82 mainTurn = e.turnId;
83 return next(e);
84 });
85
86 on('tool.call', { tool: /code_intel$/ }, async ($, e, next) => {
87 const key = agentKey(e);
88 const turn = turnOf(key);
89 if (turn !== undefined) budgetOf(key).codeIntelTurn = turn;
90 const r = await next(e);
91 // A plugin's own `$.mcp.call` of code_intel (this one's risk lookups among them) is not the agent's analysis,
92 // and the onboarding and the freshness indicator act on its own pings themselves.
93 if (next.origin.plugin === 'engine') {
94 noteCodeIntel(key, e, r);
95 try {
96 observeCodeIntel(
97 r,
98 isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY')),
99 () => $.ui.invalidate('ui.render'),
100 async (text) => {
101 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
102 },
103 );
104 } catch {
105 // The band stays as it was; the agent's answer goes back untouched.
106 }
107 // A refused call never ran; an errored one is still the agent reaching for code_intel.
108 if (r.deny === undefined) {
109 const counted = noteCodeIntelCall(key === MAIN, parseToolText(r.text, r.isError === true).time);
110 if (showsAdoption()) $.ui.invalidate('ui.render');
111 // Saved in the background: the agent's answer never waits on the store.
112 background(() =>
113 save(counted, {
114 now: () => $.clock.now(),
115 sessionId: () => $.session.id(),
116 get: (k) => $.store.get(k),
117 set: (k, entry) => $.store.set(k, entry),
118 keys: () => $.store.keys(),
119 del: (k) => $.store.delete(k),
120 }),
121 );
122 try {
123 // The index the answer came from, for the project the call ran in. The answer does not wait for git.
124 const session = await $.session.cwd();
125 const cwd = stringArg(e, 'cwd');
126 const root = await projectRoot(cwd === undefined ? session : absolute(cwd, session), (p) => $.fs.exists(p));
127 if (root !== null) {
128 void observeEnvelope(
129 parseToolText(r.text, r.isError === true),
130 root,
131 (argv, init) => $.process.run(argv, init),
132 () => $.ui.invalidate('ui.render'),
133 async (text) => {
134 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
135 },
136 ).catch(() => undefined);
137 }
138 } catch {
139 // The indicator stays as it was.
140 }
141 }
142 }
143 return r;
144 });
145}
146
147/** Starts every budget over, for a new conversation (`/clear`, `/resume`, `/branch`). */
148export function resetBudgets(): void {
149 budgets.clear();
150}
151
152/**
153 * Drops the budget of the subagent `agentId` when its run ends. A subagent
154 * continued later (SendMessage) keeps its id but starts a new run, so it gets a
155 * fresh budget and its earlier code_intel call no longer counts as this turn's.
156 */
157export function forgetAgentBudget(agentId: string): void {
158 budgets.delete(agentId);
159}
160hooks/command.ts 1413 lines1import type { ButtonProps, ElementTable, EngineInterface, On, RenderElement } from 'claude-code';
2import { SHARE_LABEL, SHARE_NOTE, UNREAD_NOTE, figures, loadStats, sessionCounts, settled, statRows, statsCells, statsLines } from './adoption';
3import type { Buckets, Stats } from './adoption';
4import { canDraw, codeIntel, isConfigured, isRecord, projectName, projectRoot, withinDeadline } from './lib';
5import type { CodeIntelEnvelope, CodeIntelError } from './lib';
6import { explain, explainLines } from './explain';
7import { askText, callTree, detailLines, detailRows, drillCode, hasCallGraph, hits, impactView, rankExact, searchCode, usageLines, usageRows, usageTotal, where } from './explore';
8import type { Hit } from './explore';
9import { byFile, orphanCode, orphanPage, removalPrompt } from './unused';
10import type { OrphanRow } from './unused';
11import type { Explanation } from './explain';
12import { observeEnvelope, recheck, showsFreshness, startTicks, track } from './freshness';
13import { checkConnection, pingProject, readStoredKeyAtStart, rememberRepo } from './onboarding';
14import type { FoundKey, OnboardingPorts } from './onboarding';
15import { BANNER_WIDTH, badge, branded, buttonRow, forTheme, header, kind, paint, palette, risk, scheme, status } from './theme';
16import type { Scheme } from './theme';
17
18/**
19 * The command's name. Mod commands allow letters, digits, `_` and `-`, so the
20 * bare name sits beside the Markdown `/constellation:*` commands, and a name
21 * a built-in owns is refused.
22 */
23export const COMMAND = 'constellation';
24
25/** The id of the pane the command opens; the `requestId` its tree is drawn under. */
26const PANE = 'constellation';
27
28const TABS = ['status', 'diagnose', 'deps', 'unused', 'explore', 'stats'] as const;
29export type Tab = (typeof TABS)[number];
30/** A tab that shows a code_intel query's answer. Stats shows counts kept on this machine and never queries. */
31type QueryTab = Exclude<Tab, 'stats'>;
32type Direction = 'dependencies' | 'dependents';
33
34const TAB_LABEL: Readonly<Record<Tab, string>> = {
35 status: 'Status',
36 diagnose: 'Diagnose',
37 deps: 'Deps',
38 unused: 'Unused',
39 explore: 'Explore',
40 stats: 'Stats',
41};
42
43/** One line under the tab row saying what the tab shows. */
44const TAB_HINT: Readonly<Record<Tab, string>> = {
45 status: 'Whether Constellation is reachable and your access key is accepted.',
46 diagnose: 'What the Constellation index holds for this project.',
47 deps: 'What a file imports, or what imports it.',
48 unused: 'Exports nothing imports. Verify each one before deleting it.',
49 explore: 'Search the graph and drill into a symbol without a Claude turn.',
50 stats: 'How often Claude called code_intel, beside its text searches. Counted on this machine only.',
51};
52
53/** The column a labeled row's value starts in. */
54const LABEL_WIDTH = 13;
55
56/** Rows a tab draws before it ends with a "+N more" line, and lines the text fallback keeps. */
57const MAX_ROWS = 15;
58const MAX_TEXT_LINES = 6;
59/** Hits the explorer lists in the pane, and the fewer the text fallback keeps. */
60const EXPLORE_ROWS = 20;
61const EXPLORE_TEXT_HITS = 5;
62
63/** One thing a tab shows: a line of text, optionally led by a status or kind badge, or a labeled value. */
64export type Item = {
65 /** The name of a fact (`Connection`, `Symbols`): drawn dim in a fixed column, with the value after it. */
66 label?: string;
67 badge?: { kind: 'status' | 'kind'; value: string };
68 text: string;
69 /** A file the person can pick: drawn as a pressable row. */
70 path?: string;
71 /** A project root the person can pick when the working directory is not one: a pressable row. */
72 project?: string;
73 /** Secondary text: drawn with `dimColor`. */
74 dim?: boolean;
75 /** A group title, such as a file in the unused list. */
76 heading?: boolean;
77};
78
79export type Summary = {
80 /** The same facts as plain lines, for the text fallback. */
81 lines: string[];
82 items: Item[];
83 error?: CodeIntelError;
84 /** The error laid out for a person, which the pane and the text reply draw in place of `items`. */
85 explanation?: Explanation;
86};
87
88export type SummaryOptions = {
89 direction?: Direction;
90 path?: string;
91 project?: string;
92 /** The symbol the explorer searched for, which ranks its exact matches first. */
93 query?: string;
94};
95
96/**
97 * The tab, file path and kind a command's arguments select: the first word
98 * names the tab (default status), for deps the rest is the file path, and for
99 * unused the next word (or `--kind <k>`) is the kind to list, and for explore the
100 * rest is the symbol to search for.
101 */
102export function parseArgs(args: string): { tab: Tab; path?: string; kind?: string; query?: string } {
103 const trimmed = args.trim();
104 const split = trimmed.search(/\s/);
105 const word = (split === -1 ? trimmed : trimmed.slice(0, split)).toLowerCase();
106 const tab = TABS.find((t) => t === word);
107 if (tab === undefined) return { tab: 'status' };
108 const rest = split === -1 ? '' : trimmed.slice(split).trim();
109 if (tab === 'unused') {
110 // `unused function` and `unused --kind function` both name a kind.
111 const kind = rest.replace(/^--kind(?:\s+|=)/, '').split(/\s+/)[0]?.toLowerCase();
112 return kind === undefined || kind === '' ? { tab } : { tab, kind };
113 }
114 if (tab === 'explore') return rest === '' ? { tab } : { tab, query: rest };
115 return tab === 'deps' && rest !== '' ? { tab, path: rest } : { tab };
116}
117
118function records(value: unknown): Record<string, unknown>[] {
119 return Array.isArray(value) ? value.filter(isRecord) : [];
120}
121
122function text(value: unknown): string | undefined {
123 return typeof value === 'string' && value !== '' ? value : undefined;
124}
125
126function count(value: unknown): number | undefined {
127 return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
128}
129
130/** Thousands separators for a count, as `3,079`. */
131function grouped(n: number): string {
132 return n.toLocaleString('en-US');
133}
134
135function lineOf(item: Item): string {
136 if (item.label !== undefined) {
137 const word = item.badge === undefined ? undefined : (item.badge.kind === 'status' ? status(item.badge.value) : kind(item.badge.value)).word;
138 const value = word !== undefined && item.text !== '' ? `${word} (${item.text})` : (word ?? item.text);
139 return `${item.label}: ${value}`;
140 }
141 if (item.badge?.kind === 'status') return `${item.text}: ${status(item.badge.value).word}`;
142 if (item.badge?.kind === 'kind') return ` ${item.text} · ${kind(item.badge.value).word}`;
143 return item.text;
144}
145
146function fromItems(items: Item[]): Summary {
147 return { lines: items.map(lineOf), items };
148}
149
150function failure(error: CodeIntelError): Summary {
151 const explanation = explain(error);
152 const candidates = error.candidates ?? [];
153 // With project roots to offer (the working directory sits above several
154 // projects), the pane asks for one instead of drawing the error.
155 const items: Item[] =
156 candidates.length > 0
157 ? [
158 { text: 'Choose a project', heading: true },
159 { text: 'This folder holds several Constellation projects.', dim: true },
160 ...candidates.map((c): Item => ({ text: projectName(c) ?? c, project: c })),
161 ]
162 : [];
163 return { lines: explainLines(explanation), items, error, explanation };
164}
165
166/** The first MAX_TEXT_LINES lines, then how many were left out, counting the rows a `+N more` line already stood for. */
167function textLines(lines: string[]): string[] {
168 if (lines.length <= MAX_TEXT_LINES) return lines;
169 const more = /^\+(\d+) more$/.exec(lines[lines.length - 1] ?? '');
170 const hidden = lines.length - MAX_TEXT_LINES + (more === null ? 0 : Number(more[1]) - 1);
171 return [...lines.slice(0, MAX_TEXT_LINES), `+${hidden} more`];
172}
173
174function capped(items: Item[]): Item[] {
175 if (items.length <= MAX_ROWS) return items;
176 return [...items.slice(0, MAX_ROWS), { text: `+${items.length - MAX_ROWS} more`, dim: true }];
177}
178
179function connection(result: unknown): Item[] {
180 const pong = isRecord(result) && result['pong'] === true;
181 return [
182 { label: 'Connection', badge: { kind: 'status', value: pong ? 'healthy' : 'unknown' }, text: '' },
183 { label: 'Auth', badge: { kind: 'status', value: pong ? 'healthy' : 'unknown' }, text: '' },
184 ];
185}
186
187function statusItems(result: unknown, project: string | undefined): Item[] {
188 return [...connection(result), ...(project === undefined ? [] : [{ label: 'Project', text: project }])];
189}
190
191function diagnoseItems(result: unknown): Item[] {
192 const ping = isRecord(result) ? result['ping'] : undefined;
193 const caps = isRecord(result) && isRecord(result['caps']) ? result['caps'] : {};
194 const indexed = caps['isIndexed'];
195 const items = connection(ping);
196 items.push({
197 label: 'Index',
198 badge: { kind: 'status', value: indexed === true ? 'indexed' : indexed === false ? 'not indexed' : 'unknown' },
199 text: '',
200 });
201 const languages = caps['languages'] ?? caps['supportedLanguages'];
202 if (Array.isArray(languages) && languages.length > 0) {
203 items.push({ label: 'Languages', text: languages.filter((l) => typeof l === 'string').join(', ') });
204 }
205 const symbols = count(caps['symbolCount']);
206 if (symbols !== undefined) items.push({ label: 'Symbols', text: grouped(symbols) });
207 const files = count(caps['fileCount']);
208 if (files !== undefined) items.push({ label: 'Files', text: grouped(files) });
209 const branch = text(caps['indexedBranch']);
210 if (branch !== undefined) items.push({ label: 'Branch', text: branch });
211 return items;
212}
213
214function depsItems(result: unknown, direction: Direction, path: string | undefined): Item[] {
215 if (!isRecord(result)) return [{ text: 'No data returned', dim: true }];
216 const entries = records(direction === 'dependencies' ? result['directDependencies'] : result['directDependents']);
217 const rows: Item[] = [];
218 for (const entry of entries) {
219 const file = text(entry['filePath']);
220 if (file !== undefined) rows.push({ text: file, path: file });
221 else {
222 const module = text(entry['moduleName']);
223 if (module !== undefined) rows.push({ text: module, dim: true });
224 }
225 }
226 const label = direction === 'dependencies' ? 'depends on' : 'is used by';
227 const header: Item = { text: `${path ?? text(result['file']) ?? 'file'} ${label} ${rows.length}`, heading: true };
228 return rows.length === 0
229 ? [header, { text: direction === 'dependencies' ? 'No dependencies found' : 'No dependents found', dim: true }]
230 : [header, ...capped(rows)];
231}
232
233function unusedItems(result: unknown): Item[] {
234 if (!isRecord(result)) return [{ text: 'No data returned', dim: true }];
235 const symbols = records(result['orphanedSymbols']);
236 if (symbols.length === 0) return [{ text: 'No unused exports found', dim: true }];
237 const byFile = new Map<string, Record<string, unknown>[]>();
238 for (const symbol of symbols) {
239 const file = text(symbol['filePath']) ?? 'unknown file';
240 byFile.set(file, [...(byFile.get(file) ?? []), symbol]);
241 }
242 const summary = isRecord(result['summary']) ? result['summary'] : {};
243 const total = count(summary['totalOrphanedSymbols']) ?? symbols.length;
244 const items: Item[] = [{ text: `${grouped(total)} unused exports`, heading: true }];
245 for (const [file, group] of byFile) {
246 items.push({ text: file, dim: true });
247 for (const symbol of group) {
248 items.push({ badge: { kind: 'kind', value: text(symbol['kind']) ?? 'unknown' }, text: text(symbol['name']) ?? 'unnamed' });
249 }
250 }
251 return capped(items);
252}
253
254/** The top matches of a symbol search as plain lines, exact name first. */
255function exploreItems(result: unknown, query: string | undefined): Item[] {
256 const found = rankExact(query ?? '', hits(result)).slice(0, EXPLORE_TEXT_HITS);
257 if (found.length === 0) return [{ text: 'No symbols match', dim: true }];
258 return found.map((h): Item => ({ text: `${h.name} · ${kind(h.kind).word} · ${where(h)}` }));
259}
260
261/**
262 * The facts of one tab from its code_intel envelope, shared by the pane and
263 * the text fallback: `items` carry the badges and rows the pane draws and
264 * `lines` the same facts as plain text. The envelope's `result` is untyped, so
265 * each field is narrowed against the executor schemas before it is read; on
266 * error the code, message and guidance are returned.
267 */
268export function summarize(tab: QueryTab, envelope: CodeIntelEnvelope, options: SummaryOptions = {}): Summary {
269 if (!envelope.success) return failure(envelope.error ?? { code: 'UNKNOWN', message: 'The request failed' });
270 const { result } = envelope;
271 switch (tab) {
272 case 'status':
273 return fromItems(statusItems(result, options.project));
274 case 'diagnose':
275 return fromItems(diagnoseItems(result));
276 case 'deps':
277 return fromItems(depsItems(result, options.direction ?? 'dependencies', options.path));
278 case 'unused':
279 return fromItems(unusedItems(result));
280 case 'explore':
281 return fromItems(exploreItems(result, options.query));
282 }
283}
284
285/** How long ago `iso` was, in the largest whole unit, from plain Date math. */
286function relative(iso: string): string {
287 const then = Date.parse(iso);
288 if (Number.isNaN(then)) return iso;
289 const seconds = Math.max(0, Math.round((Date.now() - then) / 1000));
290 if (seconds < 60) return 'just now';
291 const minutes = Math.floor(seconds / 60);
292 if (minutes < 60) return `${minutes}m ago`;
293 const hours = Math.floor(minutes / 60);
294 if (hours < 24) return `${hours}h ago`;
295 return `${Math.floor(hours / 24)}d ago`;
296}
297
298function metadata(envelope: CodeIntelEnvelope | undefined): string | undefined {
299 const parts: string[] = [];
300 if (envelope?.asOfCommit) parts.push(`as of ${envelope.asOfCommit.slice(0, 7)}`);
301 if (envelope?.lastIndexedAt) parts.push(`indexed ${relative(envelope.lastIndexedAt)}`);
302 return parts.length === 0 ? undefined : parts.join(' · ');
303}
304
305/**
306 * One line about a project for the picker, from its `getCapabilities` envelope:
307 * when it was indexed, its languages and its file count.
308 */
309export function projectDetail(envelope: CodeIntelEnvelope | undefined): string {
310 if (envelope === undefined) return 'checking';
311 if (!envelope.success) return envelope.error?.code === 'PROJECT_NOT_INDEXED' ? 'not indexed' : (envelope.error?.code ?? 'unavailable');
312 const caps = isRecord(envelope.result) ? envelope.result : {};
313 if (caps['isIndexed'] === false) return 'not indexed';
314 const parts: string[] = [];
315 const indexedAt = text(caps['lastIndexedAt']) ?? envelope.lastIndexedAt;
316 if (indexedAt !== undefined) parts.push(`indexed ${relative(indexedAt)}`);
317 const languages = caps['supportedLanguages'];
318 if (Array.isArray(languages)) {
319 const names = languages.filter((l): l is string => typeof l === 'string');
320 if (names.length > 0) parts.push(names.join(', '));
321 }
322 const files = count(caps['fileCount']);
323 if (files !== undefined) parts.push(`${files} files`);
324 return parts.length === 0 ? 'indexed' : parts.join(' · ');
325}
326
327/** The Unused tab's kind choices: the kinds an export usually has, of the categories `findOrphanedCode` filters by. */
328const UNUSED_KINDS: readonly string[] = ['function', 'class', 'interface', 'type', 'type_alias', 'variable', 'constant', 'enum', 'struct', 'trait', 'module', 'namespace'];
329/** The Unused kind choice that sends no filter. */
330const ALL_KINDS = 'all';
331
332/** The `findOrphanedCode` filter for the kind the command named, if any. */
333function unusedFilter(): { filterByKind?: string[] } {
334 return unusedKind === undefined ? {} : { filterByKind: [unusedKind] };
335}
336
337function codeFor(tab: QueryTab, direction: Direction, path: string): string {
338 switch (tab) {
339 case 'status':
340 return 'return await api.ping()';
341 case 'diagnose':
342 return 'const [ping, caps] = await Promise.all([api.ping(), api.getCapabilities()]); return { ping, caps }';
343 case 'deps':
344 return `return await api.${direction === 'dependencies' ? 'getDependencies' : 'getDependents'}({ filePath: ${JSON.stringify(path)} })`;
345 case 'unused':
346 return orphanCode(unusedFilter());
347 case 'explore':
348 return searchCode(exploreQuery);
349 }
350}
351
352// The pane's state: module variables, lost on a hot reload, so every read has a default.
353let selected: Tab = 'status';
354let tint: Scheme = 'brand';
355let depsPath = '';
356let depsDirection: Direction = 'dependencies';
357let sessionCwd: string | undefined;
358let launchCwd: string | undefined;
359/**
360 * The project picked when the session's working directory is not a project
361 * (a workspace root above several). Kept across pane opens, unlike the rest,
362 * and used only while the session is still in `from`.
363 */
364let chosen: { from: string; root: string } | undefined;
365const cache = new Map<QueryTab, CodeIntelEnvelope>();
366const pending = new Set<QueryTab>();
367const generations = new Map<QueryTab, number>();
368/** The picker's per-project `getCapabilities` envelopes, by project root. */
369const details = new Map<string, CodeIntelEnvelope>();
370const detailsPending = new Set<string>();
371/** The kind `/constellation unused <kind>` asked for. Cleared by `reset()` only. */
372let unusedKind: string | undefined;
373// The unused picker's state, cleared with the tab by `drop('unused')`.
374const picked = new Set<string>();
375let morePages: OrphanRow[] = [];
376let nextOffset: number | undefined;
377let loadingMore = false;
378let handoffNote: string | undefined;
379/** The symbol the explorer searches for. Cleared by `reset()` only, since the search field sets it and then drops the tab. */
380let exploreQuery = '';
381// The explorer's state, cleared with the tab by `drop('explore')`.
382let focusHit: Hit | undefined;
383type Section = 'details' | 'usages' | 'impact' | 'calls';
384let section: Section = 'details';
385const drill = new Map<string, CodeIntelEnvelope>();
386const drillPending = new Set<string>();
387let exploreNote: string | undefined;
388/** How long a read of the stored counts waits for counts still being saved. */
389const SETTLE_MS = 1000;
390/** The session's counts and the stored ones, read together so the rows agree; `stored` is unset when the store cannot be read. */
391type Snapshot = { session: Buckets; stored: Stats | undefined };
392/** The Stats tab's counts: unset until the tab shows, then being read, then read. Cleared by `drop('stats')`. */
393let history: Snapshot | 'reading' | undefined;
394let historyRead = 0;
395
396/** The `$.store` key that remembers the project picked in `from`, across sessions. */
397function pickKey(from: string): string {
398 return `project:${from}`;
399}
400
401function drop(tab: Tab): void {
402 if (tab === 'stats') {
403 history = undefined;
404 historyRead += 1;
405 return;
406 }
407 cache.delete(tab);
408 pending.delete(tab);
409 generations.set(tab, (generations.get(tab) ?? 0) + 1);
410 if (tab === 'unused') {
411 picked.clear();
412 morePages = [];
413 nextOffset = undefined;
414 loadingMore = false;
415 handoffNote = undefined;
416 }
417 if (tab === 'explore') {
418 focusHit = undefined;
419 section = 'details';
420 drill.clear();
421 drillPending.clear();
422 exploreNote = undefined;
423 }
424}
425
426function reset(): void {
427 for (const tab of TABS) drop(tab);
428 unusedKind = undefined;
429 exploreQuery = '';
430 selected = 'status';
431 depsPath = '';
432 depsDirection = 'dependencies';
433 sessionCwd = undefined;
434 launchCwd = undefined;
435 details.clear();
436 detailsPending.clear();
437}
438
439/** The directory queries run in: the picked project while the session stays where it was picked. */
440function target(cwd: string): string {
441 return chosen?.from === cwd ? chosen.root : cwd;
442}
443
444/**
445 * Runs the tab's query and caches the envelope. A result that lands after its
446 * tab was dropped (refresh, a new path, the pane closing) is discarded. The
447 * redraw is asked for once the envelope is cached.
448 */
449async function runQuery($: EngineInterface, tab: QueryTab): Promise<void> {
450 const generation = generations.get(tab) ?? 0;
451 pending.add(tab);
452 let envelope: CodeIntelEnvelope;
453 try {
454 const cwd = sessionCwd ?? target(await $.session.cwd());
455 envelope = await codeIntel(
456 { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
457 codeFor(tab, depsDirection, depsPath),
458 { cwd },
459 );
460 } catch (error) {
461 envelope = { success: false, error: { code: 'MCP_CALL_FAILED', message: error instanceof Error ? error.message : String(error) } };
462 }
463 if ((generations.get(tab) ?? 0) !== generation) return;
464 pending.delete(tab);
465 cache.set(tab, envelope);
466 if (tab === 'unused' && envelope.success) nextOffset = orphanPage(envelope.result).nextOffset;
467 $.ui.invalidate('ui.render');
468}
469
470/**
471 * The session's counts with the stored ones, deleting the entries past their 30
472 * days. Counts are saved in the background, so it first waits, for at most
473 * `SETTLE_MS`, for the saves still running: today's row is then never behind
474 * the session's. With no store only the session's counts come back.
475 */
476async function readStats($: EngineInterface): Promise<Snapshot> {
477 try {
478 await withinDeadline((ms, o) => $.clock.sleep(ms, o), settled(), SETTLE_MS, new AbortController().signal);
479 } catch {
480 // No timer: the stored counts are read as they are.
481 }
482 const session = sessionCounts();
483 try {
484 return { session, stored: await loadStats(await $.clock.now(), await $.store.keys(), (k) => $.store.get(k), (k) => $.store.delete(k)) };
485 } catch {
486 return { session, stored: undefined };
487 }
488}
489
490/** Reads the Stats tab's counts; a read that lands after the tab was dropped is discarded. */
491async function readHistory($: EngineInterface): Promise<void> {
492 const read = (historyRead += 1);
493 history = 'reading';
494 const snapshot = await readStats($);
495 if (historyRead !== read) return;
496 history = snapshot;
497 $.ui.invalidate('ui.render');
498}
499
500/** Reads one symbol's details, usages, impact and call graph; a result that lands after the explorer was dropped is discarded. */
501async function runDrill($: EngineInterface, id: string, symbolKind: string): Promise<void> {
502 drillPending.add(id);
503 let envelope: CodeIntelEnvelope;
504 try {
505 const cwd = sessionCwd ?? target(await $.session.cwd());
506 envelope = await codeIntel({ connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) }, drillCode(id, symbolKind), { cwd });
507 } catch (error) {
508 envelope = { success: false, error: { code: 'MCP_CALL_FAILED', message: error instanceof Error ? error.message : String(error) } };
509 }
510 if (!drillPending.delete(id)) return;
511 drill.set(id, envelope);
512 $.ui.invalidate('ui.render');
513}
514
515/** Reads the next page of unused exports; a page that lands after the tab was dropped is discarded. */
516async function loadMore($: EngineInterface): Promise<void> {
517 if (loadingMore || nextOffset === undefined) return;
518 const generation = generations.get('unused') ?? 0;
519 const code = orphanCode({ ...unusedFilter(), limit: 50, offset: nextOffset });
520 loadingMore = true;
521 $.ui.invalidate('ui.render');
522 let envelope: CodeIntelEnvelope;
523 try {
524 const cwd = sessionCwd ?? target(await $.session.cwd());
525 envelope = await codeIntel({ connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) }, code, { cwd });
526 } catch (error) {
527 envelope = { success: false, error: { code: 'MCP_CALL_FAILED', message: error instanceof Error ? error.message : String(error) } };
528 }
529 if ((generations.get('unused') ?? 0) !== generation) return;
530 loadingMore = false;
531 if (envelope.success) {
532 const page = orphanPage(envelope.result);
533 morePages = [...morePages, ...page.rows];
534 nextOffset = page.nextOffset;
535 } else {
536 handoffNote = 'Could not load more. Try again.';
537 }
538 $.ui.invalidate('ui.render');
539}
540
541/**
542 * An error in the pane: the error badge and the headline in bold, then,
543 * indented under it, the detail and notes dim, the numbered steps with each
544 * command bold, and the docs link and the code last.
545 */
546function errorView(el: ElementTable, ex: Explanation, tint: Scheme): RenderElement {
547 const row = (label: string, value: RenderElement) =>
548 el.Box({ flexDirection: 'row', children: [el.Text({ dimColor: true, children: label.padEnd(7) }), value] });
549 const under: RenderElement[] = [];
550 if (ex.detail !== undefined || ex.notes.length > 0) {
551 under.push(
552 el.Box({
553 flexDirection: 'column',
554 children: [ex.detail, ...ex.notes].filter((t): t is string => t !== undefined).map((t) => el.Text({ dimColor: true, children: t })),
555 }),
556 );
557 }
558 if (ex.steps.length > 0) {
559 under.push(
560 el.Box({
561 flexDirection: 'column',
562 children: [
563 el.Text({ bold: true, children: 'Next steps' }),
564 ...ex.steps.map((step, i) =>
565 el.Box({ flexDirection: 'row', columnGap: 1, children: [el.Text({ dimColor: true, children: `${i + 1}.` }), el.Text({ bold: true, children: step })] }),
566 ),
567 ],
568 }),
569 );
570 }
571 under.push(
572 el.Box({
573 flexDirection: 'column',
574 children: [
575 ...(ex.docs === undefined ? [] : [row('Docs', el.Link({ href: ex.docs, label: ex.docs }))]),
576 row('Code', el.Text({ dimColor: true, children: ex.code })),
577 ],
578 }),
579 );
580 return el.Box({
581 flexDirection: 'column',
582 gap: 1,
583 children: [
584 el.Box({ flexDirection: 'row', columnGap: 1, children: [badge(el, '', forTheme(status('error'), tint)), el.Text({ bold: true, children: ex.title })] }),
585 el.Box({ flexDirection: 'column', gap: 1, paddingLeft: 2, children: under }),
586 ],
587 });
588}
589
590/** Reads one project's capabilities for the picker; a result that lands after the pane closed is dropped. */
591async function runDetail($: EngineInterface, root: string): Promise<void> {
592 detailsPending.add(root);
593 const envelope = await codeIntel(
594 { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
595 'return await api.getCapabilities()',
596 { cwd: root },
597 );
598 if (!detailsPending.delete(root)) return;
599 details.set(root, envelope);
600 $.ui.invalidate('ui.render');
601}
602
603export function registerCommand(on: On): void {
604 on('session.start', async ($, e, next) => {
605 const ports: OnboardingPorts = {
606 run: (argv, init) => $.process.run(argv, init),
607 exists: (p) => $.fs.exists(p),
608 read: (p) => $.fs.read(p),
609 envSet: (key) => $.env.set('CONSTELLATION_ACCESS_KEY', key),
610 after: (ms, fn) => {
611 $.clock.after(ms, fn);
612 },
613 mcp: { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
614 reload: () => $.command.run({ command: 'reload-plugins' }),
615 toast: (text) => $.ui.toast(text),
616 invalidate: () => $.ui.invalidate('ui.render'),
617 log: async (text) => {
618 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
619 },
620 };
621 // A key the CLI stored is set before the session goes on, so the MCP server can start with it.
622 // A `-p` or SDK run skips the read-back: no one is at the prompt, and a login shell can take seconds.
623 let found: FoundKey | undefined;
624 try {
625 if (e.isInteractive && !isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) {
626 found = await readStoredKeyAtStart(e.cwd, ports);
627 if (found !== undefined) await ports.envSet(found.key);
628 } else {
629 await rememberRepo(e.cwd, ports.exists);
630 }
631 } catch {
632 // The onboarding never fails the session or skips the registration.
633 found = undefined;
634 }
635 const r = await next(e);
636 // The project to ping and watch: the stored key's, else the session's when its key is set.
637 let root: string | null = null;
638 try {
639 if (found !== undefined) root = found.projectRoot;
640 else if (isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) root = await projectRoot(e.cwd, ports.exists);
641 } catch {
642 root = null;
643 }
644 // With showFreshness off, a stored key's connection check still runs; nothing else does.
645 if (root !== null && (found !== undefined || showsFreshness())) {
646 const at = root;
647 const again = () => recheck(ports.run, ports.invalidate, ports.log);
648 track(at);
649 try {
650 // Never await code_intel in session.start: the ping runs on a timer. Only a stored key's ping acts on
651 // AUTH_ERROR and the index button; either answer tells the freshness indicator what is indexed.
652 $.clock.after(0, () => {
653 const observe = (envelope: CodeIntelEnvelope) => void observeEnvelope(envelope, at, ports.run, ports.invalidate, ports.log).catch(() => undefined);
654 const pinged =
655 found !== undefined
656 ? checkConnection(at, ports, observe)
657 : pingProject(at, ports).then((envelope) => {
658 if (envelope !== undefined) observe(envelope);
659 });
660 void pinged.then(again).catch(() => undefined);
661 });
662 } catch {
663 // No timer: the agent's own calls still bring up the band and the indicator.
664 }
665 try {
666 // Every five minutes git alone compares the checkout again; code_intel is never called on the timer.
667 if (showsFreshness()) startTicks(() => $.clock.every(5 * 60_000, () => void again().catch(() => undefined)));
668 } catch {
669 // No timer: git commands the agent runs and code_intel answers still update the indicator.
670 }
671 }
672 try {
673 await $.command.register({
674 name: COMMAND,
675 description: 'Constellation status, diagnose, deps, unused code, symbol explorer and code_intel usage stats',
676 argumentHint: '[status|diagnose|deps <file>|unused [kind]|explore [query]|stats]',
677 immediate: true,
678 });
679 } catch {
680 // Registration refused: the Markdown commands still work.
681 }
682 return r;
683 });
684
685 on('command.run', { command: COMMAND }, async ($, e) => {
686 const { tab, path, kind, query } = parseArgs(e.args);
687 const draws = canDraw(await $.session.surfaces());
688 if (tab === 'stats' && !draws) {
689 const { session, stored } = await readStats($);
690 return { text: [branded(TAB_LABEL[tab]), ...statsLines(session, stored).map((l) => `- ${l}`)].join('\n') };
691 }
692 const cwd = await $.session.cwd();
693 if (chosen?.from !== cwd) {
694 try {
695 const saved = await $.store.get(pickKey(cwd));
696 if (typeof saved === 'string') chosen = { from: cwd, root: saved };
697 } catch {
698 // Nothing saved, or the store is unavailable: the picker asks again.
699 }
700 }
701 const dir = target(cwd);
702 unusedKind = kind;
703 exploreQuery = query ?? '';
704 if (!draws && tab !== 'stats') {
705 if (tab === 'deps' && path === undefined) return { text: branded('Usage: /constellation deps <file>') };
706 if (tab === 'explore' && query === undefined) return { text: branded('Usage: /constellation explore <query>') };
707 const envelope = await codeIntel(
708 { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
709 codeFor(tab, 'dependencies', path ?? ''),
710 { cwd: dir },
711 );
712 const summary = summarize(tab, envelope, { path, project: projectName(dir), query });
713 const meta = metadata(envelope);
714 if (summary.explanation !== undefined) return { text: [branded(TAB_LABEL[tab]), ...summary.lines].join('\n') };
715 const body = [...textLines(summary.lines), ...(meta === undefined ? [] : [meta])];
716 return { text: [branded(TAB_LABEL[tab]), ...body.map((l) => `- ${l.trim()}`)].join('\n') };
717 }
718 reset();
719 unusedKind = kind;
720 exploreQuery = query ?? '';
721 selected = tab;
722 depsPath = path ?? '';
723 sessionCwd = dir;
724 launchCwd = cwd;
725 try {
726 tint = scheme((await $.config.list()).find((r) => r.key === 'theme')?.value);
727 } catch {
728 tint = scheme(undefined);
729 }
730 await $.ui.open({ id: PANE, title: 'Constellation', focus: true, closeOnEscape: true });
731 $.ui.invalidate('ui.render');
732 return {};
733 });
734
735 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e, next) => {
736 if (e.surface !== 'terminal' && e.surface !== 'desktop') return next(e);
737 const el = $.ui.resolve(e);
738 const envelope = selected === 'stats' ? undefined : cache.get(selected);
739 const needsPath = selected === 'deps' && depsPath === '';
740 const needsQuery = selected === 'explore' && exploreQuery === '';
741 if (selected === 'stats') {
742 if (history === undefined) void readHistory($);
743 } else if (envelope === undefined && !pending.has(selected) && !needsPath && !needsQuery) void runQuery($, selected);
744 const isPending = selected !== 'stats' && pending.has(selected);
745
746 const redraw = (): void => $.ui.invalidate('ui.render');
747 // In a row that may be wider than the pane, the name and kind keep their width and a long location
748 // shortens in the middle, instead of every item shrinking and wrapping onto a second line.
749 const fixed = (children: RenderElement[]): RenderElement => el.Box({ flexDirection: 'row', columnGap: 1, flexShrink: 0, children });
750 const place = (text: string): RenderElement => el.Box({ flexShrink: 1, children: [el.Text({ dimColor: true, wrap: 'truncate-middle', children: text })] });
751 // Desktop has no monospace grid, so rows padded into columns do not line up there: it gets markdown tables.
752 const grid = e.surface !== 'desktop';
753 // The selected one of a row of tab-like buttons: `▸` in the terminal, Desktop's own primary button there.
754 // A checkbox: `[x]` in the terminal; on Desktop ballot boxes, the check forced to text (U+FE0E), not an emoji.
755 const check = (isChecked: boolean): string => (grid ? (isChecked ? '[x]' : '[ ]') : isChecked ? '\u2611\uFE0E' : '\u2610');
756 const choice = (isSelected: boolean, label: string): Pick<ButtonProps, 'label' | 'plain' | 'variant'> =>
757 grid ? { label: isSelected ? `▸ ${label}` : label, plain: true } : isSelected ? { label, variant: 'primary' } : { label, plain: true };
758 // A table of Boxes, each column a share of the width, so cells keep their colors and still line up without a
759 // monospace grid. Never markdown: the cells hold graph text, which a markdown parser would read as links.
760 const boxTable = (widths: readonly string[], rows: readonly { key?: string; cells: readonly RenderElement[] }[], head?: readonly string[]): RenderElement => {
761 const line = (cells: readonly RenderElement[], key?: string): RenderElement =>
762 el.Box({ ...(key === undefined ? {} : { key }), flexDirection: 'row', children: cells.map((cell, i) => el.Box({ width: widths[i] ?? 'auto', children: [cell] })) });
763 return el.Box({
764 flexDirection: 'column',
765 children: [...(head === undefined ? [] : [line(head.map((h) => el.Text({ bold: true, children: h })))]), ...rows.map((r) => line(r.cells, r.key))],
766 });
767 };
768 // Label and value rows, the label dim: the Desktop form of rows padded into a label column.
769 const factTable = (rows: readonly (readonly [string, string])[]): RenderElement =>
770 boxTable(['25%', '75%'], rows.map(([label, value]) => ({ cells: [el.Text({ dimColor: true, children: label }), el.Text({ children: value })] })));
771 const showDeps = (path: string): void => {
772 depsPath = path;
773 drop('deps');
774 redraw();
775 };
776 const accent = paint(palette.nebula, tint);
777 const pick = async (project: string): Promise<void> => {
778 const from = launchCwd ?? (await $.session.cwd());
779 chosen = { from, root: project };
780 sessionCwd = project;
781 for (const tab of TABS) drop(tab);
782 redraw();
783 try {
784 await $.store.set(pickKey(from), project);
785 } catch {
786 // Not remembered across sessions; this session keeps the pick.
787 }
788 };
789 const switchProject = async (): Promise<void> => {
790 const from = launchCwd ?? (await $.session.cwd());
791 chosen = undefined;
792 sessionCwd = from;
793 for (const tab of TABS) drop(tab);
794 redraw();
795 try {
796 await $.store.delete(pickKey(from));
797 } catch {
798 // A pick left in the store is offered again and can be switched again.
799 }
800 };
801 const summary = selected === 'stats' || envelope === undefined ? undefined : summarize(selected, envelope, { direction: depsDirection, path: depsPath, project: projectName(sessionCwd), query: exploreQuery });
802
803 const picking = summary?.items.some((i) => i.project !== undefined) ?? false;
804
805 const body: RenderElement[] = [];
806 if (selected === 'deps') {
807 body.push(
808 el.Input({
809 key: 'deps-path',
810 label: 'File',
811 value: depsPath,
812 placeholder: 'path/to/file.ts',
813 submitLabel: 'show',
814 onSubmit: (value) => showDeps(value.trim()),
815 }),
816 el.Select({
817 key: 'deps-direction',
818 label: 'Show',
819 options: [
820 { value: 'dependencies', label: 'Dependencies (what this file imports)' },
821 { value: 'dependents', label: 'Dependents (what imports this file)' },
822 ],
823 value: depsDirection,
824 onSelect: (value) => {
825 if (value !== 'dependencies' && value !== 'dependents') return;
826 if (value === depsDirection) return;
827 depsDirection = value;
828 drop('deps');
829 redraw();
830 },
831 }),
832 );
833 }
834 if (selected === 'unused' && !picking) {
835 body.push(
836 el.Select({
837 key: 'unused-kind',
838 label: 'Kind',
839 options: [
840 { value: ALL_KINDS, label: 'All kinds' },
841 ...[...UNUSED_KINDS, ...(unusedKind === undefined || UNUSED_KINDS.includes(unusedKind) ? [] : [unusedKind])].map((k) => ({ value: k, label: k })),
842 ],
843 value: unusedKind ?? ALL_KINDS,
844 onSelect: (value) => {
845 const chosenKind = value === ALL_KINDS ? undefined : value;
846 if (chosenKind === unusedKind) return;
847 unusedKind = chosenKind;
848 drop('unused');
849 redraw();
850 },
851 }),
852 );
853 }
854 const hit = focusHit;
855 if (selected === 'explore' && hit === undefined) {
856 body.push(
857 el.Input({
858 key: 'explore-query',
859 label: 'Symbol',
860 value: exploreQuery,
861 placeholder: 'name',
862 submitLabel: 'search',
863 autoFocus: true,
864 onSubmit: (value) => {
865 exploreQuery = value.trim();
866 drop('explore');
867 redraw();
868 },
869 }),
870 );
871 }
872 const firstPage = selected === 'unused' && envelope?.success === true ? orphanPage(envelope.result) : undefined;
873 const loaded = firstPage === undefined ? [] : [...firstPage.rows, ...morePages];
874 const pickedRows = loaded.filter((r) => picked.has(r.symbolId));
875 const toggle = (ids: readonly string[], select: boolean): void => {
876 for (const id of ids) {
877 if (select) picked.add(id);
878 else picked.delete(id);
879 }
880 redraw();
881 };
882 if (firstPage !== undefined) {
883 if (loaded.length === 0) {
884 body.push(el.Text({ dimColor: true, children: 'No unused exports found' }));
885 } else {
886 body.push(
887 el.Box({
888 flexDirection: 'column',
889 children: [
890 el.Box({
891 flexDirection: 'row',
892 columnGap: 2,
893 children: [
894 el.Text({ bold: true, children: `${picked.size} selected` }),
895 el.Text({ dimColor: true, children: `of ${grouped(firstPage.total ?? loaded.length)} unused exports` }),
896 el.Button({ key: 'select-all', label: 'Select all', hotkey: 'a', plain: true, onPress: () => toggle(loaded.map((r) => r.symbolId), true) }),
897 ],
898 }),
899 // The list's keys sit here, not in the footer: a long list scrolls the footer out of view.
900 // Desktop shows each hotkey on its button and is used with a pointer, so the key hints are the terminal's.
901 ...(grid ? [el.Text({ dimColor: true, children: `tab/shift+tab move · enter toggle${picked.size > 0 ? ' · h hand off' : ''}` })] : []),
902 ...(handoffNote === undefined ? [] : [el.Text({ dimColor: true, children: handoffNote })]),
903 ],
904 }),
905 );
906 for (const [file, rows] of byFile(loaded)) {
907 const ids = rows.map((r) => r.symbolId);
908 const all = ids.every((id) => picked.has(id));
909 body.push(
910 el.Button({ key: `orphan-file:${file}`, label: `${check(all)} ${file}`, plain: true, onPress: () => toggle(ids, !all) }),
911 ...rows.map((row) =>
912 // The file is the header above, so a row names only its line. Desktop: the name is part of the
913 // checkbox, so it is a larger target, and the columns are shares of the width.
914 !grid
915 ? el.Box({
916 key: `row:${row.symbolId}`,
917 flexDirection: 'row',
918 paddingLeft: 2,
919 children: [
920 el.Box({
921 width: '50%',
922 children: [
923 el.Button({
924 key: `orphan:${row.symbolId}`,
925 label: `${check(picked.has(row.symbolId))} ${row.name}`,
926 plain: true,
927 onPress: () => toggle([row.symbolId], !picked.has(row.symbolId)),
928 }),
929 ],
930 }),
931 el.Box({ width: '25%', children: [badge(el, '', forTheme(kind(row.kind), tint))] }),
932 el.Box({ width: '25%', children: row.lineEnd === undefined ? [] : [el.Text({ dimColor: true, children: `line ${row.lineEnd}` })] }),
933 ],
934 })
935 : el.Box({
936 key: `row:${row.symbolId}`,
937 flexDirection: 'row',
938 columnGap: 1,
939 paddingLeft: 2,
940 children: [
941 fixed([
942 el.Button({
943 key: `orphan:${row.symbolId}`,
944 label: check(picked.has(row.symbolId)),
945 plain: true,
946 onPress: () => toggle([row.symbolId], !picked.has(row.symbolId)),
947 }),
948 el.Text({ children: row.name }),
949 badge(el, '', forTheme(kind(row.kind), tint)),
950 ]),
951 ...(row.lineEnd === undefined ? [] : [el.Text({ dimColor: true, children: `line ${row.lineEnd}` })]),
952 ],
953 }),
954 ),
955 );
956 }
957 if (nextOffset !== undefined && !loadingMore) {
958 body.push(el.Button({ key: 'load-more', label: 'Load more', plain: true, onPress: () => loadMore($) }));
959 }
960 if (loadingMore) body.push(badge(el, 'loading more', forTheme(status('pending'), tint)));
961 }
962 } else if (selected === 'stats') {
963 // Every row from one snapshot; while it is being read, the session's counts as they stand.
964 const snapshot = typeof history === 'object' ? history : undefined;
965 if (!grid) {
966 body.push(
967 boxTable(
968 ['24%', '19%', '19%', '19%', '19%'],
969 statsCells(snapshot?.session ?? sessionCounts(), snapshot?.stored).map(({ label, figures: f }) => ({
970 key: `stats:${label}`,
971 cells: [
972 el.Text({ dimColor: true, children: label }),
973 el.Text({ children: f.calls }),
974 el.Text({ children: f.symbol }),
975 el.Text({ dimColor: true, children: f.literal }),
976 el.Text({ bold: true, children: f.share }),
977 ],
978 })),
979 ['', 'code_intel calls', 'Symbol-like', 'Literal', SHARE_LABEL],
980 ),
981 );
982 } else {
983 for (const row of statRows(snapshot?.session ?? sessionCounts(), snapshot?.stored)) {
984 const f = figures(row.counts);
985 body.push(
986 el.Box({
987 key: `stats:${row.label}`,
988 flexDirection: 'row',
989 children: [
990 el.Text({ dimColor: true, children: row.label.padEnd(LABEL_WIDTH) }),
991 el.Box({
992 flexDirection: 'column',
993 children: [
994 el.Box({
995 flexDirection: 'row',
996 columnGap: 2,
997 flexWrap: 'wrap',
998 children: [
999 el.Text({ children: f.calls }),
1000 el.Text({ children: f.symbol }),
1001 el.Text({ dimColor: true, children: f.literal }),
1002 el.Box({
1003 flexDirection: 'row',
1004 columnGap: 1,
1005 children: [el.Text({ bold: true, children: f.share }), el.Text({ dimColor: true, children: SHARE_LABEL })],
1006 }),
1007 ],
1008 }),
1009 ...(row.split === undefined ? [] : [el.Text({ dimColor: true, children: row.split })]),
1010 ],
1011 }),
1012 ],
1013 }),
1014 );
1015 }
1016 }
1017 if (snapshot === undefined) body.push(badge(el, 'reading the stored counts', forTheme(status('pending'), tint)));
1018 else if (snapshot.stored === undefined) body.push(el.Text({ dimColor: true, children: UNREAD_NOTE }));
1019 body.push(el.Text({ dimColor: true, children: SHARE_NOTE }));
1020 } else if (selected === 'explore' && summary !== undefined && summary.explanation === undefined) {
1021 const labeled = (label: string, value: string): RenderElement =>
1022 el.Box({ flexDirection: 'row', children: [el.Text({ dimColor: true, children: label.padEnd(LABEL_WIDTH) }), el.Text({ children: value })] });
1023 const stamp = (from: CodeIntelEnvelope | undefined): RenderElement[] => {
1024 const parts: string[] = [];
1025 if (from?.time !== undefined) parts.push(`${from.time} ms`);
1026 if (from?.asOfCommit) parts.push(`as of ${from.asOfCommit.slice(0, 7)}`);
1027 return parts.length === 0 ? [] : [el.Text({ dimColor: true, children: parts.join(' · ') })];
1028 };
1029 if (hit === undefined) {
1030 const found = rankExact(exploreQuery, hits(envelope?.result)).slice(0, EXPLORE_ROWS);
1031 if (found.length === 0) body.push(el.Text({ dimColor: true, children: 'No symbols match' }));
1032 for (const h of found) {
1033 body.push(
1034 el.Box({
1035 key: `row:${h.id}`,
1036 flexDirection: 'row',
1037 columnGap: 1,
1038 children: [
1039 fixed([
1040 el.Button({
1041 key: `hit:${h.id}`,
1042 label: h.name,
1043 plain: true,
1044 onPress: () => {
1045 focusHit = h;
1046 section = 'details';
1047 if (!drill.has(h.id) && !drillPending.has(h.id)) void runDrill($, h.id, h.kind);
1048 redraw();
1049 },
1050 }),
1051 badge(el, '', forTheme(kind(h.kind), tint)),
1052 ]),
1053 place(where(h)),
1054 ],
1055 }),
1056 );
1057 }
1058 body.push(...stamp(envelope));
1059 } else {
1060 const drilled = drill.get(hit.id);
1061 const result = isRecord(drilled?.result) ? drilled.result : {};
1062 const aliasNote = el.Text({ dimColor: true, children: 'Callers importing through path aliases or export * barrels may be missing.' });
1063 const sections: [Section, string][] = [
1064 ['details', 'Details'],
1065 ['usages', 'Usages'],
1066 ['impact', 'Impact'],
1067 // Only a kind with a call graph offers it; core refuses the read for any other.
1068 ...(hasCallGraph(hit.kind) ? [['calls', 'Call graph'] as [Section, string]] : []),
1069 ];
1070 body.push(
1071 el.Box({
1072 flexDirection: 'column',
1073 gap: 1,
1074 children: [
1075 el.Box({
1076 flexDirection: 'column',
1077 children: [
1078 el.Text({ dimColor: true, children: `results for ${exploreQuery}` }),
1079 el.Box({
1080 flexDirection: 'row',
1081 columnGap: 1,
1082 children: [
1083 fixed([badge(el, '', forTheme(kind(hit.kind), tint)), el.Text({ bold: true, children: hit.name })]),
1084 place(where(hit)),
1085 fixed([
1086 el.Button({
1087 key: 'copy-location',
1088 label: 'Copy location',
1089 plain: true,
1090 dimColor: true,
1091 onPress: async (press) => {
1092 const { isCopied } = await $.ui.copy({ text: where(hit), surface: press.surface });
1093 exploreNote = isCopied ? 'Copied' : 'Could not copy';
1094 redraw();
1095 },
1096 }),
1097 ]),
1098 ],
1099 }),
1100 ...(exploreNote === undefined ? [] : [el.Text({ dimColor: true, children: exploreNote })]),
1101 ],
1102 }),
1103 el.Box({
1104 flexDirection: 'row',
1105 columnGap: 2,
1106 children: sections.map(([name, label]) =>
1107 el.Button({
1108 key: `section-${name}`,
1109 ...choice(name === section, label),
1110 onPress: () => {
1111 section = name;
1112 redraw();
1113 },
1114 }),
1115 ),
1116 }),
1117 drilled === undefined
1118 ? badge(el, 'querying Constellation', forTheme(status('pending'), tint))
1119 : !drilled.success
1120 ? errorView(el, summarize('explore', drilled).explanation ?? explain({ code: 'UNKNOWN', message: 'The request failed' }), tint)
1121 : el.Box({
1122 flexDirection: 'column',
1123 children: (() => {
1124 if (section === 'details') {
1125 const lines = detailLines(result['details']);
1126 if (lines.length === 0) return [el.Text({ dimColor: true, children: 'No details returned' })];
1127 return grid ? lines.map((l) => el.Text({ children: l })) : [factTable(detailRows(result['details']))];
1128 }
1129 if (section === 'usages') {
1130 const lines = usageLines(result['usages']);
1131 if (lines.length === 0) return [el.Text({ dimColor: true, children: 'No usages found' }), aliasNote];
1132 if (grid) return [...lines.map((l) => el.Text({ children: l })), aliasNote];
1133 const total = usageTotal(result['usages']);
1134 const rows = usageRows(result['usages']);
1135 return [
1136 ...(total === undefined ? [] : [el.Text({ children: total })]),
1137 ...(rows.length === 0 ? [] : [boxTable(['75%', '25%'], rows.map((r) => ({ cells: r.map((t) => el.Text({ children: t })) })), ['Location', 'Usage'])]),
1138 aliasNote,
1139 ];
1140 }
1141 if (section === 'impact') {
1142 const view = impactView(result['impact']);
1143 const facts: [string, string][] = [
1144 ...(view.files === undefined ? [] : [['Files', String(view.files)] as [string, string]]),
1145 ...(view.direct === undefined ? [] : [['Direct', String(view.direct)] as [string, string]]),
1146 ...(view.transitive === undefined ? [] : [['Transitive', String(view.transitive)] as [string, string]]),
1147 ...(view.tests === undefined && view.production === undefined
1148 ? []
1149 : [['Files', `${view.tests ?? 0} test · ${view.production ?? 0} production`] as [string, string]]),
1150 ];
1151 return [
1152 ...(view.riskLevel === undefined ? [] : [badge(el, '', forTheme(risk(view.riskLevel), tint))]),
1153 ...(grid ? facts.map(([label, value]) => labeled(label, value)) : facts.length === 0 ? [] : [factTable(facts)]),
1154 ...(grid
1155 ? view.top.map((d) => badge(el, d.name, forTheme(kind(d.kind), tint)))
1156 : view.top.length === 0
1157 ? []
1158 : [boxTable(['60%', '40%'], view.top.map((d) => ({ cells: [el.Text({ children: d.name }), badge(el, '', forTheme(kind(d.kind), tint))] })), ['Dependent', 'Kind'])]),
1159 aliasNote,
1160 ];
1161 }
1162 const tree = callTree(result['calls']);
1163 return tree.length === 0
1164 ? [el.Text({ dimColor: true, children: 'No callers or callees found' })]
1165 : tree.map((l) => el.Text({ ...(l.depth === 0 ? { bold: true } : {}), children: `${' '.repeat(l.depth)}${l.text}` }));
1166 })(),
1167 }),
1168 ],
1169 }),
1170 ...stamp(drilled),
1171 );
1172 }
1173 } else if (summary?.explanation !== undefined && !summary.items.some((i) => i.project !== undefined)) {
1174 body.push(errorView(el, summary.explanation, tint));
1175 } else if (summary !== undefined) {
1176 let row = 0;
1177 // On Desktop, each run of labeled facts is one table.
1178 const facts: RenderElement[][] = [];
1179 const flush = (): void => {
1180 if (facts.length > 0) body.push(boxTable(['25%', '75%'], facts.splice(0).map((cells) => ({ cells }))));
1181 };
1182 for (const item of summary.items) {
1183 const path = item.path;
1184 const project = item.project;
1185 if (!grid && item.label !== undefined && project === undefined && path === undefined) {
1186 const tone =
1187 item.badge === undefined ? undefined : forTheme(item.badge.kind === 'status' ? status(item.badge.value) : kind(item.badge.value), tint);
1188 facts.push([el.Text({ dimColor: true, children: item.label }), tone === undefined ? el.Text({ children: item.text }) : badge(el, item.text, tone)]);
1189 continue;
1190 }
1191 flush();
1192 if (project !== undefined) {
1193 // The tabs are hidden while picking, so the digits are free for the rows.
1194 const n = row++;
1195 if (!details.has(project) && !detailsPending.has(project)) void runDetail($, project);
1196 body.push(
1197 el.Box({
1198 key: `row:${project}`,
1199 flexDirection: 'row',
1200 columnGap: 2,hooks/describe.ts 73 lines1import type { EngineInterface, On } from 'claude-code';
2import { freshnessLine, observeEnvelope, recheck, track } from './freshness';
3import type { Run } from './freshness';
4import { canDraw, isConfigured, projectRoot } from './lib';
5import type { McpPort } from './lib';
6import { pingProject } from './onboarding';
7
8/**
9 * Appended to the description of every search tool the model sees. Constant, so
10 * the cached description keeps the prompt cache valid.
11 */
12export const GUIDANCE =
13 '\n\nFor symbol definitions, references, dependents, call graphs or impact, use the code_intel tool. Grep, Glob and grep or rg in the shell are for literal text such as error messages, config values, log strings and comments.';
14
15/**
16 * The last gate result a description was built under; undefined until one is.
17 * Once the guidance is in, it stays: it is harmless outside a project, and
18 * taking it out again would change the tools block and rewrite the prompt cache
19 * every time Claude `cd`s out of and back into an indexed project.
20 */
21let lastGate: boolean | undefined;
22
23/** True when the access key starts with `ak:` and `cwd` sits inside an indexed project. */
24async function gateOpen($: EngineInterface, cwd: string): Promise<boolean> {
25 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return false;
26 return (await projectRoot(cwd, (p) => $.fs.exists(p))) !== null;
27}
28
29export function registerDescribe(on: On): void {
30 on('tool.describe', { tool: /^(Grep|Glob|Bash)$/ }, async ($, e, next) => {
31 const r = await next(e);
32 const open = lastGate === true || (await gateOpen($, await $.session.cwd()));
33 lastGate = open;
34 if (!open) return r;
35 return { ...r, description: r.description + GUIDANCE };
36 });
37
38 on('classic.CwdChanged', async ($, e, next) => {
39 const r = await next(e);
40 // The freshness indicator follows the project: a new one is pinged for what is indexed, the same one compared again.
41 try {
42 const root = isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY')) ? await projectRoot(e.new_cwd, (p) => $.fs.exists(p)) : null;
43 if (root !== null) {
44 const run: Run = (argv, init) => $.process.run(argv, init);
45 const invalidate = () => $.ui.invalidate('ui.render');
46 const log = async (text: string) => {
47 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
48 };
49 const showing = freshnessLine(Date.now()) !== undefined;
50 if (track(root)) {
51 // The last project's line goes.
52 if (showing) invalidate();
53 const mcp: McpPort = { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) };
54 void pingProject(root, { read: (p) => $.fs.read(p), mcp })
55 .then((envelope) => (envelope === undefined ? undefined : observeEnvelope(envelope, root, run, invalidate, log)))
56 .then(() => recheck(run, invalidate, log))
57 .catch(() => undefined);
58 } else {
59 void recheck(run, invalidate, log).catch(() => undefined);
60 }
61 }
62 } catch {
63 // The indicator stays as it was; the gate below still runs.
64 }
65 if (lastGate !== false) return r;
66 if (await gateOpen($, e.new_cwd)) {
67 lastGate = true;
68 $.ui.invalidate('tool.describe');
69 }
70 return r;
71 });
72}
73hooks/freshness.ts 305 lines1import type { ElementTable, On, PluginOptions, ProcessRunInit, ProcessRunResult, RenderElement, Timer } from 'claude-code';
2import { explain } from './explain';
3import { canDraw, type CodeIntelEnvelope, type CodeIntelError, GIT, GIT_ENV, GIT_TIMEOUT_MS, isConfigured, plural, stringArg } from './lib';
4import { badge, brandMark, branded, forTheme, status } from './theme';
5import type { Scheme } from './theme';
6
7/** Runs a command, as `$.process.run`. */
8export type Run = (argv: readonly string[], init: ProcessRunInit) => Promise<Pick<ProcessRunResult, 'exitCode' | 'stdout'>>;
9
10/** Writes the line where nothing draws it. A promise it returns may reject; that is ignored. */
11export type Log = (text: string) => Promise<void> | void;
12
13/** What the graph was indexed at, from a code_intel envelope. */
14type Index = { asOfCommit: string; lastIndexedAt?: string; branch?: string };
15
16/** What the working tree is at. `behind` is undefined when the count could not be taken. */
17type Local = { head: string; branch: string; behind: number | undefined };
18
19/** What the indicator shows, or nothing when the graph matches the checkout. */
20export type FreshnessView =
21 | { kind: 'behind'; behind: number; lastIndexedAt?: string }
22 | { kind: 'mismatch'; asOfCommit: string; lastIndexedAt?: string }
23 | { kind: 'error'; failure: CodeIntelError; lastIndexedAt?: string };
24
25/** Error codes the onboarding band already shows, so the indicator stays quiet. */
26const ONBOARDING_CODES: ReadonlySet<string> = new Set(['AUTH_ERROR', 'PROJECT_NOT_INDEXED', 'NOT_CONFIGURED', 'MCP_UNAVAILABLE']);
27
28/** A commit id as git prints it. Anything else from the server never reaches a git argument. */
29const COMMIT = /^[0-9a-f]{7,64}$/i;
30
31const SEP = ' · ';
32
33/**
34 * A git command that moves HEAD or changes the tree: `git`, then options such
35 * as `-C dir`, then the subcommand, with no `;`, `&`, `|` or line break
36 * between them, so `cd x && git commit` counts and `echo git; commit` does not.
37 */
38const GIT_MOVES = /\bgit\s[^;&|\n]*\b(?:commit|pull|checkout|merge|rebase)\b/;
39
40/**
41 * Module state, cleared by `registerFreshness`. The index, the local checkout
42 * and the root describe the repository, so `resetFreshness` keeps them.
43 */
44let index: Index | undefined;
45let local: Local | undefined;
46let failure: CodeIntelError | undefined;
47let root: string | undefined;
48let logged = false;
49/** The latest recheck; an older one that finishes after a newer started drops its result. */
50let seq = 0;
51let timer: Timer | undefined;
52/** The `showFreshness` option. Off, no project is tracked, so no git runs and no line shows. */
53let enabled = true;
54
55/** How long ago `iso` was: "just now", "5m ago", "2h ago" or "3d ago". Undefined when `iso` is not a date. */
56function age(iso: string, now: number): string | undefined {
57 const then = Date.parse(iso);
58 if (Number.isNaN(then)) return undefined;
59 const minutes = Math.floor(Math.max(0, now - then) / 60000);
60 if (minutes < 1) return 'just now';
61 if (minutes < 60) return `${minutes}m ago`;
62 const hours = Math.floor(minutes / 60);
63 return hours < 24 ? `${hours}h ago` : `${Math.floor(hours / 24)}d ago`;
64}
65
66/**
67 * What to draw for the graph's commit against the checkout, or undefined for
68 * nothing. A failure with no index is an error. A HEAD that starts with the
69 * indexed commit (the envelope may carry a short id) is fresh.
70 * Otherwise HEAD is behind when the index commit has newer commits, and a
71 * mismatch when it has none or the count is unknown.
72 */
73export function freshnessView(
74 known: Index | undefined,
75 checkout: Local | undefined,
76 error: CodeIntelError | undefined,
77): FreshnessView | undefined {
78 if (known === undefined) {
79 return error === undefined ? undefined : { kind: 'error', failure: error };
80 }
81 if (checkout === undefined) return undefined;
82 if (checkout.head.startsWith(known.asOfCommit)) return undefined;
83 const shared = known.lastIndexedAt === undefined ? {} : { lastIndexedAt: known.lastIndexedAt };
84 if (checkout.behind !== undefined && checkout.behind > 0) return { kind: 'behind', behind: checkout.behind, ...shared };
85 return { kind: 'mismatch', asOfCommit: known.asOfCommit, ...shared };
86}
87
88/** What a behind or mismatch view says: its state words, and when the index was taken. */
89function stateParts(view: Exclude<FreshnessView, { kind: 'error' }>, now: number): { head: string; since?: string } {
90 const since = view.lastIndexedAt === undefined ? undefined : age(view.lastIndexedAt, now);
91 const head = view.kind === 'behind' ? `index ${plural(view.behind, 'commit')} behind` : `index at ${view.asOfCommit.slice(0, 7)}`;
92 return since === undefined ? { head } : { head, since: `indexed ${since}` };
93}
94
95/** The indicator as one plain line, for the band and for sessions that cannot draw. */
96export function freshnessText(view: FreshnessView, now: number): string {
97 if (view.kind === 'error') {
98 const ex = explain(view.failure);
99 return branded([`✗ ${view.failure.code}`, ex.title, ...(ex.steps[0] === undefined ? [] : [ex.steps[0]])].join(SEP));
100 }
101 const { head, since } = stateParts(view, now);
102 return branded([head, ...(since === undefined ? [] : [since])].join(SEP));
103}
104
105/**
106 * The indicator as one row: the brand mark in blue, then the state words in
107 * primary text and the index age dim. An error is its code as a red `✗` badge
108 * and its next step dim, or its headline when there is no step: the row is
109 * cut at the terminal's width, and the step is the part to act on. `el` is the
110 * table from `$.ui.resolve(e)`.
111 */
112export function freshnessBand(el: ElementTable, view: FreshnessView, tint: Scheme, now: number): RenderElement {
113 const dim = (text: string) => el.Text({ dimColor: true, children: text });
114 if (view.kind === 'error') {
115 const ex = explain(view.failure);
116 const step = ex.steps[0];
117 return el.Text({
118 wrap: 'truncate',
119 children: [
120 brandMark(el, tint),
121 SEP,
122 badge(el, '', forTheme({ ...status('error'), word: view.failure.code }, tint)),
123 step === undefined ? `${SEP}${ex.title}` : dim(`${SEP}${step}`),
124 ],
125 });
126 }
127 const { head, since } = stateParts(view, now);
128 return el.Text({
129 wrap: 'truncate',
130 children: [brandMark(el, tint), `${SEP}${head}`, ...(since === undefined ? [] : [dim(`${SEP}${since}`)])],
131 });
132}
133
134/**
135 * Where HEAD is against `asOfCommit`, in the project at `root`: its commit and
136 * branch (`HEAD` when detached), how many commits it is past `asOfCommit`, and
137 * whether the tree has changes. Undefined when git fails, so the indicator
138 * stays as it was.
139 */
140export async function compareLocal(run: Run, root: string, asOfCommit: string): Promise<Local | undefined> {
141 const git = (args: string[]): Promise<Pick<ProcessRunResult, 'exitCode' | 'stdout'>> =>
142 run([...GIT, ...args], { cwd: root, env: GIT_ENV, timeoutMs: GIT_TIMEOUT_MS });
143 try {
144 const parsed = await git(['rev-parse', 'HEAD', '--symbolic-full-name', 'HEAD']);
145 if (parsed.exitCode !== 0) return undefined;
146 const [head = '', ref = ''] = parsed.stdout.split('\n').map((l) => l.trim());
147 if (head === '') return undefined;
148 const branch = ref.startsWith('refs/heads/') ? ref.slice('refs/heads/'.length) : 'HEAD';
149 let behind: number | undefined = 0;
150 if (!head.startsWith(asOfCommit)) {
151 const counted = await git(['rev-list', '--count', `${asOfCommit}..HEAD`, '--']);
152 const n = Number(counted.stdout.trim());
153 behind = counted.exitCode === 0 && /^\d+$/.test(counted.stdout.trim()) ? n : undefined;
154 }
155 return { head, branch, behind };
156 } catch {
157 return undefined;
158 }
159}
160
161/** The line now, or undefined when nothing is shown. */
162function lineNow(): string | undefined {
163 const view = freshnessView(index, local, failure);
164 return view === undefined ? undefined : freshnessText(view, Date.now());
165}
166
167/** Draws again and logs once when the line changed from `before`. */
168function changed(before: string | undefined, invalidate: () => void, log?: Log): void {
169 const after = lineNow();
170 if (after === before) return;
171 invalidate();
172 // Only a stale index is worth a line where nothing draws the indicator.
173 if (after !== undefined && log !== undefined && !logged && freshnessView(index, local, failure)?.kind === 'behind') {
174 logged = true;
175 void Promise.resolve(log(after)).catch(() => undefined);
176 }
177}
178
179/** Compares the checkout with the index, then draws again when the line changed from `before`. Never rejects. */
180async function compare(before: string | undefined, run: Run, invalidate: () => void, log?: Log): Promise<void> {
181 if (root === undefined || index === undefined) return changed(before, invalidate, log);
182 const mine = ++seq;
183 const next = await compareLocal(run, root, index.asOfCommit);
184 if (mine !== seq) return;
185 if (next === undefined) return changed(before, invalidate, log);
186 // The snapshot is per branch: one taken on another branch says nothing here.
187 if (index.branch === undefined) index = { ...index, branch: next.branch };
188 else if (index.branch !== next.branch) index = undefined;
189 local = next;
190 changed(before, invalidate, log);
191}
192
193/**
194 * Compares the checkout with the index and draws again when the line changed.
195 * A no-op without a tracked root and an index. Never rejects.
196 */
197export function recheck(run: Run, invalidate: () => void, log?: Log): Promise<void> {
198 return compare(lineNow(), run, invalidate, log);
199}
200
201/**
202 * Learns what the graph was indexed at from a code_intel envelope for the
203 * project at `root`. Only a hex commit id is kept, so nothing else from the
204 * server reaches git or the text. A failure shows only while no index is
205 * known, and never for the codes the onboarding band owns.
206 */
207export async function observeEnvelope(
208 envelope: CodeIntelEnvelope,
209 at: string,
210 run: Run,
211 invalidate: () => void,
212 log?: Log,
213): Promise<void> {
214 if (at !== root) return;
215 const before = lineNow();
216 if (!envelope.success) {
217 const error = envelope.error;
218 if (index === undefined && error !== undefined && !ONBOARDING_CODES.has(error.code)) failure = error;
219 return changed(before, invalidate, log);
220 }
221 failure = undefined;
222 const commit = envelope.asOfCommit;
223 if (commit === undefined || !COMMIT.test(commit)) return changed(before, invalidate, log);
224 if (index?.asOfCommit === commit && index.lastIndexedAt === envelope.lastIndexedAt) return changed(before, invalidate, log);
225 index = { asOfCommit: commit, ...(envelope.lastIndexedAt === undefined ? {} : { lastIndexedAt: envelope.lastIndexedAt }) };
226 await compare(before, run, invalidate, log);
227}
228
229/** Whether the `showFreshness` option is on. */
230export function showsFreshness(): boolean {
231 return enabled;
232}
233
234/**
235 * Tracks the project at `at`. A different root drops what was known about the
236 * last one; true when it changed. With `showFreshness` off nothing is tracked.
237 */
238export function track(at: string): boolean {
239 if (!enabled || at === root) return false;
240 root = at;
241 index = undefined;
242 local = undefined;
243 failure = undefined;
244 return true;
245}
246
247/** Starts the redraw timer with `every`, a closure over `$.clock.every`, after cancelling the last one. */
248export function startTicks(every: () => Timer): void {
249 timer?.cancel();
250 timer = every();
251}
252
253/** The indicator now: what to draw and its line, or undefined for nothing. */
254export function freshnessLine(now: number): { view: FreshnessView; text: string } | undefined {
255 const view = freshnessView(index, local, failure);
256 return view === undefined ? undefined : { view, text: freshnessText(view, now) };
257}
258
259/**
260 * Starts the indicator over and keeps the `showFreshness` option (an unset
261 * value counts as on). A Bash call that ran a git commit, pull, checkout,
262 * merge or rebase compares the checkout again; the call's result goes back
263 * untouched and does not wait for git. With the option off no hook is registered.
264 */
265export function registerFreshness(on: On, options: PluginOptions): void {
266 timer?.cancel();
267 timer = undefined;
268 index = undefined;
269 local = undefined;
270 failure = undefined;
271 root = undefined;
272 logged = false;
273 seq = 0;
274 enabled = options.showFreshness !== false;
275 if (!enabled) return;
276
277 on('tool.call', { tool: /^Bash$/ }, async ($, e, next) => {
278 const r = await next(e);
279 if (r.deny !== undefined || r.isError === true) return r;
280 try {
281 if (!GIT_MOVES.test(stringArg(e, 'command') ?? '')) return r;
282 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return r;
283 void recheck(
284 (argv, init) => $.process.run(argv, init),
285 () => $.ui.invalidate('ui.render'),
286 async (text) => {
287 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
288 },
289 ).catch(() => undefined);
290 } catch {
291 // The indicator stays as it was.
292 }
293 return r;
294 });
295}
296
297/**
298 * Lets the next conversation (`/clear`, `/resume`, `/branch`) log the line
299 * again. The index, the checkout and the root stay: they describe the
300 * repository, not the conversation.
301 */
302export function resetFreshness(): void {
303 logged = false;
304}
305hooks/impact.ts 203 lines1import type { EngineInterface, On, PluginOptions } from 'claude-code';
2import { agentKey } from './budget';
3import { absolute, isConfigured, plural, projectRoot, stringArg, withinDeadline } from './lib';
4import { atLeast, collectEvidence, type FileRisk, fileRisk, forgetAgentEvidence, hasEvidence, resetRiskCache, type RiskLevel } from './risk';
5import { branded, risk as tone } from './theme';
6
7/** What the gate does before an edit to a file at or above the threshold. */
8type Mode = 'off' | 'dialog' | 'native' | 'require-analysis';
9
10const MODES: readonly Mode[] = ['off', 'dialog', 'native', 'require-analysis'];
11
12/** How long the toast for an edit already headed to the permission prompt stays. */
13const TOAST_MS = 10_000;
14
15/**
16 * How long an edit waits for its file's risk before it goes ahead ungated. The
17 * hook's own time limit pauses while `$.mcp.call` runs, so a slow server would
18 * otherwise hold the edit for code_intel's full timeout. A late lookup still
19 * settles into the cache for the next edit.
20 */
21export const RISK_DEADLINE_MS = 3000;
22
23const PROCEED = 'Proceed';
24const PROCEED_REMEMBER = "Proceed, and don't ask again for this file";
25const CANCEL = 'Cancel';
26
27let mode: Mode = 'off';
28let threshold: RiskLevel = 'high';
29
30/**
31 * The session's permission mode as of the last prompt. In `auto` an `ask` goes
32 * to the classifier, not a person, so the gate treats it as auto-approved.
33 * Read from `classic.UserPromptSubmit`, because `tool.check` and the
34 * `classic.PreToolUse` envelope carry no mode; a mode switched mid-turn is seen
35 * at the next prompt.
36 */
37let permissionMode: string | undefined;
38
39/**
40 * Files the user chose not to be asked about again, by absolute path. Session
41 * wide, not per agent: `tool.check` carries no `agentId`.
42 */
43const remembered = new Set<string>();
44
45/** Per agent, the files require-analysis mode has already refused once, by absolute path. */
46const assessed = new Map<string, Set<string>>();
47
48/**
49 * The risk word first, so a narrow toast that cuts the end keeps it, then how
50 * many files depend on the file, the file, and the indexed commit when known.
51 */
52export function impactLine(risk: FileRisk): string {
53 const commit = risk.asOfCommit === undefined ? '' : ` · as of ${risk.asOfCommit}`;
54 return `${tone(risk.level).word} risk · ${plural(risk.dependents, 'dependent')} · ${risk.path}${commit}`;
55}
56
57/** `impactLine` after the brand, for a log or dialog. A toast is already titled with the plugin's name. */
58export function headline(risk: FileRisk): string {
59 return branded(impactLine(risk));
60}
61
62/** The dialog's question: the headline, the top dependents when there are any, and the question itself. */
63function question(risk: FileRisk): string {
64 const lines = [headline(risk)];
65 if (risk.topDependents.length > 0) lines.push(`Top dependents: ${risk.topDependents.join(', ')}`);
66 lines.push('Edit it anyway?');
67 return lines.join('\n');
68}
69
70/** The refusal the model reads when the user declines or dismisses the dialog, with what they typed under "Other". */
71function declined(risk: FileRisk, said?: string): string {
72 const words = said === undefined ? '' : ` The user said: "${said}"`;
73 return branded(`The user declined this edit to ${risk.path} (${impactLine(risk)}). Ask before trying a different approach.${words}`);
74}
75
76/** The refusal the model reads before its first edit to a file it has not looked into. */
77function refusal(risk: FileRisk): string {
78 const commit = risk.asOfCommit === undefined ? '' : `, as of ${risk.asOfCommit}`;
79 const top = risk.topDependents.length > 0 ? ` Top dependents: ${risk.topDependents.join(', ')}.` : '';
80 const symbols = risk.usedSymbols.length > 0 ? ` Symbols they import from it: ${risk.usedSymbols.join(', ')}.` : '';
81 return branded(`${risk.path} has ${risk.dependents} dependents (${tone(risk.level).word} risk${commit}).${top}${symbols} Check that your change keeps these callers working (use code_intel impactAnalysis / traceSymbolUsage on the symbols you change), then retry the edit.`);
82}
83
84function modeOf(value: unknown): Mode {
85 return MODES.find((m) => m === value) ?? 'off';
86}
87
88/**
89 * The risk of an edit by `tool` to `path` (absolute, normalized) when it is at
90 * or above the threshold, else undefined: no access key, no indexed project, a
91 * `Write` that creates the file, a failed lookup, or one slower than
92 * `RISK_DEADLINE_MS`.
93 */
94async function gatedRisk($: EngineInterface, tool: string, path: string, signal: AbortSignal): Promise<FileRisk | undefined> {
95 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return undefined;
96 const root = await projectRoot(absolute('..', path), (p) => $.fs.exists(p));
97 if (root === null) return undefined;
98 if (tool === 'Write' && !(await $.fs.exists(path))) return undefined;
99 const pending = fileRisk(
100 { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a), after: (ms, fn) => $.clock.after(ms, fn) },
101 root,
102 path,
103 );
104 const risk = await withinDeadline((ms, o) => $.clock.sleep(ms, o), pending, RISK_DEADLINE_MS, signal);
105 return risk !== undefined && atLeast(risk.level, threshold) ? risk : undefined;
106}
107
108export function registerImpactGate(on: On, options: PluginOptions): void {
109 resetImpact();
110 resetRiskCache();
111 mode = modeOf(options.impactGate);
112 threshold = options.impactThreshold === 'critical' ? 'critical' : 'high';
113 collectEvidence(mode === 'require-analysis');
114
115 if (mode === 'require-analysis') {
116 on('tool.call', { tool: /^(Edit|Write|MultiEdit|NotebookEdit)$/ }, async ($, e, next) => {
117 const raw = stringArg(e, 'file_path') ?? stringArg(e, 'notebook_path');
118 if (raw === undefined) return next(e);
119 const path = absolute(raw, await $.session.cwd());
120 const key = agentKey(e);
121 const seen = assessed.get(key) ?? new Set<string>();
122 if (seen.has(path)) return next(e);
123 // The first edit is the one chance: a lookup that misses the deadline or fails lets
124 // it through, and a later refusal would come after the file already changed.
125 assessed.set(key, seen);
126 seen.add(path);
127 const found = await gatedRisk($, String(e.tool), path, next.signal);
128 if (found === undefined || hasEvidence(key, [found.path, path], found.usedSymbols)) return next(e);
129 return { deny: refusal(found) };
130 });
131 return;
132 }
133 if (mode !== 'dialog' && mode !== 'native') return;
134
135 on('classic.UserPromptSubmit', async (_$, e, next) => {
136 permissionMode = e.permission_mode;
137 return next(e);
138 });
139
140 // Every return is `next(e)` or a fixed `ask` or `deny`: core's decision is read from a
141 // `$.tool.check` query, never from what `next` resolves to, so the gate cannot turn it into an allow.
142 on('tool.check', { tool: /^(Edit|Write|MultiEdit|NotebookEdit)$/ }, async ($, e, next) => {
143 // A query (another plugin's `$.tool.check`) has no call id and never opens a dialog or toast.
144 if (e.tool_use_id === undefined) return next(e);
145 const input = typeof e.input === 'object' && e.input !== null ? e.input : undefined;
146 const raw = input === undefined ? undefined : (stringArg(input, 'file_path') ?? stringArg(input, 'notebook_path'));
147 if (raw === undefined) return next(e);
148 // The query skips this hook and asks no settings PreToolUse hook, so it is the rules' and the mode's decision.
149 const { decision } = await $.tool.check({ tool: e.tool, input: e.input });
150 if (decision === 'deny') return next(e);
151 // In auto mode an ask goes to the classifier: no one would see it, so the gate asks itself.
152 const classified = decision === 'ask' && permissionMode === 'auto';
153 // An edit headed to the permission prompt needs no downgrade (native) and gets only a toast (dialog).
154 if (mode === 'native' && decision === 'ask' && !classified) return next(e);
155 // A -p or SDK run has no one to answer: a downgrade there would turn the edit into a refusal.
156 if (mode === 'native' && decision === 'allow' && (await $.session.surfaces()).length === 0) return next(e);
157 const path = absolute(raw, await $.session.cwd());
158 const asks = (mode === 'dialog' && decision === 'allow') || classified;
159 if (asks && remembered.has(path)) return next(e);
160 const risk = await gatedRisk($, String(e.tool), path, next.signal);
161 if (risk === undefined) return next(e);
162
163 const line = headline(risk);
164 if (!asks) {
165 $.ui.toast(impactLine(risk), { timeoutMs: TOAST_MS });
166 // Dialog mode leaves a prompted edit at its prompt; native mode sends an auto-approved one there.
167 if (mode !== 'native') return next(e);
168 return { decision: 'ask', reason: line };
169 }
170 // A -p or SDK run has no one to ask: no one would see the dialog, so fail open.
171 if ((await $.session.surfaces()).length === 0) {
172 $.ui.log(`${line} · could not ask, edit allowed`);
173 return next(e);
174 }
175 let answer = CANCEL;
176 try {
177 answer = await $.ui.ask(question(risk), [PROCEED, PROCEED_REMEMBER, CANCEL]);
178 } catch {
179 // With someone to ask, a rejection is the dialog dismissed (Esc), which refuses.
180 }
181 // Proceed keeps core's decision, so in auto mode the classifier still decides: the gate only adds a check.
182 if (answer === PROCEED) return next(e);
183 if (answer === PROCEED_REMEMBER) {
184 remembered.add(path);
185 return next(e);
186 }
187 return { decision: 'deny', reason: declined(risk, answer === CANCEL ? undefined : answer) };
188 });
189}
190
191/** Forgets every file the user chose not to be asked about, for a new conversation (`/clear`, `/resume`, `/branch`). */
192export function resetImpact(): void {
193 permissionMode = undefined;
194 remembered.clear();
195 assessed.clear();
196}
197
198/** Drops what the subagent `agentId` has been refused and looked at, when its run ends. */
199export function forgetAgentImpact(agentId: string): void {
200 assessed.delete(agentId);
201 forgetAgentEvidence(agentId);
202}
203hooks/nudge.ts 73 lines1import type { On } from 'claude-code';
2import { background, noteSearch, save, showsAdoption } from './adoption';
3import { agentKey, hasNudgeLeft, MAIN, spendNudge, usedCodeIntelThisTurn } from './budget';
4import { searchTarget } from './classify';
5import { isConfigured, projectRoot } from './lib';
6import { branded } from './theme';
7
8/** Added to the model's context when a session or a subagent starts. */
9export const SESSION_TEXT =
10 'You have access to the code_intel source code intelligence tool, this should be your preferred tool for searching or navigating the code base (finding definitions or references, impact analysis, architecture details, etc.). Other search tools (e.g. grep, glob, awk, rg) should be used for literal text search or as a fallback.';
11
12/** Added to the model's context with a search tool call's result. */
13export const REMINDER_TEXT = branded(
14 'Use the code_intel tool before other tools for searching or navigating the codebase. Other search tools (e.g. grep, glob, awk, rg) should be used for literal text search or as a fallback.',
15);
16
17type WithContext = { additionalContext?: string[] };
18
19/** `result` with `text` appended to its context, whatever decision it already carries. */
20function withContext<R extends WithContext>(result: R, text: string): R {
21 return { ...result, additionalContext: [...(result.additionalContext ?? []), text] };
22}
23
24export function registerNudges(on: On): void {
25 on('classic.SessionStart', async ($, e, next) => {
26 const r = await next(e);
27 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return r;
28 return withContext(r, SESSION_TEXT);
29 });
30
31 on('classic.SubagentStart', async ($, e, next) => {
32 const r = await next(e);
33 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return r;
34 return withContext(r, SESSION_TEXT);
35 });
36
37 // On `tool.call`, not `classic.PreToolUse`: adding context means reading what `next` resolved to,
38 // and a hook on a permission event has to return that unread.
39 on('tool.call', { tool: /^(Grep|Glob|Bash)$/ }, async ($, e, next) => {
40 const { isSearch, symbolLike, path } = searchTarget(e);
41 const r = await next(e);
42 if (r.deny !== undefined) return r;
43 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return r;
44 // One walk for constellation.json per call, shared by the count and the reminder.
45 let walk: Promise<boolean> | undefined;
46 const inProject = (): Promise<boolean> =>
47 (walk ??= (async () => (await projectRoot(await $.session.cwd(), (p) => $.fs.exists(p), path)) !== null)());
48 // Counted only where code_intel could have answered: the agent's own search, with a key, inside an indexed project.
49 // It runs in the background, so the search's answer waits on neither the walk nor the store.
50 if (isSearch && next.origin.plugin === 'engine') {
51 const isMain = agentKey(e) === MAIN;
52 background(async () => {
53 if (!(await inProject())) return;
54 const counted = noteSearch(isMain, symbolLike);
55 // A literal search changes nothing the spinner shows.
56 if (symbolLike && showsAdoption()) $.ui.invalidate('ui.render');
57 await save(counted, {
58 now: () => $.clock.now(),
59 sessionId: () => $.session.id(),
60 get: (k) => $.store.get(k),
61 set: (k, entry) => $.store.set(k, entry),
62 keys: () => $.store.keys(),
63 del: (k) => $.store.delete(k),
64 });
65 });
66 }
67 if (!symbolLike || usedCodeIntelThisTurn(e) || !hasNudgeLeft(e)) return r;
68 if (!(await inProject())) return r;
69 if (!spendNudge(e)) return r;
70 return { ...r, context: [...(r.context ?? []), REMINDER_TEXT] };
71 });
72}
73hooks/onboarding.ts 823 lines1import type {
2 ElementTable,
3 EngineInterface,
4 On,
5 ProcessRunInit,
6 ProcessRunResult,
7 ProcessSpawnChunk,
8 ProcessSpawnRequest,
9 RenderElement,
10} from 'claude-code';
11import { freshnessBand, freshnessLine } from './freshness';
12import { absolute, canDraw, codeIntel, gitRoot, isRecord, parseToolText, projectRoot, relativeTo } from './lib';
13import type { CodeIntelEnvelope, McpPort } from './lib';
14import { badge, brandMark, branded, buttonRow, forTheme, onboarding, scheme } from './theme';
15import type { Scheme, Tone } from './theme';
16
17/** The access key format the CLI writes: `ak:` and 32 hex digits. */
18export const KEY_PATTERN = /^ak:[0-9a-f]{32}$/i;
19
20/** What `constellation index` prints when the project ID is unknown to Constellation. */
21export const NOT_REGISTERED_OUTPUT = /Project not registered|PROJECT_NOT_REGISTERED/;
22
23/** How long a theme read serves draws: a running CLI draws the band again for each line it prints. */
24const THEME_MS = 1000;
25
26/** Where a project is created and its ID found. */
27const WEB_APP = 'https://app.constellationdev.io';
28
29/** How long the stored key read-back may take: a profile that prompts must not hold up the session. */
30const READ_BACK_MS = 5000;
31
32/** Where Windows keeps `reg`: by absolute path, so a `reg` in the working directory is never run. */
33const REG = 'C:\\Windows\\System32\\reg.exe';
34
35/** Prints the shell's PATH, then where the CLI is: the PATH line is marked, so it never reads as the CLI's path. */
36export const CLI_LOOKUP = `printf 'PATH=%s\\n' "$PATH"; command -v constellation`;
37
38/** How the CLI is installed, and where the docs say so. */
39const INSTALL_COMMAND = 'npm i -g @constellationdev/cli';
40const INSTALL_DOCS = 'https://docs.constellationdev.io/cli/#installation';
41
42/** What a sign-in that stored a new key says, before the reload. */
43const CONNECTED = 'Connected';
44const CONNECTED_NO_PROJECT = 'Connected. Run const init in this repo to set it up';
45
46/** A failed sign-in's line where the CLI said nothing, and the sign-in step where no `/bin/sh` runs (Windows). */
47const AUTH_IN_TERMINAL = 'Run const auth in a terminal';
48
49/** An index press where no `constellation.json` sits at or above the session's directory, and the index step where no `/bin/sh` runs. */
50const INDEX_IN_PROJECT = 'Run const index in a terminal, in the project directory';
51
52/** The band's states. The first that holds wins, in this order. */
53export type OnboardingState = 'not-set-up' | 'sign-in-again' | 'no-project' | 'not-registered' | 'not-indexed' | 'working';
54
55/** The CLI run in progress. */
56export type Task = 'auth' | 'index';
57
58/** What the band's state is decided from. */
59export type OnboardingFacts = {
60 /** The session's `CONSTELLATION_ACCESS_KEY` starts with `ak:`. */
61 configured: boolean;
62 /** A key the CLI stored was read back. */
63 stored?: boolean;
64 /** The error code of the latest code_intel answer. */
65 code?: string;
66 /** The project roots `CWD_NOT_INDEXED` found under the git root. */
67 candidates?: readonly string[];
68 /** The CLI's own output said the project is not registered. */
69 notRegistered?: boolean;
70 /** `constellation auth` or `constellation index` is running. */
71 running?: boolean;
72};
73
74/** The band's state for `facts`: the first row that holds, else undefined (nothing to show). */
75export function onboardingState(facts: OnboardingFacts): OnboardingState | undefined {
76 if (!facts.configured && facts.stored !== true) return 'not-set-up';
77 if (facts.code === 'AUTH_ERROR') return 'sign-in-again';
78 if (facts.code === 'CWD_NOT_INDEXED' && (facts.candidates ?? []).length === 0) return 'no-project';
79 if (facts.code === 'PROJECT_NOT_REGISTERED' || facts.notRegistered === true) return 'not-registered';
80 if (facts.code === 'PROJECT_NOT_INDEXED') return 'not-indexed';
81 if (facts.running === true) return 'working';
82 return undefined;
83}
84
85/**
86 * The last key in `output` that matches `KEY_PATTERN`, else undefined. Each
87 * line's last word counts, which covers `printenv` (the value alone, between
88 * whatever a profile prints) and `reg query`
89 * (`CONSTELLATION_ACCESS_KEY REG_SZ ak:...`).
90 */
91export function parseStoredKey(output: string): string | undefined {
92 let found: string | undefined;
93 for (const line of output.split('\n')) {
94 const token = line.trim().split(/\s+/).pop() ?? '';
95 if (KEY_PATTERN.test(token)) found = token;
96 }
97 return found;
98}
99
100/** The last line of `output` that is an absolute POSIX path, else undefined. */
101export function parseCliPath(output: string): string | undefined {
102 let found: string | undefined;
103 for (const raw of output.split('\n')) {
104 const line = raw.trim();
105 if (line.startsWith('/')) found = line;
106 }
107 return found;
108}
109
110/**
111 * The last complete, non-empty line of `buffer`, else undefined. Text after
112 * the last newline is still being written, so it waits. A carriage return
113 * redraws a line in place, so what follows the last one in a line is kept.
114 */
115export function lastLine(buffer: string): string | undefined {
116 const lines = buffer.split('\n').slice(0, -1);
117 for (let i = lines.length - 1; i >= 0; i--) {
118 const shown = (lines[i] ?? '')
119 .split('\r')
120 .map((part) => part.trim())
121 .filter((part) => part !== '')
122 .pop();
123 if (shown !== undefined) return shown;
124 }
125 return undefined;
126}
127
128/** The http(s) URL on or after the line that says "open this URL manually", else undefined. */
129export function manualUrl(buffer: string): string | undefined {
130 const at = buffer.indexOf('open this URL manually');
131 if (at < 0) return undefined;
132 const from = buffer.lastIndexOf('\n', at) + 1;
133 return /https?:\/\/[^\s'"<>]+/.exec(buffer.slice(from))?.[0];
134}
135
136/** Runs a command, as `$.process.run`. */
137export type Run = (argv: readonly string[], init: ProcessRunInit) => Promise<Pick<ProcessRunResult, 'exitCode' | 'stdout'>>;
138
139/**
140 * What the onboarding calls. `claude plugin validate` follows `$` only into
141 * functions of the same file, so a handler spells each call in a closure.
142 */
143export type OnboardingPorts = {
144 run: Run;
145 exists: (path: string) => Promise<boolean>;
146 /** Reads a file's text, as `$.fs.read`. */
147 read: (path: string) => Promise<string>;
148 /** Sets `CONSTELLATION_ACCESS_KEY` for the session and what it starts. */
149 envSet: (key: string) => Promise<unknown>;
150 after: (ms: number, fn: () => void) => void;
151 mcp: McpPort;
152 /** Runs `/reload-plugins`, which restarts the MCP server with the session's environment. */
153 reload: () => Promise<unknown>;
154 toast: (text: string) => void;
155 /** Draws the band again. */
156 invalidate: () => void;
157 /** Writes `text` as a transcript line when no surface of the session draws the band. */
158 log: (text: string) => Promise<void>;
159};
160
161/** How a state change is told: a redraw, and a line where nothing draws. */
162type Notify = Pick<OnboardingPorts, 'invalidate'> & Partial<Pick<OnboardingPorts, 'log'>>;
163
164/** The one line a session that cannot draw the band gets, with the command to run. */
165const LOG_STEP: Readonly<Record<Exclude<OnboardingState, 'working'>, string>> = {
166 'not-set-up': 'run const auth',
167 'sign-in-again': 'run const auth',
168 'no-project': 'run const init',
169 'not-registered': 'check projectId in constellation.json',
170 'not-indexed': 'run const index',
171};
172
173/** The states an error put up, which a later success takes down. */
174const ERROR_STATES: ReadonlySet<OnboardingState> = new Set(['sign-in-again', 'not-indexed', 'not-registered', 'no-project']);
175
176/**
177 * Module state, cleared by `registerOnboarding` and `resetOnboarding`.
178 * `generation` changes with each, so work started before a reset can tell.
179 */
180let generation = 0;
181let state: OnboardingState | undefined;
182/** The CLI run in progress; it ends with its child, whatever resets meanwhile. */
183let running: Task | undefined;
184/** What the running or last CLI run printed. */
185let buffer = '';
186/** The line under the state's headline once a CLI run has ended, such as its last output line. */
187let detail: string | undefined;
188/** The last button press found no CLI: the band says how to install it. */
189let cliMissing = false;
190/** A session that cannot draw gets one line. */
191let logged = false;
192/** Whether a POSIX `/bin/sh` is present, once asked: Windows has none, and the band starts no CLI there. */
193let shell: boolean | undefined;
194/** The repository's stored dismissal, by its store key: only this plugin writes it, so one read serves every draw. */
195let dismissal: { key: string; value: unknown } | undefined;
196/** Claude Code's theme and when it was read: `/theme` raises no event, so a read older than THEME_MS is read again. */
197let theme: { value: unknown; readAt: number } | undefined;
198/** The git root (else the working directory) the session started in: dismissals are kept per repository. */
199let repoRoot: string | undefined;
200
201/** Draws the band again. */
202function redraw(notify: Pick<OnboardingPorts, 'invalidate'>): void {
203 try {
204 notify.invalidate();
205 } catch {
206 // Refused while a band draws: the next draw reads the new state.
207 }
208}
209
210/** Puts up `next`, with `line` under its headline, and tells the band, unless a CLI run holds the band. */
211function apply(next: OnboardingState | undefined, notify: Notify, line?: string): void {
212 if (running !== undefined || next === state) return;
213 state = next;
214 detail = line;
215 redraw(notify);
216 if (next === undefined || next === 'working' || logged || notify.log === undefined) return;
217 logged = true;
218 notify.log(branded(`${HEADLINE[next]} · ${LOG_STEP[next]}`)).catch(() => undefined);
219}
220
221/**
222 * Starts a CLI run: the band shows it as working, and nothing else writes the
223 * band until `endTask`. Returns the generation, which a run compares once its
224 * child exits to tell whether a reset came meanwhile, or undefined (refused)
225 * while another run is live, so sign-in and indexing never overlap.
226 */
227export function startTask(task: Task, notify: Pick<OnboardingPorts, 'invalidate'>): number | undefined {
228 if (running !== undefined) return undefined;
229 buffer = '';
230 apply(onboardingState({ configured: true, running: true }), notify);
231 running = task;
232 return generation;
233}
234
235/** Ends the CLI run, whatever reset came meanwhile. */
236export function endTask(): void {
237 running = undefined;
238}
239
240/**
241 * Records the git root of `cwd` (else `cwd` itself) as the repository whose
242 * dismissal the band reads, and returns the git root, or null outside one.
243 */
244export async function rememberRepo(cwd: string, exists: (path: string) => Promise<boolean>): Promise<string | null> {
245 const root = await gitRoot(cwd, exists);
246 repoRoot = root ?? cwd;
247 return root;
248}
249
250/** Whether a POSIX `/bin/sh` is present (Windows has none), asked once per load. */
251async function hasShell(exists: (path: string) => Promise<boolean>): Promise<boolean> {
252 shell ??= await exists('/bin/sh');
253 return shell;
254}
255
256/**
257 * Reads back the key the CLI stored, or undefined: never logged or shown.
258 * A login `/bin/sh` reads `~/.profile`, where the CLI writes the key, whatever
259 * the person's shell; the empty override keeps an inherited key from masking
260 * it. A run that fails or runs past the timeout counts as no key. Only where
261 * there is no `/bin/sh` (Windows: the engine exposes no OS) is the registry read.
262 */
263export async function storedKey(ports: Pick<OnboardingPorts, 'run' | 'exists'>): Promise<string | undefined> {
264 try {
265 const r = (await hasShell(ports.exists))
266 ? await ports.run(['/bin/sh', '-lc', 'printenv CONSTELLATION_ACCESS_KEY'], {
267 env: { CONSTELLATION_ACCESS_KEY: '' },
268 timeoutMs: READ_BACK_MS,
269 })
270 : await ports.run([REG, 'query', 'HKCU\\Environment', '/v', 'CONSTELLATION_ACCESS_KEY'], { timeoutMs: READ_BACK_MS });
271 return r.exitCode === 0 ? parseStoredKey(r.stdout) : undefined;
272 } catch {
273 return undefined;
274 }
275}
276
277/** The PATH a `CLI_LOOKUP` run printed, else undefined. */
278export function parseShellPath(output: string): string | undefined {
279 let found: string | undefined;
280 for (const line of output.split('\n')) {
281 if (line.startsWith('PATH=')) found = line.slice('PATH='.length).trim();
282 }
283 return found;
284}
285
286/** Where the CLI is (undefined when not found), and what its child's environment sets over the host's. */
287export type CliLookup = { path: string | undefined; env: Record<string, string> };
288
289/**
290 * Finds the CLI the way a terminal would: a plain `/bin/sh` looks on the
291 * host's PATH, then a login one on the PATH the profile sets. A CLI only the
292 * login shell finds runs with that PATH before the host's, so its
293 * `#!/usr/bin/env node` finds the same node. A path inside one of `untrusted`
294 * (the session's directory and its git root) is a repository's file and
295 * counts as not found. Never rejects.
296 */
297export async function cliPath(run: Run, untrusted: readonly string[]): Promise<CliLookup> {
298 const look = async (flag: '-c' | '-lc') => {
299 const r = await run(['/bin/sh', flag, CLI_LOOKUP], { timeoutMs: READ_BACK_MS });
300 const path = r.exitCode === 0 ? parseCliPath(r.stdout) : undefined;
301 const trusted = path !== undefined && untrusted.every((dir) => relativeTo(dir, absolute(path, dir)) === null);
302 return { path: trusted ? path : undefined, PATH: parseShellPath(r.stdout) };
303 };
304 try {
305 const host = await look('-c');
306 if (host.path !== undefined) return { path: host.path, env: {} };
307 const login = await look('-lc');
308 if (login.path === undefined) return { path: undefined, env: {} };
309 return { path: login.path, env: { PATH: [login.PATH, host.PATH].filter((p) => p !== undefined && p !== '').join(':') } };
310 } catch {
311 return { path: undefined, env: {} };
312 }
313}
314
315/** A stored key found at session start, for the caller to set before the session goes on. */
316export type FoundKey = { key: string; projectRoot: string | null };
317
318/**
319 * At session start with no key set: outside a git repository nothing runs. In
320 * one, the stored key is read back; with none the band says not set up, else
321 * the key and the project root (null without a `constellation.json`, which
322 * then gets no ping) return.
323 */
324export async function readStoredKeyAtStart(
325 cwd: string,
326 ports: Pick<OnboardingPorts, 'run' | 'exists'> & Notify,
327): Promise<FoundKey | undefined> {
328 if ((await rememberRepo(cwd, ports.exists)) === null) return undefined;
329 const key = await storedKey(ports);
330 if (key === undefined) {
331 apply(onboardingState({ configured: false, stored: false }), ports);
332 return undefined;
333 }
334 return { key, projectRoot: await projectRoot(cwd, ports.exists) };
335}
336
337/**
338 * Takes the band down, shows `toast` when given, and reloads the plugins on a
339 * timer. The reload unloads this module, so nothing is chained after it.
340 */
341function reloadPlugins(ports: OnboardingPorts, toast?: string): void {
342 state = undefined;
343 detail = undefined;
344 buffer = '';
345 ports.invalidate();
346 if (toast !== undefined) ports.toast(toast);
347 // `$.command.run` is refused inside a hook the turn waits on, so it always goes through the timer.
348 ports.after(0, () => {
349 ports.reload().catch(() => undefined);
350 });
351}
352
353/**
354 * Sets `key` for the session, shows `toast`, then reloads the plugins so the
355 * MCP server starts with the key. A reload unloads the module and kills a
356 * running child, so call it once a CLI run has ended (`endTask`).
357 */
358export async function connect(key: string, ports: OnboardingPorts, toast: string): Promise<void> {
359 await ports.envSet(key);
360 reloadPlugins(ports, toast);
361}
362
363/** The API a `constellation.json` with no `apiUrl` reaches. */
364const DEFAULT_API = 'https://api.constellationdev.io';
365
366/**
367 * True when the `constellation.json` in `root` leaves the API at the default
368 * (the MCP server sends the access key to the one it names, and takes any
369 * falsy `apiUrl` as the default). A file that cannot be read or parsed counts
370 * as naming another.
371 */
372export async function usesDefaultApi(root: string, read: (path: string) => Promise<string>): Promise<boolean> {
373 try {
374 const config: unknown = JSON.parse(await read(`${root.replace(/\/$/, '')}/constellation.json`));
375 if (!isRecord(config)) return false;
376 return !config.apiUrl || (typeof config.apiUrl === 'string' && config.apiUrl.replace(/\/+$/, '') === DEFAULT_API);
377 } catch {
378 return false;
379 }
380}
381
382/**
383 * Pings the project at `root`, unless its `constellation.json` names an API
384 * other than the default, which a repository chooses, so it is not pinged
385 * unasked. Undefined when skipped or when anything throws. Never rejects.
386 */
387export async function pingProject(root: string, ports: Pick<OnboardingPorts, 'read' | 'mcp'>): Promise<CodeIntelEnvelope | undefined> {
388 try {
389 if (!(await usesDefaultApi(root, ports.read))) return undefined;
390 return await codeIntel(ports.mcp, 'return await api.ping()', { cwd: root });
391 } catch {
392 return undefined;
393 }
394}
395
396/**
397 * After a stored key was set at session start, in the project at `root`: a
398 * ping (`pingProject`) decides, and `observe` sees its answer first.
399 * `AUTH_ERROR` means the server started before the key was set, so the
400 * plugins reload; `PROJECT_NOT_INDEXED` (also sent for an unregistered
401 * project) puts up the index button. Never rejects.
402 */
403export async function checkConnection(root: string, ports: OnboardingPorts, observe?: (envelope: CodeIntelEnvelope) => void): Promise<void> {
404 try {
405 const envelope = await pingProject(root, ports);
406 if (envelope === undefined) return;
407 try {
408 observe?.(envelope);
409 } catch {
410 // What observes the ping never changes what the ping decides.
411 }
412 const code = envelope.error?.code;
413 if (code === 'AUTH_ERROR') {
414 // No toast: nothing is known to work. The agent's next AUTH_ERROR says sign in again.
415 // A sign-in already running connects when it ends; a reload now would kill its child.
416 if (running === undefined) reloadPlugins(ports);
417 return;
418 }
419 const next = onboardingState({ configured: true, code });
420 if (next !== undefined) apply(next, ports);
421 } catch {
422 // The band stays as it was.
423 }
424}
425
426/**
427 * Reads the agent's own code_intel answer `r`: an error that has a fix puts up
428 * its state, and a success takes down a state an error put up. A run of the
429 * CLI holds the band, and `MCP_UNAVAILABLE` (the server is not connected) and
430 * a `CWD_NOT_INDEXED` that lists project roots (a monorepo) change nothing.
431 * `configured` is whether the session's key starts with `ak:`; with none,
432 * `AUTH_ERROR` says "not signed in": the server then got no key.
433 */
434export function observeCodeIntel(
435 r: { deny?: string; text?: string; isError?: boolean },
436 configured: boolean,
437 invalidate: () => void,
438 log?: (text: string) => Promise<void>,
439): void {
440 if (r.deny !== undefined || running !== undefined) return;
441 const notify: Notify = log === undefined ? { invalidate } : { invalidate, log };
442 const envelope = parseToolText(r.text, r.isError === true);
443 if (envelope.success) {
444 if (state !== undefined && ERROR_STATES.has(state)) apply(undefined, notify);
445 return;
446 }
447 const error = envelope.error;
448 if (error === undefined || error.code === 'MCP_UNAVAILABLE') return;
449 const next = onboardingState({ configured, code: error.code, candidates: error.candidates });
450 if (next !== undefined) apply(next, notify);
451}
452
453/** What the band's buttons call beyond the session start's ports. */
454export type ButtonPorts = OnboardingPorts & {
455 /** Starts a child, as `$.process.spawn`: the loop over its pieces is its life. */
456 spawn: (request: ProcessSpawnRequest) => AsyncIterable<ProcessSpawnChunk>;
457 /** The session's working directory. */
458 cwd: () => Promise<string>;
459};
460
461/** A claimed CLI run: the generation it started in, the CLI it runs and what its environment sets. */
462type Claim = { gen: number; cli: string; env: Record<string, string> };
463
464/**
465 * Claims the band for `task` before anything is awaited, so a second press
466 * is refused at once, then finds the CLI. Undefined when a run is live, when
467 * a reset came during the lookup (the claim is released), or when no CLI is
468 * found: the band then goes back to what it showed and says how to install
469 * it, and nothing is spawned.
470 */
471async function claim(task: Task, ports: ButtonPorts): Promise<Claim | undefined> {
472 const prior = state;
473 const gen = startTask(task, ports);
474 if (gen === undefined) return undefined;
475 const { path, env } = await ports
476 .cwd()
477 .then(async (cwd) => cliPath(ports.run, [cwd, (await gitRoot(cwd, ports.exists)) ?? cwd]))
478 .catch((): CliLookup => ({ path: undefined, env: {} }));
479 if (path !== undefined && generation === gen) {
480 cliMissing = false;
481 return { gen, cli: path, env };
482 }
483 endTask();
484 if (generation === gen) {
485 cliMissing = true;
486 apply(prior, ports);
487 }
488 return undefined;
489}
490
491/**
492 * Reads a CLI run's child to its end, both streams into `buffer`, and draws
493 * the band again when its latest line changes. False when the child could not
494 * start. What it prints after a reset is not kept: the band it was for is gone.
495 */
496async function follow(start: () => AsyncIterable<ProcessSpawnChunk>, gen: number, notify: Pick<OnboardingPorts, 'invalidate'>): Promise<boolean> {
497 try {
498 for await (const { text } of start()) {
499 if (generation !== gen) continue;
500 const was = lastLine(buffer);
501 buffer += text;
502 if (lastLine(buffer) !== was) redraw(notify);
503 }
504 return true;
505 } catch {
506 return false;
507 }
508}
509
510/**
511 * The Sign in button: runs `constellation auth` with the inherited key
512 * emptied, so the CLI neither reuses nor asks to replace it, then reads the
513 * stored key back. A new key connects; anything else (the exit code is not
514 * read) says the sign-in failed. The run holds the band until that is
515 * decided, and the plugins reload only after the child has exited, since a
516 * reload kills it. A run that outlives a reset acts on nothing.
517 */
518export async function startSignIn(ports: ButtonPorts): Promise<void> {
519 const claimed = await claim('auth', ports);
520 if (claimed === undefined) return;
521 const { gen, cli, env } = claimed;
522 const before = await storedKey(ports);
523 if (generation !== gen) {
524 endTask();
525 return;
526 }
527 void (async () => {
528 let after: string | undefined;
529 let root: string | null | undefined;
530 try {
531 const started = await follow(
532 // Never through a login shell: its profile would export the stored key again over the empty one.
533 () => ports.spawn({ argv: [cli, 'auth'], env: { ...env, CONSTELLATION_ACCESS_KEY: '', NO_COLOR: '1' } }),
534 gen,
535 ports,
536 );
537 if (started && generation === gen) after = await storedKey(ports);
538 if (after !== undefined && after !== before) {
539 root = await ports
540 .cwd()
541 .then((cwd) => projectRoot(cwd, ports.exists))
542 .catch(() => undefined);
543 }
544 } finally {
545 endTask();
546 }
547 if (generation !== gen) return;
548 if (after !== undefined && after !== before) {
549 try {
550 await connect(after, ports, root === null ? CONNECTED_NO_PROJECT : CONNECTED);
551 return;
552 } catch {
553 // The key could not be set: the sign-in failed.
554 }
555 }
556 apply('sign-in-again', ports, lastLine(buffer) ?? AUTH_IN_TERMINAL);
557 })();
558}
559
560/**
561 * The Index button: runs `constellation index --wait` in the project root,
562 * then a ping decides (the exit code is not read). Only a successful ping
563 * takes the band down. An error with a state of its own puts it up (a
564 * rejected key says sign in again; not registered when the CLI said so);
565 * anything else stays not indexed. The run holds the band until the ping
566 * answers. A run that outlives a reset acts on nothing.
567 */
568export async function startIndex(ports: ButtonPorts): Promise<void> {
569 const prior = state;
570 const claimed = await claim('index', ports);
571 if (claimed === undefined) return;
572 const { gen, cli, env } = claimed;
573 const root = await ports
574 .cwd()
575 .then((cwd) => projectRoot(cwd, ports.exists))
576 .catch(() => null);
577 if (root === null || generation !== gen) {
578 endTask();
579 if (generation === gen) apply(prior, ports, INDEX_IN_PROJECT);
580 return;
581 }
582 void (async () => {
583 let ping: CodeIntelEnvelope | undefined;
584 try {
585 await follow(() => ports.spawn({ argv: [cli, 'index', '--wait'], cwd: root, env: { ...env, NO_COLOR: '1' } }), gen, ports);
586 if (generation === gen) ping = await codeIntel(ports.mcp, 'return await api.ping()', { cwd: root });
587 } finally {
588 endTask();
589 }
590 if (generation !== gen) return;
591 if (ping?.success === true) {
592 buffer = '';
593 apply(undefined, ports);
594 ports.toast('Indexed this project');
595 return;
596 }
597 const code = ping?.error?.code;
598 apply(onboardingState({ configured: true, code, notRegistered: NOT_REGISTERED_OUTPUT.test(buffer) }) ?? 'not-indexed', ports, lastLine(buffer));
599 })();
600}
601
602/** The second spelling of the ports, for the band's buttons; the first is the session start's in `command.ts`. */
603function portsOf($: EngineInterface): ButtonPorts {
604 return {
605 spawn: (request) => $.process.spawn(request),
606 cwd: () => $.session.cwd(),
607 run: (argv, init) => $.process.run(argv, init),
608 exists: (p) => $.fs.exists(p),
609 read: (p) => $.fs.read(p),
610 envSet: (key) => $.env.set('CONSTELLATION_ACCESS_KEY', key),
611 after: (ms, fn) => {
612 $.clock.after(ms, fn);
613 },
614 mcp: { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
615 reload: () => $.command.run({ command: 'reload-plugins' }),
616 toast: (text) => $.ui.toast(text),
617 invalidate: () => $.ui.invalidate('ui.render'),
618 log: async (text) => {
619 if (!canDraw(await $.session.surfaces())) $.ui.log(text);
620 },
621 };
622}
623
624/** The store key of a repository's dismissed state. */
625function dismissalKey(repo: string): string {
626 return `onboarding-dismissed:${repo}`;
627}
628
629const TONE: Readonly<Record<OnboardingState, Tone>> = {
630 'not-set-up': onboarding.notSetUp,
631 'sign-in-again': onboarding.failed,
632 'no-project': onboarding.notSetUp,
633 'not-registered': onboarding.failed,
634 'not-indexed': onboarding.notSetUp,
635 working: onboarding.pending,
636};
637
638const HEADLINE: Readonly<Record<Exclude<OnboardingState, 'working'>, string>> = {
639 'not-set-up': 'Not signed in',
640 'sign-in-again': 'Sign-in failed',
641 'no-project': 'Not set up for this project',
642 'not-registered': "This project isn't registered",
643 'not-indexed': "This project hasn't been indexed yet",
644};
645
646/** What the band draws and what its buttons do. */
647export type BandView = {
648 state: OnboardingState;
649 tint: Scheme;
650 /** The CLI's latest output line, or what to do next. */
651 detail?: string;
652 /** The CLI run behind `working`. */
653 task?: Task;
654 /** The address a sign-in asks to be opened when no browser opened. */
655 url?: string;
656 /** The last press found no CLI: how to install it shows above the buttons. */
657 cliMissing?: boolean;
658 /** No `/bin/sh` runs here (Windows): the band names the command to run in a terminal instead of a button. */
659 noShell?: boolean;
660 dismiss: () => void;
661 signIn: () => void;
662 index: () => void;
663};
664
665/**
666 * The band for a state: a badge and headline, the steps for states a button
667 * cannot fix (a command to run in a terminal and a link), the CLI's latest
668 * line, then the buttons, Dismiss left and the fix rightmost. A running CLI
669 * gets no buttons.
670 */
671export function band(el: ElementTable, view: BandView): RenderElement {
672 const tone = forTheme(TONE[view.state], view.tint);
673 const headline =
674 view.state === 'working' ? (view.task === 'index' ? 'Indexing this project' : 'Signing in') : HEADLINE[view.state];
675 const rows: RenderElement[] = [
676 el.Text({ wrap: 'truncate', children: [brandMark(el, view.tint), ' · ', badge(el, '', tone), ' ', el.Text({ bold: true, children: headline })] }),
677 ];
678 if (view.state === 'no-project') {
679 rows.push(el.Text({ children: 'Run const init in a terminal, with the project ID from the web app:' }), el.Link({ href: WEB_APP }));
680 }
681 if (view.state === 'not-registered') {
682 rows.push(el.Text({ children: 'Check projectId in constellation.json against the web app:' }), el.Link({ href: WEB_APP }));
683 }
684 if (view.detail !== undefined) rows.push(el.Text({ dimColor: true, wrap: 'truncate', children: view.detail }));
685 if (view.url !== undefined) rows.push(el.Link({ href: view.url, label: view.url }));
686 // A run passes on its own, so it is never dismissed: a dismissal would hide every later run.
687 if (view.state === 'working') return el.Box({ flexDirection: 'column', children: rows });
688 const dismiss = { key: 'onboarding-dismiss', label: 'Dismiss', onPress: view.dismiss };
689 const signsIn = view.state === 'not-set-up' || view.state === 'sign-in-again';
690 if (view.noShell === true && (signsIn || view.state === 'not-indexed')) {
691 rows.push(el.Text({ children: signsIn ? AUTH_IN_TERMINAL : INDEX_IN_PROJECT }));
692 }
693 const action =
694 view.noShell === true
695 ? undefined
696 : signsIn
697 ? { key: 'onboarding-sign-in', label: 'Sign in', onPress: view.signIn }
698 : view.state === 'not-indexed'
699 ? { key: 'onboarding-index', label: 'Index this project', onPress: view.index }
700 : undefined;
701 if (action !== undefined && view.cliMissing === true) {
702 rows.push(el.Text({ children: `Install the Constellation CLI, then press ${action.label} again: ${INSTALL_COMMAND}` }), el.Link({ href: INSTALL_DOCS }));
703 }
704 rows.push(
705 action === undefined
706 ? el.Box({ flexDirection: 'row', justifyContent: 'flex-end', children: [el.Button(dismiss)] })
707 : buttonRow(el, dismiss, action),
708 );
709 return el.Box({ flexDirection: 'column', children: rows });
710}
711
712/**
713 * The color scheme now, with the clock it was read at. The theme row is read at
714 * most once a second (`THEME_MS`), so a running CLI's redraws read it once.
715 */
716async function readTint($: EngineInterface): Promise<{ now: number; tint: Scheme }> {
717 const now = await $.clock.now();
718 if (theme === undefined || now - theme.readAt > THEME_MS) {
719 try {
720 theme = { value: (await $.config.list()).find((r) => r.key === 'theme')?.value, readAt: now };
721 } catch {
722 // The default colors, until a read succeeds.
723 }
724 }
725 return { now, tint: scheme(theme?.value) };
726}
727
728/** True when a lower mod drew nothing: core's own drawing, or a container with no children. */
729function isEmpty(element: RenderElement): boolean {
730 if (element.type === 'engine') return true;
731 if (element.type !== 'Box' && element.type !== 'Text') return false;
732 const children: unknown = element.props?.children;
733 return children === undefined || (Array.isArray(children) && children.length === 0);
734}
735
736/**
737 * The onboarding band above the prompt. Draws from module state only; a
738 * repository whose stored dismissal equals the current state passes, so a
739 * new, different error shows the band again. The dismissal is read once and
740 * the theme at most once a second, so a running CLI's redraws read neither.
741 */
742export function registerOnboarding(on: On): void {
743 generation += 1;
744 state = undefined;
745 running = undefined;
746 buffer = '';
747 detail = undefined;
748 cliMissing = false;
749 logged = false;
750 repoRoot = undefined;
751 shell = undefined;
752 dismissal = undefined;
753 theme = undefined;
754
755 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
756 const shown = state;
757 if (e.props.hasSurvey) return next(e);
758 if (shown === undefined) {
759 // A fresh index reads nothing; the line draws only while no onboarding state exists.
760 const row = freshnessLine(Date.now());
761 if (row === undefined) return next(e);
762 const { now, tint } = await readTint($);
763 const below = await next(e);
764 const el = $.ui.resolve(e);
765 const line = freshnessBand(el, row.view, tint, now);
766 return isEmpty(below) ? line : el.Box({ flexDirection: 'column', children: [line, below] });
767 }
768 const key = dismissalKey(repoRoot ?? (await $.session.cwd()));
769 if (dismissal?.key !== key) {
770 try {
771 dismissal = { key, value: await $.store.get(key) };
772 } catch {
773 // The store is unavailable: the band shows, and the next draw reads again.
774 }
775 }
776 if (dismissal?.key === key && dismissal.value === shown) return next(e);
777 const { tint } = await readTint($);
778 const noShell = !(await hasShell((p) => $.fs.exists(p)));
779 // While a run goes, its latest line; then the line it ended on.
780 const line = running === undefined ? detail : lastLine(buffer);
781 // Only complete lines: a URL still being written is not offered.
782 const url = running === 'auth' ? manualUrl(buffer.slice(0, buffer.lastIndexOf('\n') + 1)) : undefined;
783 return band($.ui.resolve(e), {
784 state: shown,
785 tint,
786 ...(line === undefined ? {} : { detail: line }),
787 ...(running === undefined ? {} : { task: running }),
788 ...(url === undefined ? {} : { url }),
789 ...(cliMissing ? { cliMissing } : {}),
790 ...(noShell ? { noShell } : {}),
791 dismiss: async () => {
792 dismissal = { key, value: shown };
793 try {
794 await $.store.set(key, shown);
795 } catch {
796 // Kept for this session only: the next one shows the band again.
797 }
798 portsOf($).invalidate();
799 },
800 signIn: () => startSignIn(portsOf($)),
801 index: () => startIndex(portsOf($)),
802 });
803 });
804}
805
806/**
807 * Starts the band over for a new conversation (`/clear`, `/resume`, `/branch`).
808 * Not set up and no project stay: they describe the process and the
809 * repository, not the conversation. A CLI run still going keeps `running`: its
810 * loop clears it when the child exits, so sign-in and indexing never overlap,
811 * and the changed generation tells it not to act on what it finds.
812 */
813export function resetOnboarding(): void {
814 generation += 1;
815 if (state !== 'not-set-up' && state !== 'no-project') {
816 state = undefined;
817 detail = undefined;
818 }
819 buffer = '';
820 cliMissing = false;
821 logged = false;
822}
823hooks/primpact.ts 184 lines1import type { EngineInterface, On, PluginOptions } from 'claude-code';
2import { type Blast, blastRadius } from './blast';
3import { type GhPrCreate, ghPrCreate } from './classify';
4import { absolute, GIT, GIT_ENV, GIT_TIMEOUT_MS, isConfigured, plural, projectRoot, relativeTo, stringArg, withinDeadline } from './lib';
5import { branded } from './theme';
6
7/** What happens before `gh pr create`. */
8type Mode = 'require' | 'inform' | 'off';
9
10const MODES: readonly Mode[] = ['require', 'inform', 'off'];
11
12/**
13 * How long `gh pr create` waits for the impact lookup before it goes ahead
14 * without the section. The hook's own time limit pauses while `$.mcp.call`
15 * runs, so a slow server would otherwise hold the command for code_intel's
16 * full timeout.
17 */
18export const PR_DEADLINE_MS = 8000;
19
20/** An `## Impact` heading at a line start or after whitespace or a quote (`--body "## Impact`). */
21const HEADING = /(^|[\s"'])##\s+Impact\b/m;
22
23const MOST_AFFECTED = 5;
24const MAX_EXPORTS = 10;
25
26const INSTRUCTION = 'Add this Impact section to the PR body and run gh pr create again.';
27
28let mode: Mode = 'inform';
29
30/** The branches require mode has refused once, keyed by project root and branch. */
31const refused = new Set<string>();
32
33function modeOf(value: unknown): Mode {
34 return MODES.find((m) => m === value) ?? 'inform';
35}
36
37function quoted(names: readonly string[]): string {
38 return names.map((n) => `\`${n}\``).join(', ');
39}
40
41/**
42 * The PR body's `## Impact` section for the `changed` project-relative files
43 * and their blast radius: the counts, the five dependents that import the
44 * most changed files, up to ten of the changed files' symbols other files
45 * import, and where the numbers come from.
46 */
47export function buildImpactSection(changed: string[], blast: Blast): string {
48 const lines = [
49 '## Impact',
50 '',
51 `- **Changed files:** ${changed.length}`,
52 `- **Downstream dependents:** ${blast.dependents.length}${blast.atLimit === undefined ? '' : '+'} (${plural(blast.tests, 'test file')})${
53 blast.skipped === undefined ? '' : `, of the first ${changed.length - blast.skipped} changed files`
54 }`,
55 ];
56 if (blast.dependents.length > 0) {
57 lines.push(`- **Most affected:** ${quoted(blast.dependents.slice(0, MOST_AFFECTED))}`);
58 }
59 if (blast.exports.length > 0) {
60 const more = blast.exports.length - MAX_EXPORTS;
61 const shown = quoted(blast.exports.slice(0, MAX_EXPORTS));
62 lines.push(`- **Exported symbols in use:** ${more > 0 ? `${shown}, +${more} more` : shown}`);
63 }
64 const asOf = blast.asOfCommit === undefined ? '' : ` as of ${blast.asOfCommit}`;
65 lines.push(
66 '',
67 `_From the code graph${asOf}; imports through tsconfig path aliases or export * barrels may be undercounted._`,
68 );
69 return lines.join('\n');
70}
71
72/** True when `line` writes `path` (`> path`, `>> path`, `tee path`): the file is not there yet, or is stale, until the command runs. */
73function writes(line: string, path: string): boolean {
74 const name = path.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
75 return new RegExp(`(?:>>?|\\btee(?:\\s+-a)?)\\s*['"]?${name}['"]?(?=[\\s;&|)]|$)`).test(line);
76}
77
78/**
79 * The remote's default branch: `origin/HEAD`, which only a clone or
80 * `git remote set-head` sets, else `origin/main` or `origin/master` when that
81 * ref exists. Undefined when none does; nothing is guessed.
82 */
83async function defaultBase($: EngineInterface, root: string): Promise<string | undefined> {
84 const head = await $.process.run([...GIT, 'symbolic-ref', 'refs/remotes/origin/HEAD'], { cwd: root, env: GIT_ENV, timeoutMs: GIT_TIMEOUT_MS });
85 const ref = head.stdout.trim();
86 if (head.exitCode === 0 && ref.startsWith('refs/remotes/') && ref.length > 'refs/remotes/'.length) return ref.slice('refs/remotes/'.length);
87 for (const name of ['main', 'master']) {
88 const found = await $.process.run([...GIT, 'rev-parse', '--verify', '--quiet', `refs/remotes/origin/${name}`], { cwd: root, env: GIT_ENV, timeoutMs: GIT_TIMEOUT_MS });
89 if (found.exitCode === 0) return `origin/${name}`;
90 }
91 return undefined;
92}
93
94/** The branch checked out in `root`, or undefined when git fails. */
95async function branchOf($: EngineInterface, root: string): Promise<string | undefined> {
96 const head = await $.process.run([...GIT, 'rev-parse', '--abbrev-ref', 'HEAD'], { cwd: root, env: GIT_ENV, timeoutMs: GIT_TIMEOUT_MS });
97 const branch = head.stdout.trim();
98 return head.exitCode === 0 && branch !== '' ? branch : undefined;
99}
100
101/**
102 * The impact section for the branch checked out in `root`, against the PR's
103 * base (`origin/<--base>`, else the remote's default branch). Undefined when
104 * a git command fails, nothing changed, or the lookup failed or missed
105 * `PR_DEADLINE_MS`. Rejects when a git command cannot start or times out.
106 */
107async function impactSection($: EngineInterface, pr: GhPrCreate, root: string, signal: AbortSignal): Promise<string | undefined> {
108 const base = pr.base !== undefined && pr.base !== '' ? `origin/${pr.base}` : await defaultBase($, root);
109 if (base === undefined) return undefined;
110 // `-z` gives each path as is, NUL-terminated; without it git quotes unusual names.
111 const diff = await $.process.run([...GIT, 'diff', '--no-ext-diff', '--no-renames', '--name-only', '-z', '--relative', `${base}...HEAD`], { cwd: root, env: GIT_ENV, timeoutMs: GIT_TIMEOUT_MS });
112 if (diff.exitCode !== 0) return undefined;
113 const changed = diff.stdout.split('\0').filter((path) => path !== '');
114 if (changed.length === 0) return undefined;
115 const blast = await withinDeadline(
116 (ms, o) => $.clock.sleep(ms, o),
117 blastRadius({ connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) }, root, changed, { exports: true }),
118 PR_DEADLINE_MS,
119 signal,
120 );
121 return blast === undefined ? undefined : buildImpactSection(changed, blast);
122}
123
124export function registerPrImpact(on: On, options: PluginOptions): void {
125 mode = modeOf(options.prImpact);
126 refused.clear();
127 if (mode === 'off') return;
128
129 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
130 const raw = stringArg(e, 'command') ?? '';
131 const pr = ghPrCreate(raw);
132 // A PR for another branch or repository is not the checkout's to describe.
133 if (pr === null || pr.head !== undefined || pr.repo !== undefined) return next(e);
134 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return next(e);
135 const session = absolute('.', await $.session.cwd());
136 const cwd = absolute(pr.dir ?? '.', session);
137 // git runs only under the session's directory, never one a `cd` in the command leads out to.
138 if (cwd !== session && relativeTo(session, cwd) === null) return next(e);
139 const root = await projectRoot(cwd, (p) => $.fs.exists(p));
140 if (root === null) return next(e);
141
142 if (mode === 'inform') {
143 // The lookup runs while the command does, so the command's result waits for it as little as possible.
144 // A git command that cannot start or times out shows no section.
145 const pending = impactSection($, pr, root, next.signal).catch(() => undefined);
146 const r = await next(e);
147 if (r.deny !== undefined || r.isError) return r;
148 const section = await pending;
149 if (section !== undefined) $.ui.log(`${branded('PR impact')}\n${section}`);
150 return r;
151 }
152
153 try {
154 // The raw line covers inline and heredoc bodies, whatever their quoting.
155 if (HEADING.test(raw) || (pr.body !== undefined && HEADING.test(pr.body))) return next(e);
156 // A body on standard input cannot be read here.
157 if (pr.bodyFile === '-') return next(e);
158 // A body file this command writes is checked through the command line above. A file that cannot be
159 // read has no heading: gh would fail on it too, so the refusal costs nothing.
160 if (pr.bodyFile !== undefined && !writes(raw, pr.bodyFile)) {
161 const text = await $.fs.read(absolute(pr.bodyFile, cwd)).catch(() => '');
162 if (HEADING.test(text)) return next(e);
163 }
164 const branch = await branchOf($, root);
165 if (branch === undefined) return next(e);
166 const key = `${root}\0${branch}`;
167 // Each branch is refused once, so the gate never loops.
168 if (refused.has(key)) return next(e);
169 const section = await impactSection($, pr, root, next.signal);
170 if (section === undefined) return next(e);
171 refused.add(key);
172 return { deny: `${branded('PR impact')}\n${section}\n\n${INSTRUCTION}` };
173 } catch {
174 // A git command that cannot start or times out.
175 return next(e);
176 }
177 });
178}
179
180/** Forgets the branches already refused, for a new conversation (`/clear`, `/resume`, `/branch`). */
181export function resetPrImpact(): void {
182 refused.clear();
183}
184hooks/session.ts 68 lines1import type { On } from 'claude-code';
2import { resetAdoption } from './adoption';
3import { forgetAgentLines, resetAugment } from './augment';
4import { forgetAgentBudget, resetBudgets } from './budget';
5import { resetFreshness } from './freshness';
6import { forgetAgentImpact, resetImpact } from './impact';
7import { isConfigured } from './lib';
8import { resetOnboarding } from './onboarding';
9import { resetPrImpact } from './primpact';
10import { resetRiskCache } from './risk';
11import { resetToolRows } from './toolrows';
12import { resetTurnSummary, summarizeTurn } from './turnsummary';
13
14/**
15 * Session lifecycle for the module's state, in one place: a new conversation
16 * (`/clear`, `/resume`, `/branch`) starts every budget and shown line over, and
17 * a subagent's state is dropped when its run ends. The main loop's answered
18 * turn also gets its impact summary line here.
19 */
20export function registerSession(on: On): void {
21 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async (_$, e, next) => {
22 resetBudgets();
23 resetAugment();
24 resetRiskCache();
25 resetImpact();
26 resetTurnSummary();
27 resetPrImpact();
28 resetToolRows();
29 resetOnboarding();
30 resetAdoption();
31 resetFreshness();
32 return next(e);
33 });
34
35 on('turn.complete', async ($, e, next) => {
36 if (e.agentId !== undefined) {
37 forgetAgentBudget(e.agentId);
38 forgetAgentLines(e.agentId);
39 forgetAgentImpact(e.agentId);
40 return next(e);
41 }
42 if (e.isAborted || e.reason !== 'answer') {
43 resetTurnSummary();
44 return next(e);
45 }
46 const r = await next(e);
47 try {
48 if (!isConfigured(await $.env.get('CONSTELLATION_ACCESS_KEY'))) return r;
49 const line = await summarizeTurn(
50 {
51 exists: (p) => $.fs.exists(p),
52 mcp: { connect: (s) => $.mcp.connect(s), call: (s, t, a) => $.mcp.call(s, t, a) },
53 sleep: (ms, o) => $.clock.sleep(ms, o),
54 },
55 next.signal,
56 );
57 if (line === undefined) return r;
58 // A line another hook beneath already set stays, with this one under it.
59 return { ...r, text: r.text !== undefined && r.text !== e.answer ? `${r.text}\n${line}` : line };
60 } catch {
61 return r;
62 } finally {
63 // Every main-loop turn ends here, so the next one starts with an empty record, whatever happened above.
64 resetTurnSummary();
65 }
66 });
67}
68