Shows Cortex Hub tool calls above the prompt as a stacked bar, one color per category, with /cs session progress, tokens in and saved, and hit@k for code…

A Claude Code mod that draws this session's Cortex Hub tool calls above the prompt: a stacked bar with one color per category, the latest call, what the results cost and saved in tokens, how often the agent opened what a code lookup ranked, how many of its code searches went to cortex rather than grep, and where /cs stands. Each cortex tool row in the transcript gets a tag in its category's color.
◆ cortex ████████████████████████████████████████ 9 calls · last plan_quality 1.3s ✓
■ session 2 ■ knowledge 1 ■ memory 1 ■ code 3 ■ quality 1 ■ tasks 1
tokens ~3.3k in · ~9.8k saved est. │ lookups cortex 3 · grep 9 · 25% · 1 fallback │ hit@1 1/3 · …
/cs ● session ● recall ● changes ● tasks │ ● build ● typecheck ○ lint ○ report
While a call is running the tail reads ⟳ code_search; a failed call turns it into ✗ and adds · 1 err. In a cortex project the band shows no cortex session yet — run /cs until the first cortex_session_start; elsewhere it stays out of the way until a cortex tool runs.
Under each cortex tool row:
● cortex-hub - cortex_code_search (MCP)(query: "hybrid search")
■ code · 233ms ✓ · ~700 tok · 3 files ~13k · used #2
~700 tok is what the result put into the context, 3 files ~13k the files it pointed at and their size, and used #2 says the agent went on to open the second of them (missed: it opened other files instead). A search or a check says how its result read instead: 2 found · top 0.61, nothing found, risk low, 7.5/10.
Needs Claude Code 2.1.287 or later in the terminal or the desktop app.
The Claude Code extension's chat panel (2.1.288) does not draw mod UI, so run Claude Code in the IDE's terminal instead: set "claudeCode.useTerminal": true in the IDE's settings, and the extension opens claude in an integrated terminal, where the band, the tags and the pane all show. In Antigravity the setting lives in its user settings.json, and its CLI is antigravity-ide (/Applications/Antigravity IDE.app/Contents/Resources/app/bin/ on macOS).
The mod also knows how to draw on the extension's surface, for when it does: there is no band above that prompt, so the newest cortex row carries the bar, the measures and the /cs checklist, and /cortex-calls puts them above its list.
From a clone, for one session:
claude --plugin-dir mods/cortex-bar
Or from this repo as a marketplace, which is also how the IDE extension gets it (it reads the same installed plugins as the CLI; it has no --plugin-dir):
claude plugin marketplace add lktiep/cortex-hub # or the path of a clone
claude plugin install cortex-bar@cortex-hub # --scope project to share it with the repo
Then start a new conversation in the extension (or the terminal).
| Command | What it does |
|---|---|
/cortex-bar | Show or hide the band and the row tags (remembered) |
/cortex-bar on / off | Show / hide explicitly |
/cortex-bar reset | Clear the call counts and the measures |
/cortex-calls | Open a pane with the measures and the last 50 calls |
◆ 10 cortex calls · 1 failed
tokens ~3.3k in · ~9.8k saved est. │ lookups cortex 3 · grep 9 · 25% · 1 fallback │ hit@1 1/3 · …
Per tool ──────────────────────────────────────────────────────────────────────────
tool calls ok avg ~tok saved quality
■ knowledge_search 1 1 612ms ~600 · 1/1 found · last 2 found
■ code_search 2 2 1.3s ~1.4k ~9.8k hit@1 0/2 · hit@3 1/2 · …
■ plan_quality 1 1 1.5s ~225 · 0/1 passed · last 7.5/10
Lookups estimate · cortex 25% of what it could answer ──────────────────────────────
cortex 3 code_search, code_context, code_impact, cypher
symbol 5 code_context could answer
word or regex 4 code_search could answer
literal 2 rg is right
in known files 1 rg is right
file by name 1 find or Glob is right
not repo code 1 logs, tmp, other dirs
fallback 1 grep within 3 calls of a cortex lookup
Calls newest first ────────────────────────────────────────────────────────────────
17:55:33 ✗ ■ code_reindex 30s ~0 MCP error…
17:54:57 ✓ ■ plan_quality 1.5s ~225 7.5/10 plan=1. A…
17:54:29 ✓ ■ code_search 1.3s ~700 3 files ~13k · used #2 query=whe…
Every column keeps its width, and only the last one in a row is cut, so nothing wraps. A narrow pane drops avg, then ~tok, then ok from the table, and the calls swap their tokens and arguments for the result. Where no pane can be placed (a claude -p run) the list comes back as text instead.
Everything is counted in this Claude Code session, from what passes through it; the hub's own cortex_tool_stats counts on the server, with its own baseline.
~3.3k in, ~700 tok): the characters of each cortex result over 4, the rule the hub's stats use. An estimate of what the result added to the context.code_search, code_context, code_impact and cypher. The mod reads the file paths in a lookup's result, up to ten, in the order they appear, and sizes each file on disk. A Read, Edit, Write or notebook edit of one of those files, or a Bash command naming it, is the agent using the lookup; the rank of the best one opened is used #n. A file can count for any of the last three lookups that returned it. A Read or Edit of a project file none of them returned is a stray, and a lookup that closes (three newer ones came after it) with strays and nothing used is missed; one with neither is unused and not judged.~9.8k saved est.) is, per lookup: the tokens of the files it pointed at (each capped at 25k, about what one Read shows), less what the result itself cost, less the files the agent opened anyway. A missed lookup saved nothing. It is an upper bound: it assumes that without the lookup the agent would have read every one of those files. cortex_tool_stats uses a fixed per-tool baseline instead, so the two differ.lookups cortex 3 · grep 9 · 25%) weigh the cortex code lookups against the searches the agent ran itself: rg, grep, git grep, find, fd and the like in a Bash command (not one fed by a pipe, which filters another command's output), and the Grep and Glob tools. Each gets a kind from its pattern and where it looks:| Kind | What it is | Counted as |
|---|---|---|
| symbol | an identifier like verifyKey or HybridSearch | code_context could answer |
| word or regex | any other pattern over the repo | code_search could answer |
| literal | an env var, a config key, a quoted string, a path | rg is right |
| in known files | any pattern in files named outright | rg is right |
| file by name | find, fd, git ls-files, rg --files, Glob | find or Glob is right |
| not repo code | logs, temp folders, transcripts, node_modules, stdin | not counted against |
grep in the band is the symbol and word searches, and the share is the cortex lookups over those plus themselves: how much of what cortex could have answered went to it. A fallback is one of those searches within three calls of a cortex lookup in the same agent loop, which usually means the lookup did not answer. The kinds are an estimate: they read the command, not what the agent meant, so a word search may well have been better as a grep. A denied call ran nothing and is not counted.
knowledge_search, the number of memory_search results, the risk_level of detect_changes (unknown is a failed lookup, not a pass), the score and verdict of plan_quality.The measures start over with a new cortex_session_start, /clear or /cortex-bar reset. They never hold up or change a tool's result: sizes are read in the background, and an output in a shape the parsers do not know is left unjudged.
| Category | Tools |
|---|---|
| session | session_start, session_end, changes, health, list_repos |
| knowledge | knowledge_search, knowledge_store |
| memory | memory_search, memory_store, memory_delete |
| code | code_search, code_context, code_impact, code_reindex, cypher, detect_changes |
| quality | quality_report, plan_quality, tool_stats |
| tasks | task_* |
| other | any cortex tool not listed |
tool.call hook on every mcp__<server>__cortex_* tool, whatever the MCP server is called. A new cortex_session_start starts the counts over.tool.call hook on Read, Edit, Write, NotebookEdit and Bash, after the tool ran; a denied or failed call does not count.tool.call hook on every tool: a search gets its kind, any other call moves the fallback window of its agent loop. Subagents count in the same totals./cs checklist and the gates come from the markers .claude/hooks/ writes to .cortex/.session-state/, the same evidence the hooks gate on. A marker counts only when it holds the tool= line the tracker writes, so an empty or hand-made file stays ○. The mod rereads them shortly after cortex, Bash and edit tools and at the end of each turn, so build/typecheck/lint turn green when the gates pass and go back to ○ after the next write clears them. gate-off shows as ⚠ gates off.The argument shown for a call is its first non-empty query, name, target, title, repo, taskId, plan or content, cut to 48 characters. Fields whose name looks like a credential (key, token, secret, password, authorization) are never shown. Nothing is sent anywhere: the mod only reads what passes through this Claude Code session.
The same measures, read back from Claude Code's transcripts of earlier sessions:
node mods/cortex-bar/scripts/lookup-audit.mjs # this directory's newest 5 sessions
node mods/cortex-bar/scripts/lookup-audit.mjs --last 0 # all of them
node mods/cortex-bar/scripts/lookup-audit.mjs ~/.claude/projects/<project-folder> session.jsonl
started agents calls cortex code lookups symbol word other share fallback
2026-10-01 09:12 4 2442 69 12 49 45 454 11% 1
2026-10-02 21:01 2 1375 119 21 24 22 294 31% 4
all 6 3817 188 33 73 67 748 19% 5
started requests input cache write cache read output cache hit prompt/call
2026-10-01 09:12 2363 4.7k 5.0M 252.1M 1.8M 98% 105k
2026-10-02 21:01 1204 2.5k 4.1M 135.1M 1.3M 97% 101k
all 3567 7.2k 9.1M 387.2M 3.1M 97% 104k
cortex tool calls err result ok used missed unused hit@1 hit@3 hit@10
detect_changes 30 2 26/28 - - - - - -
code_search 20 1 18/19 9 5 5 6/14 9/14 10/14
…
Offered but never called (2 of 26): memory_delete, task_submit_strategy
Each session is the main transcript and its subagents', and each agent loop is replayed on its own, as the hooks see it live. Per cortex tool it adds the errors, how many results said something (result ok), and for the code lookups whether the agent opened what they named. The tokens come from each model response's usage, counted once per response (a response is written as one line per content block). cache hit is the share of the prompt read from the cache. It stays high whatever the agent does, because every request resends the whole conversation and only the newest part is not cached yet; what a better lookup changes is prompt/call, cache write and the number of requests. Offered but never called lists the cortex tools the session had but never used. It prints counts only: no command, path, result or session id leaves the transcripts.
cd mods/cortex-bar
claude plugin validate .
claude plugin test
The first load (claude --plugin-dir mods/cortex-bar) generates the engine's types into .claude-plugin/types/ (ignored by git), which tsconfig.json extends. After that the hooks, plain JS with JSDoc types, typecheck strictly:
node_modules/.bin/tsc -p mods/cortex-bar/tsconfig.json --allowJs --checkJs --noEmit
hooks/model.js holds everything that decides what is drawn, as pure functions, and hooks/lookups.js how a search command reads; hooks/register.js times calls, reads the markers and turns rows into elements. scripts/replay.js runs a transcript through the same functions, and scripts/lookup-audit.mjs only reads files and prints. The tests mount every drawing on the surfaces that raise it: the band on terminal and desktop, the tool rows, folded groups and the pane on vscode as well.
hooks/register.js 557 lines1// cortex-bar: the Cortex Hub tool calls of this session, drawn above the prompt as a
2// stacked bar (one color per category) with where /cs stands, and a colored tag under each
3// cortex tool row. What it draws is model.js; this file times and measures the calls,
4// follows which files the agent opens after a lookup, reads the hooks' markers and turns
5// rows into elements.
6
7import {
8 ALWAYS_JUDGED,
9 CORTEX_TOOL,
10 LOOKUP_TOOLS,
11 LOOKUP_WINDOW,
12 MARKERS,
13 addCall,
14 applyUse,
15 bandModel,
16 categoryOf,
17 closeLookup,
18 emptyStats,
19 estimateTokens,
20 firstLine,
21 fitRow,
22 groupTag,
23 hitPaths,
24 inProject,
25 newLookup,
26 paneModel,
27 qualityOf,
28 rowTag,
29 shortName,
30 summarizeArgs,
31 textProps,
32 withSizes,
33} from './model.js'
34import { countTool, emptyLookupCounts, lookupKindOf } from './lookups.js'
35
36const STATE_DIR = '.cortex/.session-state'
37const PANE_ID = 'cortex-calls'
38const RECENT_LIMIT = 50
39const REFRESH_DELAY_MS = 400
40/** How many finished calls keep their time for their tags. */
41const TIMED_LIMIT = 200
42/** How many lookups are kept for their tags. */
43const LOOKUP_LIMIT = 500
44/**
45 * The surfaces that raise no AbovePrompt (Claude Code for VS Code, which Antigravity and
46 * Cursor run too, and the mobile app): there the newest cortex row carries the band.
47 */
48const NO_BAND = ['vscode', 'mobile']
49/** Cells the transcript indents a tool row's lines by, kept free so a tag never wraps. */
50const TRANSCRIPT_INDENT = 6
51
52/**
53 * @typedef {import('claude-code').EngineInterface} Engine
54 * @typedef {import('./model.js').Call} Call
55 * @typedef {import('./model.js').Running} Running
56 * @typedef {import('./model.js').Row} Row
57 * @typedef {import('./model.js').Verdict} Verdict
58 * @typedef {import('./model.js').Lookup} Lookup
59 * @typedef {import('./model.js').Use} Use
60 * @typedef {import('./lookups.js').LookupCounts} LookupCounts
61 */
62
63// Module state lives as long as this load: a hot reload or a new session starts it over.
64let visible = true
65let stats = emptyStats()
66/** @type {Call[]} */
67let recent = []
68/** @type {Running[]} */
69let inFlight = []
70/** @type {string[] | null} */
71let markers = null
72/**
73 * Finished calls by tool_use_id, for the tags under their rows: kept apart from `recent`
74 * so a new session or a reset does not strip the times off the rows already drawn.
75 * @type {Map<string, Call>}
76 */
77const timed = new Map()
78let callIds = 0
79/** @type {import('claude-code').Timer | null} */
80let refreshTimer = null
81/** The project root, which repo-relative hit paths are under. */
82let root = ''
83/**
84 * Lookups by tool_use_id, oldest first. A reset closes them and starts a new epoch: the
85 * measures count the current epoch only, the tags keep showing the older ones.
86 * @type {Map<string, Lookup>}
87 */
88const lookups = new Map()
89let epoch = 0
90/** Cortex code lookups against the native searches, by kind. */
91let counts = emptyLookupCounts()
92
93function resetCalls() {
94 stats = emptyStats()
95 recent = []
96 counts = emptyLookupCounts()
97 for (const [id, lookup] of lookups) lookups.set(id, closeLookup(lookup))
98 epoch += 1
99}
100
101/** The lookups the measures count. */
102function currentLookups() {
103 return [...lookups.values()].filter((lookup) => lookup.epoch === epoch)
104}
105
106/** The lookups a file opened now still counts for, oldest first. */
107function openLookups() {
108 return currentLookups().filter((lookup) => !lookup.closed)
109}
110
111/**
112 * The /cs markers in the project, or null when it has no state dir (not a cortex project).
113 * A marker counts only with the `tool=` evidence the tracker writes, which is what the
114 * gates require too; gate-off holds the reason someone gave instead.
115 * @param {Engine} $
116 * @returns {Promise<string[] | null>}
117 */
118async function readMarkers($) {
119 try {
120 const dir = (await $.session.root()) + '/' + STATE_DIR
121 if (!(await $.fs.exists(dir))) return null
122 const entries = await $.fs.list(dir)
123 const present = MARKERS.filter((name) =>
124 entries.some((entry) => entry.name === name && entry.kind === 'file' && entry.size > 0),
125 )
126 const texts = await Promise.all(present.map((name) => $.fs.read(dir + '/' + name)))
127 return present.filter((name, i) =>
128 name === 'gate-off' ? texts[i]?.trim() !== '' : Boolean(texts[i]?.includes('tool=')),
129 )
130 } catch {
131 return markers
132 }
133}
134
135/** @param {Engine} $ */
136async function refreshMarkers($) {
137 const found = await readMarkers($)
138 if (JSON.stringify(found) === JSON.stringify(markers)) return
139 markers = found
140 $.ui.invalidate('ui.render')
141}
142
143/**
144 * The tracker writes its marker after the tool returns, so look a moment later.
145 * @param {Engine} $
146 */
147function scheduleRefresh($) {
148 refreshTimer?.cancel()
149 refreshTimer = $.clock.after(REFRESH_DELAY_MS, () => {
150 refreshTimer = null
151 refreshMarkers($)
152 })
153}
154
155/**
156 * @param {import('claude-code').ToolCallResult} result
157 * @returns {Verdict}
158 */
159function verdictOf(result) {
160 if (result.deny !== undefined) return { ok: false, error: 'denied: ' + firstLine(result.deny) }
161 if (result.isError) return { ok: false, error: firstLine(result.text ?? 'error') }
162 return { ok: true, error: '' }
163}
164
165/**
166 * The result as the model read it: core sets `text`; a hook's own answer may carry a
167 * string `result` instead.
168 * @param {import('claude-code').ToolCallResult | undefined} result
169 */
170function resultText(result) {
171 if (!result || result.deny !== undefined) return ''
172 if (typeof result.text === 'string') return result.text
173 return typeof result.result === 'string' ? result.result : ''
174}
175
176/**
177 * Sizes the files a lookup returned, after the fact: the tool's answer never waits on it.
178 * @param {Engine} $
179 * @param {string} toolUseId
180 * @param {string[]} paths
181 */
182async function measureHits($, toolUseId, paths) {
183 const bytes = await Promise.all(
184 paths.map((path) =>
185 $.fs
186 .stat(path.startsWith('/') || root === '' ? path : root + '/' + path)
187 .then((stat) => (stat.kind === 'file' ? stat.size : 0))
188 .catch(() => 0),
189 ),
190 )
191 const lookup = lookups.get(toolUseId)
192 if (!lookup) return
193 lookups.set(toolUseId, withSizes(lookup, bytes))
194 $.ui.invalidate('ui.render')
195}
196
197/**
198 * A new lookup: the oldest open ones beyond the window close, and its hits get sized.
199 * @param {Engine} $
200 * @param {Call} call
201 * @param {string} text
202 */
203function startLookup($, call, text) {
204 const paths = hitPaths(text)
205 if (paths.length === 0 && !ALWAYS_JUDGED.includes(call.name)) return
206 lookups.set(
207 call.toolUseId,
208 newLookup({ toolUseId: call.toolUseId, name: call.name, epoch, returned: call.tokens, paths }),
209 )
210 const open = openLookups()
211 for (const old of open.slice(0, Math.max(0, open.length - LOOKUP_WINDOW))) {
212 lookups.set(old.toolUseId, closeLookup(old))
213 }
214 for (const oldest of lookups.keys()) {
215 if (lookups.size <= LOOKUP_LIMIT) break
216 lookups.delete(oldest)
217 }
218 if (paths.length > 0) measureHits($, call.toolUseId, paths)
219}
220
221/**
222 * A file the agent opened, counted for the open lookups.
223 * @param {Engine} $
224 * @param {Use} use
225 */
226function noteUse($, use) {
227 const open = openLookups()
228 if (open.length === 0) return
229 const after = applyUse(open, use)
230 let changed = false
231 after.forEach((lookup, i) => {
232 if (lookup === open[i]) return
233 lookups.set(lookup.toolUseId, lookup)
234 changed = true
235 })
236 if (changed) $.ui.invalidate('ui.render')
237}
238
239/**
240 * @param {Engine} $
241 * @param {Running} started
242 * @param {Verdict} verdict
243 * @param {import('claude-code').ToolCallResult} [result]
244 */
245async function finishCall($, started, verdict, result) {
246 const endedAt = await $.clock.now().catch(() => started.at)
247 inFlight = inFlight.filter((call) => call.id !== started.id)
248 const text = resultText(result)
249 /** @type {Call} */
250 const call = {
251 toolUseId: started.toolUseId,
252 name: started.name,
253 category: categoryOf(started.name),
254 args: started.args,
255 at: endedAt,
256 ms: endedAt - started.at,
257 tokens: estimateTokens(text),
258 ...verdict,
259 }
260 // Measuring is best effort: a result in a shape the parsers do not expect is left
261 // unjudged, never an error in the tool's answer.
262 try {
263 const quality = verdict.ok ? qualityOf(started.name, text) : undefined
264 if (quality) call.quality = quality
265 if (verdict.ok && LOOKUP_TOOLS.includes(started.name)) startLookup($, call, text)
266 } catch {
267 // left unjudged
268 }
269 stats = addCall(stats, call)
270 recent = [...recent, call].slice(-RECENT_LIMIT)
271 timed.set(call.toolUseId, call)
272 for (const oldest of timed.keys()) {
273 if (timed.size <= TIMED_LIMIT) break
274 timed.delete(oldest)
275 }
276 $.ui.invalidate('ui.render')
277 scheduleRefresh($)
278}
279
280/**
281 * The pane, or the same list as text where no pane can be placed (a `-p` run).
282 * @param {Engine} $
283 * @returns {Promise<import('claude-code').CommandRunResult>}
284 */
285async function openCalls($) {
286 const opened = await $.ui.open({
287 id: PANE_ID,
288 title: 'Cortex calls',
289 focus: true,
290 closeOnEscape: true,
291 })
292 if (opened.isPlaced) return {}
293 const rows = paneModel({ stats, recent, inFlight, lookups: currentLookups(), counts })
294 return { text: rows.map((row) => row.map((span) => span.text).join('')).join('\n') }
295}
296
297/**
298 * The band's rows for a transcript row on a surface without the band, when that row holds
299 * the newest cortex call; nothing anywhere else.
300 * @param {{ surface: string, viewport?: { columns: number } }} e
301 * @param {(string | undefined)[]} toolUseIds the cortex calls the row draws
302 * @returns {Row[]}
303 */
304function bandBelow(e, toolUseIds) {
305 if (!NO_BAND.includes(e.surface)) return []
306 const newest = inFlight[inFlight.length - 1] ?? recent[recent.length - 1]
307 if (!newest || !toolUseIds.includes(newest.toolUseId)) return []
308 const columns = Math.min(transcriptColumns(e) ?? 80, 100)
309 return bandModel({
310 stats,
311 recent,
312 inFlight,
313 markers,
314 lookups: currentLookups(),
315 counts,
316 columns,
317 maxRows: 4,
318 })
319}
320
321/**
322 * Cells a line under a transcript row has, less the transcript's own indent; unknown
323 * where the surface has not measured.
324 * @param {{ viewport?: { columns: number } }} e
325 */
326function transcriptColumns(e) {
327 return e.viewport ? Math.max(20, e.viewport.columns - TRANSCRIPT_INDENT) : undefined
328}
329
330/**
331 * One line per row. A Text shrinks and wraps when its row runs out of room, which breaks
332 * the columns, so each span sits in a Box that keeps its width; only a span marked
333 * `truncate` gives way, and it is cut short instead of wrapping. A row whose fixed spans
334 * are wider than `columns` is cut first.
335 * @param {import('claude-code').ElementConstructor<import('claude-code').BoxProps>} Box
336 * @param {import('claude-code').ElementConstructor<import('claude-code').TextProps>} Text
337 * @param {Row[]} rows
338 * @param {number | undefined} columns
339 */
340function drawRows(Box, Text, rows, columns) {
341 return rows.map((row) =>
342 Box({
343 flexDirection: 'row',
344 children: fitRow(row, columns).map((span) =>
345 Box({ flexShrink: span.truncate ? 1 : 0, children: [Text(textProps(span))] }),
346 ),
347 }),
348 )
349}
350
351/** @param {import('claude-code').On} on */
352export function register(on) {
353 on('session.start', async ($, e, next) => {
354 const result = await next(e)
355 await $.command.register({
356 name: 'cortex-bar',
357 description: 'Show or hide the Cortex tool-call bar above the prompt',
358 argumentHint: '[on|off|reset]',
359 immediate: true,
360 })
361 await $.command.register({
362 name: 'cortex-calls',
363 description: 'List the Cortex tool calls of this session',
364 immediate: true,
365 })
366 visible = (await $.store.get('visible')) !== false
367 root = await $.session.root().catch(() => '')
368 markers = await readMarkers($)
369 $.ui.invalidate('ui.render')
370 return result
371 })
372
373 // /clear starts a new conversation and session-init.sh wipes the markers with it.
374 on('classic.SessionStart', { source: ['clear', 'resume', 'fork'] }, async ($, e, next) => {
375 const result = await next(e)
376 if (e.source === 'clear') resetCalls()
377 $.ui.invalidate('ui.render')
378 scheduleRefresh($)
379 return result
380 })
381
382 on('command.run', { command: ['cortex-bar', 'cortex-calls'] }, async ($, e) => {
383 if (e.command === 'cortex-calls') return openCalls($)
384 const arg = e.args.trim().toLowerCase()
385 if (arg === 'reset') {
386 resetCalls()
387 $.ui.invalidate('ui.render')
388 return { text: 'cortex-bar: call counts cleared' }
389 }
390 if (arg !== '' && arg !== 'on' && arg !== 'off') {
391 return { text: 'usage: /cortex-bar [on|off|reset]' }
392 }
393 visible = arg === '' ? !visible : arg === 'on'
394 await $.store.set('visible', visible)
395 $.ui.invalidate('ui.render')
396 return { text: visible ? 'cortex-bar: shown' : 'cortex-bar: hidden (/cortex-bar shows it)' }
397 })
398
399 // Every cortex tool, whatever the MCP server is named: mcp__<server>__cortex_<name>.
400 on('tool.call', { tool: CORTEX_TOOL }, async ($, e, next) => {
401 const name = shortName(e.tool)
402 if (name === 'session_start') resetCalls()
403 /** @type {Running} */
404 const started = {
405 id: ++callIds,
406 toolUseId: e.tool_use_id,
407 name,
408 args: summarizeArgs(e),
409 at: await $.clock.now(),
410 }
411 inFlight = [...inFlight, started]
412 $.ui.invalidate('ui.render')
413 /** @type {import('claude-code').ToolCallResult} */
414 let result
415 try {
416 result = await next(e)
417 } catch (err) {
418 await finishCall($, started, { ok: false, error: 'threw: ' + firstLine(err) })
419 throw err
420 }
421 await finishCall($, started, verdictOf(result), result)
422 return result
423 })
424
425 // A file opened after a lookup says whether the lookup found it: a Read or an edit of
426 // it, or a command that names it. Build, typecheck and lint run in Bash and writes clear
427 // the gates: only the markers know, so look again after any of these but a Read.
428 on(
429 'tool.call',
430 { tool: ['Read', 'Bash', 'Edit', 'Write', 'NotebookEdit'] },
431 async ($, e, next) => {
432 const result = await next(e)
433 if (e.tool !== 'Read' && markers !== null) scheduleRefresh($)
434 if (result.deny !== undefined || result.isError) return result
435 if (e.tool === 'Bash') {
436 noteUse($, { command: e.command })
437 } else {
438 const path = e.tool === 'NotebookEdit' ? e.notebook_path : e.file_path
439 // Only a file read or edited counts against a lookup; a new file is not a miss.
440 const stray = e.tool === 'Read' || e.tool === 'Edit' ? inProject(path, root) : undefined
441 noteUse($, stray === undefined ? { path } : { path, stray })
442 }
443 return result
444 },
445 )
446
447 // Every tool, to weigh the cortex code lookups against the searches that ran instead: a
448 // grep, a find, a Grep or a Glob gets its kind, any other call moves the fallback window
449 // of its loop. A denied call ran nothing and is left out.
450 on('tool.call', async ($, e, next) => {
451 const result = await next(e)
452 if (result.deny !== undefined) return result
453 try {
454 const cortex = CORTEX_TOOL.test(e.tool) && LOOKUP_TOOLS.includes(shortName(e.tool))
455 /** @type {Record<string, unknown>} */
456 const input = { ...e }
457 const kind = cortex ? null : lookupKindOf(e.tool, input, root)
458 counts = countTool(counts, { agent: e.agentId ?? '', cortex, kind })
459 if (kind !== null) $.ui.invalidate('ui.render')
460 } catch {
461 // A command the classifier cannot read is not counted.
462 }
463 return result
464 })
465
466 on('turn.complete', async ($, e, next) => {
467 const result = await next(e)
468 await refreshMarkers($)
469 return result
470 })
471
472 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
473 const below = await next(e)
474 if (!visible || e.props.hasSurvey) return below
475 const rows = bandModel({
476 stats,
477 recent,
478 inFlight,
479 markers,
480 columns: e.props.bodyColumns,
481 maxRows: e.props.maxRows,
482 lookups: currentLookups(),
483 counts,
484 })
485 if (rows.length === 0) return below
486 const { Box, Text } = $.ui.resolve(e)
487 const band = Box({
488 key: 'cortex-bar',
489 flexDirection: 'column',
490 children: drawRows(Box, Text, rows, e.props.bodyColumns),
491 })
492 return below ? Box({ flexDirection: 'column', children: [below, band] }) : band
493 })
494
495 // Every surface draws the tool rows. Where there is no band, the newest cortex row
496 // carries it, so /cs shows its bar and checklist in the editor too.
497 on('ui.render', { component: 'ToolUse' }, async ($, e, next) => {
498 const row = await next(e)
499 if (!visible || !CORTEX_TOOL.test(e.props.tool)) return row
500 const { Box, Text } = $.ui.resolve(e)
501 const tag = rowTag({
502 name: shortName(e.props.tool),
503 isRunning: e.props.isRunning,
504 isErrored: e.props.isErrored,
505 isInterrupted: e.props.isInterrupted,
506 call: timed.get(e.props.tool_use_id),
507 lookup: lookups.get(e.props.tool_use_id),
508 })
509 const below = [tag, ...bandBelow(e, [e.props.tool_use_id])]
510 return Box({
511 flexDirection: 'column',
512 children: [row, ...drawRows(Box, Text, below, transcriptColumns(e))],
513 })
514 })
515
516 // A folded run of calls draws one line and none of its ToolUse rows.
517 on('ui.render', { component: 'ToolGroup' }, async ($, e, next) => {
518 const group = await next(e)
519 const calls = e.props.calls.filter((call) => CORTEX_TOOL.test(call.tool))
520 if (!visible || e.props.isExpanded || calls.length === 0) return group
521 const { Box, Text } = $.ui.resolve(e)
522 const below = [
523 groupTag(calls.map((call) => shortName(call.tool))),
524 ...bandBelow(
525 e,
526 calls.map((call) => call.tool_use_id),
527 ),
528 ]
529 return Box({
530 flexDirection: 'column',
531 children: [group, ...drawRows(Box, Text, below, transcriptColumns(e))],
532 })
533 })
534
535 on('ui.render', { component: 'Pane' }, async ($, e, next) => {
536 if (e.requestId !== PANE_ID) return next(e)
537 const { Box, Text } = $.ui.resolve(e)
538 // The bar and checklist head the pane where no band shows them; the bare "run /cs"
539 // hint is left out, the list says as much.
540 const columns = Math.max(20, e.props.bodyColumns - 2)
541 const current = currentLookups()
542 const summary = NO_BAND.includes(e.surface)
543 ? bandModel({ stats, recent, inFlight, markers, counts, columns, maxRows: 2 })
544 : []
545 /** @type {Row[]} */
546 const rows = [
547 ...(summary.length > 1 ? [...summary, [{ text: ' ' }]] : []),
548 ...paneModel({ stats, recent, inFlight, lookups: current, counts, columns }),
549 ]
550 return Box({
551 flexDirection: 'column',
552 paddingX: 1,
553 children: drawRows(Box, Text, rows, columns),
554 })
555 })
556}
557hooks/model.js 1076 lines1// What cortex-bar draws, as plain data. Nothing here touches the mods API, so the tests
2// can check the bar and the pane without mounting anything, and register.js stays a thin
3// layer that turns rows of spans into Box and Text elements.
4
5import { LOOKUP_KINDS, emptyLookupCounts, formatShare, lookupShare } from './lookups.js'
6
7/**
8 * @typedef {{ text: string, color?: string, bold?: boolean, dim?: boolean, truncate?: boolean }} Span
9 * @typedef {Span[]} Row
10 * @typedef {{ id: number, toolUseId: string, name: string, args: string, at: number }} Running
11 * @typedef {{ ok: boolean, error: string }} Verdict
12 * @typedef {{ kind: 'found' | 'risk known' | 'passed', ok: boolean, tag: string }} Quality
13 * @typedef {{ toolUseId: string, name: string, category: string, args: string, at: number, ms: number, tokens: number, quality?: Quality } & Verdict} Call
14 * @typedef {{ path: string, rank: number, tokens: number | null }} Hit
15 * @typedef {{ toolUseId: string, name: string, epoch: number, returned: number, hits: Hit[], used: number | null, opened: string[], strays: string[], closed: boolean }} Lookup
16 * @typedef {'used' | 'missed' | 'unused' | 'open'} LookupState
17 * @typedef {{ path: string, stray?: string } | { command: string }} Use
18 * @typedef {{ count: number, used: number, missed: number, at1: number, at3: number, at10: number, saved: number, measured: number }} LookupMetrics
19 * @typedef {{ name: string, isRunning: boolean, isErrored: boolean, isInterrupted: boolean, call?: Call, lookup?: Lookup }} ToolRow
20 * @typedef {{ calls: number, errors: number, ms: number, tokens: number, good: number, judged: number, kind: string, last: string }} ToolStats
21 * @typedef {{ total: number, errors: number, tokens: number, byCategory: Record<string, number>, byTool: Record<string, ToolStats>, okNames: string[] }} Stats
22 * @typedef {'done' | 'partial' | 'todo'} StepState
23 * @typedef {{ label: string, state: StepState }} Step
24 * @typedef {{ steps: Step[], gates: Step[] | null, gateOff: boolean }} Progress
25 * @typedef {import('./lookups.js').LookupCounts} LookupCounts
26 * @typedef {{ stats: Stats, recent: Call[], inFlight: Running[], lookups?: Lookup[], counts?: LookupCounts }} Calls
27 */
28
29/**
30 * One color per category, in the order the bar stacks them. Raw rgb() colors, mid tones
31 * that read on a dark and a light theme; the states use the theme's own keys.
32 */
33export const CATEGORIES = [
34 { id: 'session', label: 'session', color: 'rgb(175,135,255)' },
35 { id: 'knowledge', label: 'knowledge', color: 'rgb(0,175,215)' },
36 { id: 'memory', label: 'memory', color: 'rgb(95,135,255)' },
37 { id: 'code', label: 'code', color: 'rgb(95,175,95)' },
38 { id: 'quality', label: 'quality', color: 'rgb(215,175,0)' },
39 { id: 'tasks', label: 'tasks', color: 'rgb(255,135,95)' },
40 { id: 'other', label: 'other', color: 'rgb(138,138,138)' },
41]
42
43const TITLE_COLOR = 'rgb(175,135,255)'
44const OTHER_COLOR = 'rgb(138,138,138)'
45const OK = 'success'
46const FAILED = 'error'
47const WAITING = 'warning'
48
49/**
50 * The markers .claude/hooks/track-quality.sh writes into .cortex/.session-state.
51 * They are the same evidence the commit gate reads, so the bar never disagrees with it.
52 */
53export const MARKERS = [
54 'session-started',
55 'knowledge-recalled',
56 'memory-recalled',
57 'changes-checked',
58 'tasks-checked',
59 'gate-build',
60 'gate-typecheck',
61 'gate-lint',
62 'quality-gates-passed',
63 'quality-reported',
64 'gate-off',
65]
66
67const SECRET_KEY = /key|token|secret|password|authorization/i
68/** What tool.call puts beside a tool's own arguments. */
69const RESERVED = ['tool', 'tool_use_id', 'agentId', 'consent']
70const SUMMARY_KEYS = ['query', 'name', 'target', 'title', 'repo', 'taskId', 'plan', 'content']
71
72/**
73 * `mcp__cortex-hub__cortex_code_search` → `code_search`
74 * @param {string} tool
75 */
76export function shortName(tool) {
77 const at = tool.lastIndexOf('__cortex_')
78 return at === -1 ? tool : tool.slice(at + '__cortex_'.length)
79}
80
81/** @param {string} name a short cortex tool name */
82export function categoryOf(name) {
83 if (/^(session_|changes$|health$|list_repos$)/.test(name)) return 'session'
84 if (name.startsWith('knowledge_')) return 'knowledge'
85 if (name.startsWith('memory_')) return 'memory'
86 if (/^(code_|cypher$|detect_changes$)/.test(name)) return 'code'
87 if (/^(quality_report|plan_quality|tool_stats)$/.test(name)) return 'quality'
88 if (name.startsWith('task_')) return 'tasks'
89 return 'other'
90}
91
92/** @param {string} category */
93function colorOf(category) {
94 return CATEGORIES.find((c) => c.id === category)?.color ?? OTHER_COLOR
95}
96
97/**
98 * One `key=value` hint for a call, never from a field that looks like a credential.
99 * @param {Record<string, unknown>} input the tool.call event: the tool's arguments
100 * @param {number} [max]
101 */
102export function summarizeArgs(input, max = 48) {
103 /** @param {string} key */
104 const rank = (key) => {
105 const i = SUMMARY_KEYS.indexOf(key)
106 return i === -1 ? SUMMARY_KEYS.length : i
107 }
108 /** @type {[string, string][]} */
109 const fields = []
110 for (const [key, value] of Object.entries(input)) {
111 if (RESERVED.includes(key) || SECRET_KEY.test(key)) continue
112 if (typeof value === 'string' && value.trim() !== '') fields.push([key, value])
113 }
114 const [best] = fields.sort(([a], [b]) => rank(a) - rank(b))
115 if (!best) return ''
116 const text = best[1].replace(/\s+/g, ' ').trim()
117 return best[0] + '=' + (text.length > max ? text.slice(0, max - 1) + '…' : text)
118}
119
120/**
121 * The first line of a message, cut to fit one row.
122 * @param {unknown} text
123 * @param {number} [max]
124 */
125export function firstLine(text, max = 60) {
126 const line = String(text).trim().split('\n')[0] ?? ''
127 return line.length > max ? line.slice(0, max - 1) + '…' : line
128}
129
130/** @param {number} ms */
131export function formatMs(ms) {
132 if (ms < 1000) return Math.max(0, Math.round(ms)) + 'ms'
133 return (ms / 1000).toFixed(ms < 10_000 ? 1 : 0) + 's'
134}
135
136/**
137 * Tokens in a text, by the same rule the hub's own usage stats use: four characters each.
138 * There is no tokenizer to ask, so every token figure the mod shows is this estimate.
139 * @param {string} text
140 */
141export function estimateTokens(text) {
142 return Math.ceil(text.length / 4)
143}
144
145/** @param {number} tokens `840`, `6.2k`, `120k`, `1.2M` */
146export function formatTokens(tokens) {
147 const n = Math.max(0, Math.round(tokens))
148 if (n < 1000) return String(n)
149 if (n < 9_950) return (n / 1000).toFixed(1) + 'k'
150 if (n < 999_500) return Math.round(n / 1000) + 'k'
151 return (n / 1_000_000).toFixed(1) + 'M'
152}
153
154/** @returns {Stats} */
155export function emptyStats() {
156 return { total: 0, errors: 0, tokens: 0, byCategory: {}, byTool: {}, okNames: [] }
157}
158
159/**
160 * Totals outlive the recent-calls list, which keeps only the newest calls.
161 * @param {Stats} stats
162 * @param {Call} call
163 * @returns {Stats}
164 */
165export function addCall(stats, call) {
166 const okNames =
167 call.ok && !stats.okNames.includes(call.name) ? [...stats.okNames, call.name] : stats.okNames
168 const tool = stats.byTool[call.name] ?? {
169 calls: 0,
170 errors: 0,
171 ms: 0,
172 tokens: 0,
173 good: 0,
174 judged: 0,
175 kind: '',
176 last: '',
177 }
178 const quality = call.quality
179 return {
180 total: stats.total + 1,
181 errors: stats.errors + (call.ok ? 0 : 1),
182 tokens: stats.tokens + call.tokens,
183 byCategory: {
184 ...stats.byCategory,
185 [call.category]: (stats.byCategory[call.category] ?? 0) + 1,
186 },
187 byTool: {
188 ...stats.byTool,
189 [call.name]: {
190 calls: tool.calls + 1,
191 errors: tool.errors + (call.ok ? 0 : 1),
192 ms: tool.ms + call.ms,
193 tokens: tool.tokens + call.tokens,
194 good: tool.good + (quality?.ok ? 1 : 0),
195 judged: tool.judged + (quality ? 1 : 0),
196 kind: quality?.kind ?? tool.kind,
197 last: quality?.tag ?? tool.last,
198 },
199 },
200 okNames,
201 }
202}
203
204/**
205 * How a result reads, for the tools whose output says so itself: how many documents a
206 * search found, the risk a diff got, the score a plan got. Undefined for the rest, and for
207 * an output in a shape this does not know.
208 * @param {string} name a short cortex tool name
209 * @param {string} text the result as the model read it
210 * @returns {Quality | undefined}
211 */
212export function qualityOf(name, text) {
213 if (name === 'knowledge_search' || name === 'memory_search') {
214 const heading = name === 'knowledge_search' ? /^### Result \d+:.*$/gm : /^### Memory \d+\b/gm
215 const found = text.match(heading) ?? []
216 const scores = found
217 .map((line) => /Score: (\d+(?:\.\d+)?)/.exec(line)?.[1])
218 .filter((score) => score !== undefined)
219 .map(Number)
220 if (found.length === 0) return { kind: 'found', ok: false, tag: 'nothing found' }
221 const top = scores.length > 0 ? ' · top ' + Math.max(...scores).toFixed(2) : ''
222 return { kind: 'found', ok: true, tag: found.length + ' found' + top }
223 }
224 if (name === 'detect_changes') {
225 const risk = /"risk_level":\s*"(\w+)"/.exec(text)?.[1]
226 return risk ? { kind: 'risk known', ok: risk !== 'unknown', tag: 'risk ' + risk } : undefined
227 }
228 if (name === 'plan_quality') {
229 const score = /Total Score:\s*(\d+(?:\.\d+)?)\/10\s+(APPROVED|NEEDS IMPROVEMENT)/.exec(text)
230 return score
231 ? { kind: 'passed', ok: score[2] === 'APPROVED', tag: score[1] + '/10' }
232 : undefined
233 }
234 return undefined
235}
236
237/** The tools that answer "where is it": what they return is judged by what gets opened. */
238export const LOOKUP_TOOLS = ['code_search', 'code_context', 'code_impact', 'cypher']
239/** Every cortex tool, whatever the MCP server is named: mcp__<server>__cortex_<name>. */
240export const CORTEX_TOOL = /^mcp__.+__cortex_/
241/** How many of the newest lookups a file the agent opens can still count for. */
242export const LOOKUP_WINDOW = 3
243/** Lookups judged even when their result names no file: an empty one is a miss too. */
244export const ALWAYS_JUDGED = ['code_search', 'code_context']
245/** How many results of a lookup count, as the retrieval benchmark counts them. */
246const HIT_LIMIT = 10
247/** One Read returns at most about this many tokens of a file, so a bigger file counts this. */
248const READ_CAP = 25_000
249/**
250 * A repo path with at least one folder and an extension: `apps/api/src/x.ts:12`,
251 * `[docs/x.md]`. What precedes it rules out the middle of a URL or of an absolute path.
252 */
253const PATH = /(?<![\w./:@-])(\/?(?:[\w.@-]+\/)+[\w.@-]*\.[A-Za-z][A-Za-z0-9]*)(?![\w/-])/g
254
255/**
256 * The files a lookup's result points to, in the order they first appear: that order is
257 * their rank.
258 * @param {string} text
259 * @param {number} [limit]
260 */
261export function hitPaths(text, limit = HIT_LIMIT) {
262 /** @type {string[]} */
263 const paths = []
264 for (const match of text.matchAll(PATH)) {
265 const path = (match[1] ?? '').replace(/^\.\//, '')
266 if (path !== '' && !paths.includes(path)) paths.push(path)
267 if (paths.length === limit) break
268 }
269 return paths
270}
271
272/**
273 * A path the way the hits name it: relative to the project root, or undefined outside it.
274 * @param {string} path
275 * @param {string} root
276 */
277export function inProject(path, root) {
278 if (!path.startsWith('/')) return path.replace(/^\.\//, '')
279 return root !== '' && path.startsWith(root + '/') ? path.slice(root.length + 1) : undefined
280}
281
282/**
283 * @param {{ toolUseId: string, name: string, epoch: number, returned: number, paths: string[] }} input
284 * @returns {Lookup}
285 */
286export function newLookup({ toolUseId, name, epoch, returned, paths }) {
287 return {
288 toolUseId,
289 name,
290 epoch,
291 returned,
292 hits: paths.map((path, i) => ({ path, rank: i + 1, tokens: null })),
293 used: null,
294 opened: [],
295 strays: [],
296 closed: false,
297 }
298}
299
300/**
301 * The hits with the size of each file, 0 for one that is not there (another repo's).
302 * @param {Lookup} lookup
303 * @param {number[]} bytes in the order of the hits
304 * @returns {Lookup}
305 */
306export function withSizes(lookup, bytes) {
307 return {
308 ...lookup,
309 hits: lookup.hits.map((hit, i) => ({
310 ...hit,
311 tokens: Math.min(READ_CAP, Math.ceil((bytes[i] ?? 0) / 4)),
312 })),
313 }
314}
315
316/**
317 * Whether `text` names `path` whole: on its own or at the end of a longer path.
318 * @param {string} text
319 * @param {string} path
320 */
321function mentions(text, path) {
322 for (let at = text.indexOf(path); at !== -1; at = text.indexOf(path, at + 1)) {
323 const before = text[at - 1] ?? ' '
324 const after = text[at + path.length] ?? ' '
325 if (!/[\w.@-]/.test(before) && !/[\w.@/-]/.test(after)) return true
326 }
327 return false
328}
329
330/**
331 * @param {Use} use
332 */
333function useText(use) {
334 return 'command' in use ? use.command : use.path
335}
336
337/**
338 * A file the agent opened after the lookup: a Read, an edit, or a command that names it.
339 * A hit sets `used` to the best rank opened so far. A file it did not return is a stray
340 * when the caller gives one (Reads and Edits inside the project); a command never is.
341 * @param {Lookup} lookup
342 * @param {Use} use
343 * @returns {Lookup}
344 */
345export function noteOpen(lookup, use) {
346 const text = useText(use)
347 const matched = lookup.hits.filter((hit) => mentions(text, hit.path))
348 if (matched.length === 0) {
349 const stray = 'stray' in use ? use.stray : undefined
350 if (stray === undefined || lookup.strays.includes(stray)) return lookup
351 return { ...lookup, strays: [...lookup.strays, stray] }
352 }
353 const best = Math.min(...matched.map((hit) => hit.rank))
354 return {
355 ...lookup,
356 used: lookup.used === null ? best : Math.min(lookup.used, best),
357 opened: [...new Set([...lookup.opened, ...matched.map((hit) => hit.path)])],
358 }
359}
360
361/**
362 * A file opened while several lookups are open: each one that returned it counts it, and
363 * only when none did is it a stray, of the newest.
364 * @param {Lookup[]} open oldest first
365 * @param {Use} use
366 * @returns {Lookup[]}
367 */
368export function applyUse(open, use) {
369 const text = useText(use)
370 const known = open.some((lookup) => lookup.hits.some((hit) => mentions(text, hit.path)))
371 if (known) {
372 const plain = 'path' in use ? { path: use.path } : use
373 return open.map((lookup) => noteOpen(lookup, plain))
374 }
375 return open.map((lookup, i) => (i === open.length - 1 ? noteOpen(lookup, use) : lookup))
376}
377
378/**
379 * @param {Lookup} lookup
380 * @returns {Lookup}
381 */
382export function closeLookup(lookup) {
383 return lookup.closed ? lookup : { ...lookup, closed: true }
384}
385
386/**
387 * used: a file it returned was opened. missed: it closed with only other files opened.
388 * unused: it closed with nothing opened. open: the agent may still act on it.
389 * @param {Lookup} lookup
390 * @returns {LookupState}
391 */
392export function lookupState(lookup) {
393 if (lookup.used !== null) return 'used'
394 if (!lookup.closed) return 'open'
395 return lookup.strays.length > 0 ? 'missed' : 'unused'
396}
397
398/**
399 * Tokens behind a lookup's hits, or null while their sizes are not known yet.
400 * @param {Lookup} lookup
401 */
402function tokensBehind(lookup) {
403 if (lookup.hits.some((hit) => hit.tokens === null)) return null
404 return lookup.hits.reduce((sum, hit) => sum + (hit.tokens ?? 0), 0)
405}
406
407/**
408 * What reading the hits' files instead would have cost, less what the lookup returned and
409 * the files that were opened anyway. An upper bound: it assumes every hit would have been
410 * opened to find the answer. A lookup the agent went past to other files saved nothing.
411 * @param {Lookup} lookup
412 */
413function savedBy(lookup) {
414 const behind = tokensBehind(lookup)
415 if (behind === null || lookup.hits.length === 0) return null
416 if (lookup.used === null && lookup.strays.length > 0) return 0
417 const opened = lookup.hits
418 .filter((hit) => lookup.opened.includes(hit.path))
419 .reduce((sum, hit) => sum + (hit.tokens ?? 0), 0)
420 return Math.max(0, behind - lookup.returned - opened)
421}
422
423/**
424 * hit@k over the lookups that were judged (used or missed), and the tokens they saved.
425 * @param {Lookup[]} lookups
426 * @returns {LookupMetrics}
427 */
428export function lookupMetrics(lookups) {
429 const metrics = { count: lookups.length, used: 0, missed: 0, at1: 0, at3: 0, at10: 0 }
430 let saved = 0
431 let measured = 0
432 for (const lookup of lookups) {
433 const state = lookupState(lookup)
434 if (state === 'missed') metrics.missed += 1
435 if (state === 'used' && lookup.used !== null) {
436 metrics.used += 1
437 if (lookup.used <= 1) metrics.at1 += 1
438 if (lookup.used <= 3) metrics.at3 += 1
439 if (lookup.used <= 10) metrics.at10 += 1
440 }
441 const by = savedBy(lookup)
442 if (by !== null) {
443 saved += by
444 measured += 1
445 }
446 }
447 return { ...metrics, saved, measured }
448}
449
450/**
451 * Where /cs stands. The cortex steps count a call seen in this session or a marker the
452 * hooks wrote (which covers calls made before the mod loaded). Build, typecheck and lint
453 * run in Bash, so only the markers know about them: `gates` is null without a state dir.
454 * @param {string[]} okNames
455 * @param {string[] | null} markers
456 * @returns {Progress}
457 */
458export function stepsFrom(okNames, markers) {
459 /** @param {string} name */
460 const seen = (name) => okNames.includes(name)
461 /** @param {string} marker */
462 const has = (marker) => markers != null && markers.includes(marker)
463 /** @param {boolean} done @returns {StepState} */
464 const state = (done) => (done ? 'done' : 'todo')
465 const knowledge = seen('knowledge_search') || has('knowledge-recalled')
466 const memory = seen('memory_search') || has('memory-recalled')
467 /** @type {StepState} */
468 const recall = knowledge && memory ? 'done' : knowledge || memory ? 'partial' : 'todo'
469 const steps = [
470 { label: 'session', state: state(seen('session_start') || has('session-started')) },
471 { label: 'recall', state: recall },
472 {
473 label: 'changes',
474 state: state(seen('changes') || seen('detect_changes') || has('changes-checked')),
475 },
476 { label: 'tasks', state: state(seen('task_pickup') || has('tasks-checked')) },
477 ]
478 if (markers == null) return { steps, gates: null, gateOff: false }
479 const allGates = has('quality-gates-passed')
480 const gates = [
481 { label: 'build', state: state(allGates || has('gate-build')) },
482 { label: 'typecheck', state: state(allGates || has('gate-typecheck')) },
483 { label: 'lint', state: state(allGates || has('gate-lint')) },
484 { label: 'report', state: state(seen('quality_report') || has('quality-reported')) },
485 ]
486 return { steps, gates, gateOff: has('gate-off') }
487}
488
489/**
490 * Split `width` cells between the categories in proportion to their calls. Every category
491 * that was used keeps at least one cell, and the cells left over go to the largest remainders.
492 * @param {Record<string, number>} byCategory
493 * @param {number} width
494 */
495export function barSegments(byCategory, width) {
496 const used = CATEGORIES.map((c) => ({ ...c, count: byCategory[c.id] ?? 0 })).filter(
497 (c) => c.count > 0,
498 )
499 const total = used.reduce((sum, c) => sum + c.count, 0)
500 if (total === 0 || width < used.length) return []
501 const cells = used.map((c) => {
502 const exact = (c.count / total) * width
503 return { id: c.id, color: c.color, exact, width: Math.max(1, Math.floor(exact)) }
504 })
505 let filled = cells.reduce((sum, c) => sum + c.width, 0)
506 while (filled > width) {
507 const widest = cells.reduce((a, b) => (b.width > a.width ? b : a))
508 widest.width -= 1
509 filled -= 1
510 }
511 while (filled < width) {
512 const behind = cells.reduce((a, b) => (b.exact - b.width > a.exact - a.width ? b : a))
513 behind.width += 1
514 filled += 1
515 }
516 return cells.map(({ id, color, width: w }) => ({ id, color, width: w }))
517}
518
519/** @type {Record<StepState, Span>} */
520const DOT = {
521 done: { text: '●', color: OK },
522 partial: { text: '◐', color: WAITING },
523 todo: { text: '○', dim: true },
524}
525
526/**
527 * @param {Step[]} items
528 * @param {string} [gap]
529 * @returns {Row}
530 */
531function stepSpans(items, gap = ' ') {
532 return items.flatMap((item) => [DOT[item.state], { text: ' ' + item.label + gap }])
533}
534
535/**
536 * `●●○○ tasks`: the dots alone, then the first step not done yet.
537 * @param {Step[]} items
538 * @returns {Row}
539 */
540function compactSteps(items) {
541 const next = items.find((item) => item.state !== 'done')
542 return [...items.map((item) => DOT[item.state]), { text: ' ' + (next?.label ?? 'done') + ' ' }]
543}
544
545/**
546 * @param {Call[]} recent
547 * @param {Running[]} inFlight
548 * @returns {Row}
549 */
550function lastCallSpans(recent, inFlight) {
551 const running = inFlight[inFlight.length - 1]
552 if (running) return [{ text: ' · ' }, { text: '⟳ ' + running.name, color: WAITING }]
553 const last = recent[recent.length - 1]
554 if (!last) return []
555 return [
556 { text: ' · last ' + last.name + ' ' + formatMs(last.ms) + ' ', dim: true },
557 last.ok ? { text: '✓', color: OK } : { text: '✗', color: FAILED },
558 ]
559}
560
561/**
562 * `■ code 3 ■ memory 1`, in the order the bar stacks them, for the categories used.
563 * @param {Record<string, number>} byCategory
564 * @param {string} [gap]
565 * @returns {Row}
566 */
567function legendSpans(byCategory, gap = ' ') {
568 return CATEGORIES.filter((c) => (byCategory[c.id] ?? 0) > 0).flatMap((c) => [
569 { text: '■ ', color: c.color },
570 { text: c.label + ' ' + byCategory[c.id] + gap },
571 ])
572}
573
574/** @param {Row} spans */
575const textLength = (spans) => spans.reduce((sum, s) => sum + [...s.text].length, 0)
576
577/**
578 * A row that cannot wrap. While its fixed spans fit, the truncating ones give way as the
579 * layout needs; past that they are left out and the row is cut short with an ellipsis.
580 * @param {Row} row
581 * @param {number | undefined} columns
582 * @returns {Row}
583 */
584export function fitRow(row, columns) {
585 if (columns === undefined || textLength(row.filter((s) => !s.truncate)) <= columns) return row
586 /** @type {Row} */
587 const out = []
588 let room = columns - 1
589 for (const span of row) {
590 if (span.truncate) continue
591 const chars = [...span.text]
592 if (chars.length > room) {
593 if (room > 0) out.push({ ...span, text: chars.slice(0, room).join('') })
594 break
595 }
596 out.push(span)
597 room -= chars.length
598 }
599 return [...out, { text: '…', dim: true }]
600}
601
602/**
603 * Text in a column `width` cells wide, cut with an ellipsis so a space always follows it.
604 * @param {string} text
605 * @param {number} width
606 */
607function cell(text, width) {
608 const chars = [...text]
609 return chars.length < width ? text.padEnd(width) : chars.slice(0, width - 2).join('') + '… '
610}
611
612/**
613 * @param {LookupMetrics} metrics
614 * @param {string} [gap]
615 */
616function hitText({ used, missed, at1, at3, at10 }, gap = ' · ') {
617 const judged = used + missed
618 return ['hit@1 ' + at1, 'hit@3 ' + at3, 'hit@10 ' + at10]
619 .map((part) => part + '/' + judged)
620 .join(gap)
621}
622
623/**
624 * `tokens ~6.2k in · ~88k saved est. │ lookups cortex 4 · grep 117 · 3% │ hit@1 2/4 · …`:
625 * what the cortex results cost, what the lookups saved, how much of the searching cortex
626 * could answer went to it, and how often the agent opened what the lookups ranked first.
627 * @param {Stats} stats
628 * @param {Lookup[]} lookups
629 * @param {LookupCounts} counts
630 * @returns {Row}
631 */
632function metricsSpans(stats, lookups, counts) {
633 const metrics = lookupMetrics(lookups)
634 const { cortex, addressable, share } = lookupShare(counts)
635 /** @type {Row} */
636 const row = []
637 if (stats.tokens > 0 || lookups.length > 0) {
638 row.push({ text: 'tokens ', dim: true }, { text: '~' + formatTokens(stats.tokens) + ' in' })
639 }
640 if (metrics.measured > 0) {
641 row.push(
642 { text: ' · ' },
643 { text: '~' + formatTokens(metrics.saved) + ' saved', color: OK },
644 { text: ' est.', dim: true },
645 )
646 }
647 if (share !== null) {
648 if (row.length > 0) row.push({ text: ' │ ', dim: true })
649 row.push(
650 { text: 'lookups ', dim: true },
651 { text: 'cortex ' + cortex + ' · grep ' + addressable + ' · ' },
652 { text: formatShare(share), bold: true },
653 )
654 if (counts.fallback > 0) {
655 row.push({ text: ' · ' + counts.fallback + ' fallback', color: WAITING })
656 }
657 }
658 if (metrics.used + metrics.missed > 0) {
659 if (row.length > 0) row.push({ text: ' │ ', dim: true })
660 row.push({ text: hitText(metrics), truncate: true })
661 }
662 return row
663}
664
665/**
666 * The band above the prompt, as rows of spans: the stacked bar with its totals, a legend
667 * of the categories in use, the token and hit measures, and the /cs checklist. With fewer
668 * rows than that it keeps the bar, then the checklist, then the measures. Draws nothing in
669 * a project without cortex state until a cortex tool is called, and only a hint in one
670 * that has it but has not run /cs yet.
671 * @param {Calls & { markers: string[] | null, columns?: number, maxRows?: number }} input
672 * @returns {Row[]}
673 */
674export function bandModel({
675 stats,
676 recent,
677 inFlight,
678 markers,
679 lookups = [],
680 counts = emptyLookupCounts(),
681 columns,
682 maxRows,
683}) {
684 /** @type {Span} */
685 const title = { text: '◆ cortex ', color: TITLE_COLOR, bold: true }
686 const progress = stepsFrom(stats.okNames, markers)
687 const started = progress.steps[0]?.state === 'done'
688
689 if (!started && stats.total === 0 && inFlight.length === 0) {
690 if (markers == null) return []
691 return [[title, { text: 'no cortex session yet — run /cs', dim: true }]]
692 }
693
694 /** @type {Row} */
695 const tail = [{ text: ' ' + stats.total + (stats.total === 1 ? ' call' : ' calls') }]
696 if (stats.errors > 0) tail.push({ text: ' · ' + stats.errors + ' err', color: FAILED })
697 tail.push(...lastCallSpans(recent, inFlight))
698
699 const room = (columns ?? 80) - textLength([title]) - textLength(tail)
700 const width = Math.max(8, Math.min(40, room))
701 const segments = barSegments(stats.byCategory, width)
702 /** @type {Row} */
703 const bar =
704 segments.length > 0
705 ? segments.map((s) => ({ text: '█'.repeat(s.width), color: s.color }))
706 : [{ text: '░'.repeat(width), dim: true }]
707
708 const rows = [[title, ...bar, ...tail]]
709
710 const fits = (/** @type {Row} */ row) => columns === undefined || textLength(row) <= columns
711 const wideLegend = legendSpans(stats.byCategory)
712 const legend = fits(wideLegend) ? wideLegend : legendSpans(stats.byCategory, ' ')
713
714 /** @param {(items: Step[]) => Row} spans */
715 const checklistOf = (spans) => {
716 /** @type {Row} */
717 const row = [{ text: '/cs ', dim: true }, ...spans(progress.steps)]
718 if (progress.gates) row.push({ text: '│ ', dim: true }, ...spans(progress.gates))
719 if (progress.gateOff) row.push({ text: '⚠ gates off', color: WAITING })
720 return row
721 }
722 const checklist =
723 [checklistOf(stepSpans), checklistOf((items) => stepSpans(items, ' '))].find(fits) ??
724 checklistOf(compactSteps)
725
726 const metrics = metricsSpans(stats, lookups, counts)
727 const limit = maxRows ?? 3
728 const showMetrics = metrics.length > 0 && limit >= 3
729 if (legend.length > 0 && limit >= (showMetrics ? 4 : 3)) rows.push(legend)
730 if (showMetrics) rows.push(metrics)
731 if (limit >= 2) rows.push(checklist)
732 return rows
733}
734
735/**
736 * What a recorded call says about its result, as separate parts: for a lookup, the files
737 * behind it and whether one was opened; for a search or a check, how its result read.
738 * @param {Call} call
739 * @param {Lookup | undefined} lookup
740 * @returns {Span[]}
741 */
742function detailParts(call, lookup) {
743 /** @type {Span[]} */
744 const parts = []
745 if (lookup) {
746 const count = lookup.hits.length
747 const behind = tokensBehind(lookup)
748 const size = behind !== null && count > 0 ? ' ~' + formatTokens(behind) : ''
749 parts.push({ text: count + (count === 1 ? ' file' : ' files') + size, dim: true })
750 const state = lookupState(lookup)
751 if (state === 'used') parts.push({ text: 'used #' + lookup.used, color: OK })
752 if (state === 'missed') parts.push({ text: 'missed', color: WAITING })
753 }
754 if (call.quality) {
755 /** @type {Span} */
756 const tag = { text: call.quality.tag }
757 if (!call.quality.ok) tag.color = WAITING
758 parts.push(tag)
759 }
760 return parts
761}
762
763/**
764 * Parts with a dim separator before each one.
765 * @param {Span[]} parts
766 * @param {string} separator
767 * @returns {Row}
768 */
769function joined(parts, separator) {
770 return parts.flatMap((part) => [{ text: separator, dim: true }, part])
771}
772
773/**
774 * The line under a cortex tool's row in the transcript: its category in its color, then
775 * how the call went, with its time, its tokens and how its result did when the mod
776 * recorded it. The row's own flags decide the state, so a call made before the mod
777 * loaded still gets its tag.
778 * @param {ToolRow} row
779 * @returns {Row}
780 */
781export function rowTag({ name, isRunning, isErrored, isInterrupted, call, lookup }) {
782 const category = categoryOf(name)
783 /** @type {Row} */
784 const tag = [{ text: '■ ' + category, color: colorOf(category) }]
785 if (isRunning) return [...tag, { text: ' · ', dim: true }, { text: '⟳', color: WAITING }]
786 if (isInterrupted) return [...tag, { text: ' · interrupted', dim: true }]
787 const failed = isErrored || (call !== undefined && !call.ok)
788 tag.push(
789 { text: call ? ' · ' + formatMs(call.ms) + ' ' : ' ', dim: true },
790 failed ? { text: '✗', color: FAILED } : { text: '✓', color: OK },
791 )
792 if (!call) return tag
793 /** @type {Span[]} */
794 const parts =
795 call.tokens > 0 ? [{ text: '~' + formatTokens(call.tokens) + ' tok', dim: true }] : []
796 return [...tag, ...joined([...parts, ...detailParts(call, lookup)], ' · ')]
797}
798
799/**
800 * The line under a folded group of tool calls that holds cortex calls: how many of each.
801 * @param {string[]} names the short names of the group's cortex calls
802 * @returns {Row}
803 */
804export function groupTag(names) {
805 /** @type {Record<string, number>} */
806 const counts = {}
807 for (const name of names) {
808 const category = categoryOf(name)
809 counts[category] = (counts[category] ?? 0) + 1
810 }
811 return legendSpans(counts)
812}
813
814/** @param {number} at */
815function clock(at) {
816 return new Date(at).toTimeString().slice(0, 8)
817}
818
819/**
820 * The quality column of the per-tool table: hit@k for a lookup tool, the share of good
821 * results and the last one for a tool whose output says how it went.
822 * @param {string} name
823 * @param {ToolStats} tool
824 * @param {LookupMetrics} metrics the tool's own lookups
825 */
826function qualityText(name, tool, metrics) {
827 if (LOOKUP_TOOLS.includes(name)) {
828 if (metrics.used + metrics.missed > 0) return hitText(metrics)
829 return metrics.count > 0 ? 'no result opened yet' : ''
830 }
831 if (tool.judged === 0) return ''
832 return tool.good + '/' + tool.judged + ' ' + tool.kind + ' · last ' + tool.last
833}
834
835/** Cells taken by the name column, wide enough for `knowledge_search`. */
836const NAME_WIDTH = 18
837/** Columns of the per-tool table after the name, right-aligned. */
838const TABLE = [
839 { title: 'calls', width: 6 },
840 { title: 'ok', width: 5 },
841 { title: 'avg', width: 8 },
842 { title: '~tok', width: 8 },
843 { title: 'saved', width: 8 },
844]
845/** What a narrow pane leaves out of the table first, so the quality column keeps room. */
846const TABLE_DROPS = ['avg', '~tok', 'ok']
847/** Cells the quality column keeps before the table drops a column: `hit@1 2/4 · hit@3 3/4`. */
848const QUALITY_WIDTH = 24
849/** Cells taken by the result column of a call row: `10 files ~31k · used #2`. */
850const DETAIL_WIDTH = 26
851/** Below this a call row leaves out its tokens and the result takes the rest of it. */
852const WIDE_CALLS = 86
853
854/**
855 * A section title with a dim rule to the edge.
856 * @param {string} title
857 * @param {number} columns
858 * @param {string} [note]
859 * @returns {Row}
860 */
861function section(title, columns, note = '') {
862 const used = title.length + (note ? note.length + 1 : 0) + 1
863 /** @type {Row} */
864 const row = [{ text: title, bold: true, color: TITLE_COLOR }]
865 if (note) row.push({ text: ' ' + note, dim: true })
866 row.push({ text: ' ' + '─'.repeat(Math.max(0, columns - used)), dim: true })
867 return row
868}
869
870/**
871 * One row per tool used, in the bar's category order, busiest first within one.
872 * @param {Stats} stats
873 * @param {Lookup[]} lookups
874 * @param {number} columns
875 * @returns {Row[]}
876 */
877function toolTable(stats, lookups, columns) {
878 const order = (/** @type {string} */ name) =>
879 CATEGORIES.findIndex((c) => c.id === categoryOf(name))
880 const names = Object.keys(stats.byTool).sort(
881 (a, b) => order(a) - order(b) || (stats.byTool[b]?.calls ?? 0) - (stats.byTool[a]?.calls ?? 0),
882 )
883 if (names.length === 0) return []
884 const tableWidth = (/** @type {typeof TABLE} */ shown) =>
885 2 + NAME_WIDTH + shown.reduce((sum, column) => sum + column.width, 0) + 2 + QUALITY_WIDTH
886 let shown = TABLE
887 for (const title of TABLE_DROPS) {
888 if (tableWidth(shown) > columns) shown = shown.filter((column) => column.title !== title)
889 }
890 const heading =
891 ' ' +
892 'tool'.padEnd(NAME_WIDTH) +
893 shown.map((column) => column.title.padStart(column.width)).join('') +
894 ' quality'
895 /** @type {Row[]} */
896 const rows = [section('Per tool', columns), [{ text: heading, dim: true, truncate: true }]]
897 for (const name of names) {
898 const tool = stats.byTool[name]
899 if (!tool) continue
900 const metrics = lookupMetrics(lookups.filter((lookup) => lookup.name === name))
901 const saved = metrics.measured > 0 ? '~' + formatTokens(metrics.saved) : '·'
902 /** @type {Record<string, Span>} */
903 const cells = {
904 calls: { text: String(tool.calls) },
905 ok:
906 tool.errors > 0
907 ? { text: String(tool.calls - tool.errors), color: FAILED }
908 : { text: String(tool.calls) },
909 avg: { text: formatMs(tool.ms / tool.calls), dim: true },
910 '~tok': { text: '~' + formatTokens(tool.tokens) },
911 saved: metrics.saved > 0 ? { text: saved, color: OK } : { text: saved, dim: true },
912 }
913 rows.push([
914 { text: '■ ', color: colorOf(categoryOf(name)) },
915 { text: cell(name, NAME_WIDTH) },
916 ...shown.map((column) => {
917 const span = cells[column.title] ?? { text: '' }
918 return { ...span, text: span.text.padStart(column.width) }
919 }),
920 { text: ' ' + qualityText(name, tool, metrics), truncate: true },
921 ])
922 }
923 return rows
924}
925
926/**
927 * The native searches by kind, under the cortex lookups they compete with: which kinds a
928 * cortex lookup could have answered and which are rg's or find's job. A kind is read off
929 * the command alone, so the section says it is an estimate.
930 * @param {LookupCounts} counts
931 * @param {number} columns
932 * @returns {Row[]}
933 */
934function lookupTable(counts, columns) {
935 const { share } = lookupShare(counts)
936 if (share === null && Object.keys(counts.native).length === 0) return []
937 const note = share === null ? 'estimate' : 'estimate · cortex ' + formatShare(share) + ' of what it could answer'
938 /**
939 * @param {string} label
940 * @param {number} count
941 * @param {Span} hint
942 * @returns {Row}
943 */
944 const line = (label, count, hint) => [
945 { text: ' ' + cell(label, NAME_WIDTH) },
946 { text: String(count).padStart(TABLE[0]?.width ?? 6) },
947 { ...hint, text: ' ' + hint.text, truncate: true },
948 ]
949 /** @type {Row[]} */
950 const rows = [section('Lookups', columns, note)]
951 rows.push(line('cortex', counts.cortex, { text: LOOKUP_TOOLS.join(', '), dim: true }))
952 for (const kind of LOOKUP_KINDS) {
953 const count = counts.native[kind.id] ?? 0
954 if (count === 0) continue
955 const hint = kind.addressable ? { text: kind.answer, color: WAITING } : { text: kind.answer, dim: true }
956 rows.push(line(kind.label, count, hint))
957 }
958 if (counts.fallback > 0) {
959 const hint = { text: 'grep within 3 calls of a cortex lookup', color: WAITING }
960 rows.push(line('fallback', counts.fallback, hint))
961 }
962 return rows
963}
964
965/**
966 * Spans padded with spaces to `width` cells, so the column after them lines up.
967 * @param {Span[]} spans
968 * @param {number} width
969 * @returns {Row}
970 */
971function padded(spans, width) {
972 const room = width - textLength(spans)
973 return room > 0 ? [...spans, { text: ' '.repeat(room) }] : spans
974}
975
976/**
977 * The /cortex-calls pane: the totals and measures, a row per tool, the searches by kind,
978 * then the calls: running ones first, then the recent ones, newest first. Every column
979 * has a fixed width and only the last one in a row is cut to fit.
980 * @param {Calls & { limit?: number, columns?: number }} input
981 * @returns {Row[]}
982 */
983export function paneModel({
984 stats,
985 recent,
986 inFlight,
987 lookups = [],
988 counts = emptyLookupCounts(),
989 limit = 40,
990 columns = 80,
991}) {
992 /** @type {Row} */
993 const header = [
994 { text: '◆ ', color: TITLE_COLOR, bold: true },
995 { text: stats.total + ' cortex calls', bold: true },
996 ]
997 if (stats.errors > 0) header.push({ text: ' · ' + stats.errors + ' failed', color: FAILED })
998 const rows = [header]
999
1000 const searches = lookupTable(counts, columns)
1001 if (stats.total === 0 && inFlight.length === 0) {
1002 rows.push([{ text: 'Nothing yet. Run /cs to start a cortex session.', dim: true }])
1003 if (searches.length > 0) rows.push([{ text: ' ' }], ...searches)
1004 return rows
1005 }
1006
1007 const metrics = metricsSpans(stats, lookups, counts)
1008 if (metrics.length > 0) rows.push(metrics)
1009 const table = toolTable(stats, lookups, columns)
1010 if (table.length > 0) rows.push([{ text: ' ' }], ...table)
1011 if (searches.length > 0) rows.push([{ text: ' ' }], ...searches)
1012 rows.push([{ text: ' ' }], section('Calls', columns, 'newest first'))
1013
1014 const byId = new Map(lookups.map((lookup) => [lookup.toolUseId, lookup]))
1015 for (const call of [...inFlight].reverse()) {
1016 rows.push([
1017 { text: 'running ', dim: true },
1018 { text: ' ⟳ ', color: WAITING },
1019 { text: '■ ', color: colorOf(categoryOf(call.name)) },
1020 { text: cell(call.name, NAME_WIDTH) },
1021 { text: ' ' + call.args, dim: true, truncate: true },
1022 ])
1023 }
1024 const wide = columns >= WIDE_CALLS
1025 for (const call of [...recent].reverse().slice(0, limit)) {
1026 const lookup = byId.get(call.toolUseId)
1027 const parts = detailParts(call, lookup)
1028 const detail = joined(parts, ' · ').slice(1)
1029 /** @type {Row} */
1030 const row = [
1031 { text: clock(call.at), dim: true },
1032 call.ok ? { text: ' ✓ ', color: OK } : { text: ' ✗ ', color: FAILED },
1033 { text: '■ ', color: colorOf(call.category) },
1034 { text: cell(call.name, NAME_WIDTH) },
1035 { text: formatMs(call.ms).padStart(7), dim: true },
1036 ]
1037 /** @type {Span} */
1038 const last = call.error
1039 ? { text: ' ' + call.error, color: FAILED, truncate: true }
1040 : { text: ' ' + call.args, dim: true, truncate: true }
1041 if (wide) {
1042 row.push(
1043 { text: ('~' + formatTokens(call.tokens)).padStart(8), dim: true },
1044 { text: ' ' },
1045 ...padded(detail, DETAIL_WIDTH),
1046 last,
1047 )
1048 } else if (parts.length > 0 && call.ok) {
1049 // The result says more than the arguments. Where it does not fit, the file count
1050 // goes before the verdict does; what still does not fit is cut by fitRow.
1051 const room = columns - textLength(row) - 2
1052 const short = textLength(detail) > room && lookup ? parts.slice(1) : parts
1053 row.push({ text: ' ' }, ...joined(short, ' · ').slice(1))
1054 } else {
1055 row.push(last)
1056 }
1057 rows.push(fitRow(row, columns))
1058 }
1059 return rows
1060}
1061
1062/**
1063 * A span as Text props, leaving out every prop it does not set.
1064 * @param {Span} span
1065 * @returns {import('claude-code').TextProps & { children: string }}
1066 */
1067export function textProps(span) {
1068 /** @type {import('claude-code').TextProps & { children: string }} */
1069 const props = { children: span.text }
1070 if (span.color) props.color = span.color
1071 if (span.bold) props.bold = true
1072 if (span.dim) props.dimColor = true
1073 if (span.truncate) props.wrap = 'truncate-end'
1074 return props
1075}
1076hooks/lookups.js 420 lines1// Which native searches a cortex lookup could have answered. Pure, like model.js: the mod
2// counts them as they run, scripts/lookup-audit.mjs over past transcripts. Every kind is a
3// guess from the command alone, so the numbers it feeds are estimates.
4
5/**
6 * @typedef {'symbol' | 'word' | 'literal' | 'in-file' | 'find-file' | 'non-code'} LookupKind
7 * @typedef {{ argv: string[], piped: boolean }} ShellCommand
8 * @typedef {{ cortex: number, native: Record<string, number>, fallback: number, since: Record<string, number> }} LookupCounts
9 * @typedef {{ cortex: number, addressable: number, share: number | null }} LookupShare
10 */
11
12/**
13 * The kinds, in the order the pane lists them. `addressable`: a cortex lookup answers it
14 * (code_context a symbol, code_search a word or a regex); the rest are rg's or find's job.
15 * @type {{ id: LookupKind, label: string, addressable: boolean, answer: string }[]}
16 */
17export const LOOKUP_KINDS = [
18 { id: 'symbol', label: 'symbol', addressable: true, answer: 'code_context could answer' },
19 { id: 'word', label: 'word or regex', addressable: true, answer: 'code_search could answer' },
20 { id: 'literal', label: 'literal', addressable: false, answer: 'rg is right' },
21 { id: 'in-file', label: 'in known files', addressable: false, answer: 'rg is right' },
22 { id: 'find-file', label: 'file by name', addressable: false, answer: 'find or Glob is right' },
23 { id: 'non-code', label: 'not repo code', addressable: false, answer: 'logs, tmp, other dirs' },
24]
25
26/** A grep this many tool calls after a cortex lookup, in the same loop, is a fallback. */
27export const FALLBACK_WINDOW = 3
28
29const SEARCH_TOOLS = ['rg', 'grep', 'egrep', 'fgrep', 'ag', 'ack']
30const FIND_TOOLS = ['find', 'fd', 'fdfind', 'locate']
31/** Words before the command itself: `if rg …`, `env X=1 rg …`, `time rg …`. */
32const PREFIXES = ['if', 'then', 'else', 'elif', 'do', 'while', 'until', '!', '{']
33const WRAPPERS = ['command', 'builtin', 'exec', 'env', 'time', 'nice', 'noglob', 'sudo']
34/** Search options that take the next word as their value. */
35const TAKES_ARG = [
36 '-e',
37 '-f',
38 '-g',
39 '-t',
40 '-T',
41 '-m',
42 '-A',
43 '-B',
44 '-C',
45 '-d',
46 '-D',
47 '-j',
48 '-M',
49 '--regexp',
50 '--file',
51 '--glob',
52 '--iglob',
53 '--type',
54 '--type-not',
55 '--max-count',
56 '--max-depth',
57 '--max-columns',
58 '--threads',
59 '--sort',
60 '--sortr',
61 '--include',
62 '--exclude',
63 '--exclude-dir',
64 '--context',
65 '--after-context',
66 '--before-context',
67]
68/** Not code in this repo: temp and system dirs, transcripts, logs, dependencies, stdin. */
69const NON_CODE =
70 /^-$|^\/tmp\/|^\/private\/|^\/var\/|scratchpad|\.claude\/projects|node_modules|\.(log|jsonl|csv|output)$/
71const IDENTIFIER = /^[A-Za-z_$][A-Za-z0-9_$]*$/
72/** A file, not a dir: a name with an extension after at least one other character. */
73const FILE_NAME = /.\.[A-Za-z0-9]+$/
74
75/**
76 * The simple commands in a shell line, each with whether a pipe feeds it. Quotes and
77 * backslashes are read the way the shell reads them, redirections and their targets are
78 * dropped, and heredoc bodies are skipped. An unterminated quote gives nothing.
79 * @param {string} command
80 * @returns {ShellCommand[]}
81 */
82export function shellCommands(command) {
83 /** @type {ShellCommand[]} */
84 const out = []
85 /** @type {string[]} */
86 let argv = []
87 let piped = false
88 /** @type {string | null} */
89 let word = null
90 let dropNext = false
91 /** @type {boolean | null} the next word is a heredoc delimiter; true for `<<-` */
92 let delimiterNext = null
93 /** @type {{ delimiter: string, tabs: boolean }[]} */
94 let heredocs = []
95
96 const flushWord = () => {
97 if (word === null) return
98 if (delimiterNext !== null) heredocs.push({ delimiter: word, tabs: delimiterNext })
99 else if (!dropNext) argv.push(word)
100 delimiterNext = null
101 dropNext = false
102 word = null
103 }
104 /** @param {string} separator */
105 const endCommand = (separator) => {
106 flushWord()
107 if (argv.length > 0) out.push({ argv, piped })
108 argv = []
109 piped = separator === '|' || separator === '|&'
110 }
111
112 const s = command
113 let i = 0
114 while (i < s.length) {
115 const c = s[i] ?? ''
116 const next = s[i + 1] ?? ''
117 if (c === "'") {
118 const close = s.indexOf("'", i + 1)
119 if (close === -1) return []
120 word = (word ?? '') + s.slice(i + 1, close)
121 i = close + 1
122 } else if (c === '"') {
123 let j = i + 1
124 let text = ''
125 while (j < s.length && s[j] !== '"') {
126 const after = s[j + 1] ?? ''
127 if (s[j] === '\\' && '"\\$`\n'.includes(after) && after !== '') {
128 if (after !== '\n') text += after
129 j += 2
130 } else {
131 text += s[j]
132 j += 1
133 }
134 }
135 if (j >= s.length) return []
136 word = (word ?? '') + text
137 i = j + 1
138 } else if (c === '\\') {
139 if (next !== '\n' && next !== '') word = (word ?? '') + next
140 i += 2
141 } else if (c === ' ' || c === '\t') {
142 flushWord()
143 i += 1
144 } else if (c === '#' && word === null) {
145 while (i < s.length && s[i] !== '\n') i += 1
146 } else if (c === '\n') {
147 endCommand('\n')
148 i += 1
149 for (const { delimiter, tabs } of heredocs) {
150 for (;;) {
151 if (i >= s.length) return out
152 const end = s.indexOf('\n', i)
153 const line = s.slice(i, end === -1 ? s.length : end)
154 i = end === -1 ? s.length : end + 1
155 if ((tabs ? line.replace(/^\t+/, '') : line) === delimiter) break
156 }
157 }
158 heredocs = []
159 } else if ((c === '<' || c === '>') && next === '(') {
160 endCommand('(')
161 i += 2
162 } else if (c === '$' && next === '(') {
163 endCommand('(')
164 i += 2
165 } else if (c === '<' || c === '>' || (c === '&' && next === '>')) {
166 // `2>` names a file descriptor, not an argument; `x>` ends the word x.
167 if (word !== null && /^\d+$/.test(word)) word = null
168 flushWord()
169 if (c === '&') i += 1
170 const op = /^(<<<|<<-|<<|>>|>\||<>|<&|>&|<|>)/.exec(s.slice(i))?.[0] ?? c
171 i += op.length
172 if (op === '<<' || op === '<<-') {
173 delimiterNext = op === '<<-'
174 } else if (op === '<&' || op === '>&') {
175 const fd = /^[0-9-]+/.exec(s.slice(i))?.[0]
176 if (fd) i += fd.length
177 else dropNext = true
178 } else {
179 dropNext = true
180 }
181 } else if ('|&;()'.includes(c)) {
182 const op = ['||', '|&', '&&', ';;'].find((two) => s.startsWith(two, i)) ?? c
183 endCommand(op)
184 i += op.length
185 } else {
186 word = (word ?? '') + c
187 i += 1
188 }
189 }
190 endCommand(';')
191 return out
192}
193
194/**
195 * The command without the words before it: keywords, wrappers and `VAR=value`.
196 * @param {string[]} argv
197 */
198function withoutPrefix(argv) {
199 let i = 0
200 for (;;) {
201 const arg = argv[i]
202 if (arg === undefined) return []
203 if (PREFIXES.includes(arg) || /^[A-Za-z_][A-Za-z0-9_]*=/.test(arg)) {
204 i += 1
205 } else if (WRAPPERS.includes(arg)) {
206 i += 1
207 while (argv[i]?.startsWith('-')) i += 1
208 } else {
209 return argv.slice(i)
210 }
211 }
212}
213
214/**
215 * A search's pattern and the paths it searches. Several `-e` are one alternation.
216 * @param {string[]} args the words after the command
217 */
218function patternAndTargets(args) {
219 /** @type {string[]} */
220 const patterns = []
221 /** @type {string[]} */
222 const positional = []
223 let options = true
224 for (let i = 0; i < args.length; i += 1) {
225 const arg = args[i] ?? ''
226 if (options && arg === '--') {
227 options = false
228 } else if (options && TAKES_ARG.includes(arg)) {
229 if (arg === '-e' || arg === '--regexp') patterns.push(args[i + 1] ?? '')
230 i += 1
231 } else if (options && arg.startsWith('--regexp=')) {
232 patterns.push(arg.slice('--regexp='.length))
233 } else if (!(options && arg.startsWith('-') && arg !== '-')) {
234 positional.push(arg)
235 }
236 }
237 if (patterns.length > 0) return { pattern: patterns.join('|'), targets: positional }
238 return { pattern: positional[0] ?? '', targets: positional.slice(1) }
239}
240
241/**
242 * @param {string} path
243 * @param {string} root
244 */
245function outsideRepo(path, root) {
246 if (NON_CODE.test(path) || path === '..' || path.startsWith('../')) return true
247 if (!path.startsWith('/') || root === '') return false
248 return path !== root && !path.startsWith(root + '/')
249}
250
251/** @param {string} path */
252function isFile(path) {
253 if (/[*?[{$]/.test(path)) return false
254 return FILE_NAME.test(path.slice(path.lastIndexOf('/') + 1))
255}
256
257/**
258 * What a pattern looks for. A symbol: every alternative an identifier and one shaped like
259 * code (camelCase, snake_case, PascalCase). A literal: an UPPER_SNAKE name, or text with a
260 * space, a quote, `:`, `=` or `/`. Anything else is a word or a regex.
261 * @param {string} pattern
262 * @returns {LookupKind}
263 */
264export function patternKind(pattern) {
265 if (pattern === '') return 'literal'
266 const bare = pattern.replace(/\\[b<>]/g, '').replace(/[()]/g, '')
267 const alternatives = bare.split(/\\\||\|/).filter((part) => part !== '')
268 /** @param {string} name */
269 const shaped = (name) =>
270 /[a-z][A-Z]|[a-z]_[a-z]|^[A-Z][a-z]+[A-Z]/.test(name) || /^[A-Z].*[a-z]/.test(name)
271 if (
272 alternatives.length > 0 &&
273 alternatives.every((part) => IDENTIFIER.test(part)) &&
274 alternatives.some(shaped)
275 ) {
276 return 'symbol'
277 }
278 if (/[A-Z][A-Z0-9]*_[A-Z0-9_]+/.test(pattern) || /[\s"':=/]/.test(pattern)) return 'literal'
279 return 'word'
280}
281
282/**
283 * @param {string} pattern
284 * @param {string[]} targets
285 * @param {string} root
286 * @returns {LookupKind}
287 */
288function contentKind(pattern, targets, root) {
289 if (targets.length > 0 && targets.every((target) => outsideRepo(target, root))) {
290 return 'non-code'
291 }
292 if (targets.length > 0 && targets.every(isFile)) return 'in-file'
293 return patternKind(pattern)
294}
295
296/**
297 * @param {string[]} argv a command without its prefix
298 * @param {string} root
299 * @returns {LookupKind | null}
300 */
301function commandKind(argv, root) {
302 const [path = '', ...rest] = argv
303 let name = path.slice(path.lastIndexOf('/') + 1)
304 let args = rest
305 if (name === 'git') {
306 let i = 0
307 while (args[i]?.startsWith('-')) i += args[i] === '-C' || args[i] === '-c' ? 2 : 1
308 if (args[i] === 'ls-files') return 'find-file'
309 if (args[i] !== 'grep') return null
310 name = 'grep'
311 args = args.slice(i + 1)
312 }
313 if (FIND_TOOLS.includes(name)) return 'find-file'
314 if (!SEARCH_TOOLS.includes(name)) return null
315 if (args.includes('--files')) return 'find-file'
316 const { pattern, targets } = patternAndTargets(args)
317 return contentKind(pattern, targets, root)
318}
319
320/**
321 * The first search a shell line runs itself. One fed by a pipe filters another command's
322 * output, so it is not a lookup.
323 * @param {string} command
324 * @param {string} [root] the project root; a path outside it is not repo code
325 * @returns {LookupKind | null}
326 */
327export function bashLookupKind(command, root = '') {
328 for (const { argv, piped } of shellCommands(command)) {
329 if (piped) continue
330 const kind = commandKind(withoutPrefix(argv), root)
331 if (kind !== null) return kind
332 }
333 return null
334}
335
336/**
337 * @param {Record<string, unknown>} input the tool's arguments
338 * @param {string} [root]
339 * @returns {LookupKind}
340 */
341export function grepLookupKind(input, root = '') {
342 const pattern = typeof input.pattern === 'string' ? input.pattern : ''
343 const path = typeof input.path === 'string' && input.path !== '' ? [input.path] : []
344 return contentKind(pattern, path, root)
345}
346
347/**
348 * What a tool call looked for, or null for one that is not a native lookup.
349 * @param {string} tool
350 * @param {Record<string, unknown>} input the tool's arguments
351 * @param {string} [root]
352 * @returns {LookupKind | null}
353 */
354export function lookupKindOf(tool, input, root = '') {
355 if (tool === 'Bash') {
356 return typeof input.command === 'string' ? bashLookupKind(input.command, root) : null
357 }
358 if (tool === 'Grep') return grepLookupKind(input, root)
359 if (tool === 'Glob') return 'find-file'
360 return null
361}
362
363/** @returns {LookupCounts} */
364export function emptyLookupCounts() {
365 return { cortex: 0, native: {}, fallback: 0, since: {} }
366}
367
368/** @param {string | null} kind */
369function addressable(kind) {
370 return LOOKUP_KINDS.some((k) => k.id === kind && k.addressable)
371}
372
373/**
374 * The counts after one more tool call. `cortex` for a cortex code lookup, `kind` for a
375 * native one; any other call only moves the fallback window of its loop. Returns the same
376 * object when nothing changed.
377 * @param {LookupCounts} counts
378 * @param {{ agent?: string, cortex?: boolean, kind?: LookupKind | null }} call
379 * @returns {LookupCounts}
380 */
381export function countTool(counts, { agent = '', cortex = false, kind = null }) {
382 if (cortex) {
383 return { ...counts, cortex: counts.cortex + 1, since: { ...counts.since, [agent]: 0 } }
384 }
385 const before = counts.since[agent]
386 if (kind === null && before === undefined) return counts
387 const step = before === undefined ? undefined : before + 1
388 const since = { ...counts.since }
389 if (step === undefined || step >= FALLBACK_WINDOW) delete since[agent]
390 else since[agent] = step
391 const fallback = step !== undefined && step <= FALLBACK_WINDOW && addressable(kind)
392 return {
393 cortex: counts.cortex,
394 native: kind === null ? counts.native : { ...counts.native, [kind]: (counts.native[kind] ?? 0) + 1 },
395 fallback: counts.fallback + (fallback ? 1 : 0),
396 since,
397 }
398}
399
400/**
401 * Cortex lookups against the greps a cortex lookup could have answered. `share` is null
402 * until there is either.
403 * @param {LookupCounts} counts
404 * @returns {LookupShare}
405 */
406export function lookupShare(counts) {
407 const could = LOOKUP_KINDS.filter((kind) => kind.addressable).reduce(
408 (sum, kind) => sum + (counts.native[kind.id] ?? 0),
409 0,
410 )
411 const all = counts.cortex + could
412 return { cortex: counts.cortex, addressable: could, share: all === 0 ? null : counts.cortex / all }
413}
414
415/** @param {number} share a fraction */
416export function formatShare(share) {
417 const percent = share * 100
418 return (percent > 0 && percent < 1 ? '<1' : String(Math.round(percent))) + '%'
419}
420