Build custom HTML dashboards from real data using the Graphit CLI. KB-aware queries, entity wrapping, cached data sources.

The AI-Native Analytics Platform, in your terminal and your AI coding assistant.<br/> Connect your AI agents to business facts and rules, and turn their work into trusted insights, live dashboards and reports.
@graphit/cli exposes the Graphit platform as commands your AI coding assistant - Claude Code, Codex or Cursor - or you can drive directly: explore the governed semantic layer (the "knowledge base"), run governed queries against cached data sources, and build custom HTML/SVG/CSS dashboards on a bespoke canvas.
It installs as a plugin/skill, so your assistant knows how to reach for Graphit on any question about your business data - even when you never say "Graphit."
1. Install the CLI - the graphit binary, needed either way (requires Node.js 18+):
npm install -g @graphit/cli
graphit auth login
2. Connect it to your AI coding assistant by installing the Graphit plugin.
Plugin marketplace - Claude Code:
/plugin marketplace add omry-graphit/graphit-plugin
/plugin install graphit@graphit-plugin
Plugin marketplace - Codex:
codex plugin marketplace add omry-graphit/graphit-plugin
Cursor - install the Graphit plugin into Cursor's local plugins, then reload Cursor (Developer: Reload Window):
npx -y @graphit/cli setup --editor cursor
Cursor also loads Graphit's Claude Code plugin. If that plugin is on for all projects, setup says so and installs nothing. If it is on for one project only, setup still installs and warns that Graphit loads twice in that project. Update later with npx -y @graphit/cli setup --editor cursor --update.
In Cursor (2.6+), query results draw as an interactive card in the chat. The plugin registers a local MCP server, graphit-view (hooks/query-view-app/server.mjs), that Cursor starts with Node. It makes no network calls of its own: it reads the results the query hook saved under ~/.graphit/query-view/ (pruned after 48 hours) and, for the lineage and KB tabs, runs the same graphit commands you would (through npx -y @graphit/cli@<plugin version> when graphit is not on your PATH).
VS Code - graphit setup --editor vscode --project writes the skill into the repo's AGENTS.md.
Each path installs the Graphit skills so the assistant can drive the CLI on your behalf.
Start a new session after installing the plugin. Claude Code (and Codex) load plugin skills and commands at session start, so the Graphit skill,
/graphit, and thegraphitcommands are not available in the session you installed from. Open a new session first - otherwise the assistant will not have the skill loaded and will improvise instead of following the guided workflow.
graphit auth login # Open the browser login flow
graphit auth status # Show the current account and org
graphit auth logout # Clear stored credentials
The CLI talks to https://api.graphit-app.com by default. Set GRAPHIT_API_URL to point at a different backend.
TLS connections are verified against Node's bundled CA certificates, which already cover the public Graphit API. If you are behind a corporate TLS-inspecting proxy whose root certificate lives only in your operating system's trust store, set GRAPHIT_USE_SYSTEM_CA=1 to also trust the system store. It is off by default because reading the system store is unnecessary for normal use and can crash under sandboxed agent runtimes (e.g. an editor's command sandbox on macOS, where keychain access is blocked).
| Group | What it does |
|---|---|
graphit auth | Log in, check status, log out |
graphit kb | Knowledge base: list, get, search, explore, and full CRUD for metrics, dimensions, rules, synonyms, domains, relationships, topics, tables, and templates |
graphit query | Run a governed SQL query against your data |
graphit ds | Data sources: list, create, refresh, verify, update cached sources |
graphit dashboard | Custom dashboards: list, create, get, update HTML or a single entity, export to PNG/PDF, delete |
graphit connector | Connections: list, add, and test. Removal is admin-only in the Sources Hub; the CLI verb explains the handoff but does not delete. |
graphit governance | Query governance: inspect and set the enforcement mode |
graphit setup | Install the Graphit plugin for Cursor, or remove legacy copied skill files |
Run any command with --help for its exact flags and subcommands:
graphit kb create metric --help
graphit dashboard export --help
Global --output <json|table|styled> controls how results print (defaults to json, the machine-readable form agents rely on).
{{metric:NAME}}, {{dim:NAME}}), and the enforcement mode (observe / warn / strict) is set per org. Ad-hoc measures on a governed source require explicit approval and can be hard-blocked under strict mode.Full docs, the complete CLI reference, and the dashboard build workflow live at graphit-app.com.
UNLICENSED. Copyright Graphit.
hooks/query-view/register.tsx 526 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import { DETAILS_PANE, KB_PANE, LINEAGE_PANE, RESULTS_PANE, SQL_PANE, capped } from './atoms'
5import { buildModel, drawTooLarge } from './card'
6import type { CardActions } from './card'
7import { drawDesktopCard } from './card-desktop'
8import { drawTerminalCard } from './card-terminal'
9import { drawDetailsPane } from './details-pane'
10import { READ_LIMIT, openedFor, parsedFor, rememberOpened, rememberParsed, rememberSaved, savedFor, savedFromPreview, withReadSlot } from './loaders'
11import type { Loaded } from './loaders'
12import { drawExplorer, drawKbPane, drawSqlPane } from './panes'
13import { columnsOf, drawResultsPane, nextTop, resultsWidth, viewRows, windowRows } from './results-pane'
14import type { ResultsActions } from './results-pane'
15import { clean, isGraphitQuery, parseMetricDef, parseQueryResult, queryReachesStdout } from './result'
16import type { QueryResult } from './result'
17import type { Expansion } from './sql'
18import type { CommandByCall, DetailsTab, DetailsView, Explore, KbDef, KbSelection, ResultsView, SqlPane, TabByCall, Upstream } from './state'
19import { assembleUpstream, errorOf, jsonOf } from './upstream'
20
21// Feature #1062: the selected tab of each result, keyed by tool_use_id (by the
22// group's requestId in a carousel); the KB reference the sidebar shows; the
23// definitions it fetched; each Bash call's command.
24const tabs = atom({ plugin: 'graphit', key: 'queryViewTab' } as const, {} as TabByCall)
25const selected = atom({ plugin: 'graphit', key: 'queryViewSelected' } as const, null as KbSelection | null)
26const defs = atom({ plugin: 'graphit', key: 'queryViewDefs' } as const, {} as Record<string, KbDef>)
27const commands = atom({ plugin: 'graphit', key: 'queryViewCommands' } as const, {} as CommandByCall)
28// Feature #1067: the query a folded group's carousel shows (by requestId); the
29// row and column page of each result; the upstream read for each query; the
30// lineage explorer's and full-SQL pane's content.
31const slides = atom({ plugin: 'graphit', key: 'queryViewSlide' } as const, {} as Record<string, number>)
32const pages = atom({ plugin: 'graphit', key: 'queryViewPage' } as const, {} as Record<string, number>)
33const upstreams = atom({ plugin: 'graphit', key: 'queryViewUpstream' } as const, {} as Record<string, Upstream>)
34const explore = atom({ plugin: 'graphit', key: 'queryViewExplore' } as const, null as Explore | null)
35const sqlPane = atom({ plugin: 'graphit', key: 'queryViewSqlPane' } as const, null as SqlPane | null)
36const resultsView = atom({ plugin: 'graphit', key: 'queryViewResults' } as const, null as ResultsView | null)
37// The desktop card's one sidebar: which query, which tab, its SQL, KB and rules.
38const details = atom({ plugin: 'graphit', key: 'queryViewDetails' } as const, null as DetailsView | null)
39
40// Results, SQL and Lineage are as wide as the Full results table wants; KB reads best narrower.
41const DETAILS_COLUMNS = 100
42
43// The results table's actions: a search or a sort starts the window back at
44// the first row; a header press sorts low to high, then high to low, then off.
45function resultsActions(set: (fn: (v: ResultsView) => ResultsView) => unknown, copy: (text: string) => unknown): ResultsActions {
46 return {
47 search: query => set(v => ({ ...v, query, top: 0 })),
48 setTop: top => set(v => ({ ...v, top })),
49 sortBy: column =>
50 set(v =>
51 v.sort !== column
52 ? { ...v, sort: column, desc: false, top: 0 }
53 : v.desc
54 ? { ...v, sort: '', desc: false, top: 0 }
55 : { ...v, desc: true, top: 0 },
56 ),
57 copy,
58 }
59}
60
61// A pane body's height in rows, as the surface laid it out.
62// eslint-disable-next-line @typescript-eslint/no-explicit-any
63function paneRows(e: any): number | undefined {
64 const rows = (e.props as { scroll?: { bodyRows?: unknown } } | undefined)?.scroll?.bodyRows
65 return typeof rows === 'number' && rows > 0 ? rows : undefined
66}
67
68// A pane's body width in cells: what the surface laid it out at, else what it measured.
69// eslint-disable-next-line @typescript-eslint/no-explicit-any
70function paneColumns(e: any): number | undefined {
71 const body = (e.props as { bodyColumns?: unknown } | undefined)?.bodyColumns
72 if (typeof body === 'number' && body > 0) return body
73 const measured = (e.viewport as { columns?: unknown } | undefined)?.columns
74 return typeof measured === 'number' && measured > 0 ? measured : undefined
75}
76
77// Feature #1077: tell scripts/show-query-result.mjs that this view draws the
78// session's query results, so it says "already displayed" instead of asking the
79// agent to repeat the table (plugin-status/query-view-marker.mjs reads it). The
80// hook's context cannot be rewritten from here: in the desktop app the classic
81// chain carried none of it (Feature #1067). Stamped before every query, keyed by
82// the current id - `/clear` and a resume continue under a new id without a
83// reload, and SessionStart prunes markers older than 48h. A failed stamp only
84// costs the old directive, so it never blocks the query.
85// eslint-disable-next-line @typescript-eslint/no-explicit-any
86async function stampDrawsMarker($: any): Promise<void> {
87 try {
88 const id = String(await $.session.id())
89 if (!/^[A-Za-z0-9._-]{1,128}$/.test(id)) return
90 // An empty variable counts as unset, as in plugin-status/query-view-marker.mjs.
91 const home = await $.env.get('HOME')
92 const data = (await $.env.get('GRAPHIT_PLUGIN_DATA')) || (home ? `${home}/.graphit` : null)
93 if (data) await $.fs.write(`${data}/sessions/${id}.query-view`, '{}')
94 } catch {
95 // An engine without these calls, or an unwritable directory.
96 }
97}
98
99// The command as shown on a card: from the graphit invocation on, so a long
100// path or a `cd ... &&` prefix does not hide the SQL.
101function commandLine(command: string): string {
102 const at = command.search(/(?:graphit|index\.js)\s+query\b/)
103 const shown = at > 0 ? command.slice(at) : command
104 return clean(shown).replace(/\s+/g, ' ').slice(0, 160)
105}
106
107// The chalk G's inner markup, read once per load from the plugin bundle.
108let logoInner: string | null = null
109
110// Feature #1067: the call's result - its output when that parses, else the
111// file Claude Code saved it to (read once, at draw time, never on tool.call).
112// eslint-disable-next-line @typescript-eslint/no-explicit-any
113async function loadResult($: any, id: string | undefined, output: unknown): Promise<Loaded> {
114 const direct = parseQueryResult(output)
115 if (direct) return { result: direct }
116 const file = savedFor(id) ?? savedFromPreview(output)
117 if (!file) return null
118 if (file.size > READ_LIMIT) return { tooLarge: file.size }
119 if (parsedFor(file.path) === undefined) {
120 // A read that fails (past `$.fs.read`'s limit when the engine gave no size)
121 // is reported as too large rather than leaving the plain row.
122 let text: string
123 try {
124 text = await $.fs.read(file.path)
125 } catch {
126 return { tooLarge: file.size }
127 }
128 rememberParsed(file.path, parseQueryResult(text))
129 }
130 const result = parsedFor(file.path)
131 return result ? { result } : null
132}
133
134// Feature #1067: `$.process.run` resolves argv[0] on the app's own PATH, and
135// Claude Code puts the plugin's bin/ on the PATH of Bash calls only - so a bare
136// `graphit` never starts for a plugin-only install. Run the plugin's own
137// wrapper; a global install on PATH is the fallback (and covers Windows, where
138// the bash wrapper cannot start without a shell).
139// eslint-disable-next-line @typescript-eslint/no-explicit-any
140async function runGraphit($: any, args: string[], timeoutMs: number): Promise<{ exitCode?: number; stdout?: string; stderr?: string }> {
141 try {
142 return await $.process.run([`${$.plugin.root}/bin/graphit`, ...args], { timeoutMs })
143 } catch {
144 return await $.process.run(['graphit', ...args], { timeoutMs })
145 }
146}
147
148// Feature #1067: one query's upstream lineage, read through plain `graphit`
149// with the caller's own permissions - the source (its warehouse SQL and last
150// refresh), the semantic models, each referenced metric - at most
151// a shared cap of reads at a time (withReadSlot), cached per query.
152// eslint-disable-next-line @typescript-eslint/no-explicit-any
153async function loadUpstream($: any, key: string, sourceName: string | undefined, refs: Array<{ kind: string; name: string }>): Promise<void> {
154 if ((await read($, upstreams))[key]?.status === 'loading') return
155 await update($, upstreams, m => capped(m, key, { status: 'loading' } as Upstream))
156 let reason = ''
157 const run = async (args: string[]): Promise<unknown> => {
158 try {
159 const ran = await withReadSlot(() => runGraphit($, args, 30000))
160 const answer = jsonOf(String(ran.stdout ?? ''))
161 // The CLI prints its failure as `{"error": ...}` on stderr, after any warning.
162 if (!answer && !reason) reason = errorOf(String(ran.stderr ?? ''))
163 return answer
164 } catch {
165 return null
166 }
167 }
168 let up: Upstream
169 try {
170 const metricRefs = refs.filter(r => r.kind === 'Metric')
171 const [dsList, models, ...metrics] = await Promise.all([
172 run(['ds', 'list', '--limit', '200']),
173 run(['kb', 'list', 'semantic-model']),
174 ...metricRefs.map(r => run(['kb', 'get', 'metric', '--', r.name])),
175 ])
176 const ds = ((dsList as { data_sources?: Array<{ id?: string; name?: string }> } | null)?.data_sources ?? []).find(
177 d => !!sourceName && (d.name ?? '').toLowerCase() === sourceName.toLowerCase(),
178 )
179 const history = ds?.id ? await run(['ds', 'refresh-history', '--', ds.id]) : null
180 up = assembleUpstream({ sourceName, dsList, history, models, metrics, refs })
181 // Feature #1067: a source the signed-in org does not have is said plainly,
182 // never reported as a warehouse-to-result read.
183 if (dsList && sourceName && !ds) up.notFound = sourceName
184 up.loadedAt = new Date().toLocaleTimeString('en-GB', { timeZone: 'Asia/Jerusalem', hour: '2-digit', minute: '2-digit' })
185 if (!dsList && !models) {
186 up.status = 'error'
187 up.error = reason ? `the graphit CLI said: ${reason}` : 'the graphit CLI did not answer'
188 }
189 } catch {
190 // A malformed answer must never leave the lineage stuck on loading.
191 up = { status: 'error', error: 'the graphit CLI answered in an unexpected shape' }
192 }
193 await update($, upstreams, m => capped(m, key, up))
194}
195
196// Feature #1062: open the KB sidebar on a reference and read its definition.
197// eslint-disable-next-line @typescript-eslint/no-explicit-any
198async function openKb($: any, x: Expansion): Promise<void> {
199 await update($, selected, () => ({ kind: x.kind, name: x.name, alias: x.alias, expansion: x.expr }))
200 await $.ui.open({ id: KB_PANE, title: 'Knowledge Base', closeOnEscape: true, focus: true })
201 await loadDef($, x.kind, x.name)
202}
203
204// One KB asset's definition, read once through the CLI and kept by
205// `${kind}:${name}`. Only metrics have a definition read; the rest are marked so.
206// eslint-disable-next-line @typescript-eslint/no-explicit-any
207async function loadDef($: any, kind: string, name: string): Promise<void> {
208 const k = `${kind}:${name}`
209 if (kind !== 'Metric') {
210 await update($, defs, d => capped(d, k, { status: 'unsupported' }))
211 return
212 }
213 const status = (await read($, defs))[k]?.status
214 if (status === 'ok' || status === 'loading') return
215 await update($, defs, d => capped(d, k, { status: 'loading' }))
216 try {
217 const ran = await withReadSlot(() => runGraphit($, ['kb', 'get', 'metric', '--', name], 20000))
218 const def = parseMetricDef(ran.stdout || ran.stderr)
219 await update($, defs, d => capped(d, k, def))
220 } catch {
221 await update($, defs, d => capped(d, k, { status: 'error', error: 'Could not run graphit kb get.' }))
222 }
223}
224
225// One query's card: its state read here, drawn by the surface's renderer.
226// eslint-disable-next-line @typescript-eslint/no-explicit-any
227async function drawLoaded($: any, e: any, loaded: Loaded, id: string, command: string, header: string | null, nav: unknown = null, rowKey: string = id): Promise<unknown> {
228 const ui = $.ui.resolve(e)
229 if (loaded && 'tooLarge' in loaded) return drawTooLarge(ui, loaded.tooLarge)
230 const result = (loaded as { result: QueryResult }).result
231 if (logoInner === null) {
232 const logo: string = await $.fs.read(`${$.plugin.root}/hooks/query-view/graphit-logo.svg`).catch(() => '')
233 logoInner = logo.replace(/^[\s\S]*?<svg[^>]*>/, '').replace(/<\/svg>\s*$/, '').replace(/<title>[\s\S]*?<\/title>/, '')
234 }
235 const paged = await read($, pages)
236 const colKey = `${rowKey}:cols`
237 let model: ReturnType<typeof buildModel> | null = null
238 const act: CardActions = {
239 setTab: tab => update($, tabs, m => capped(m, id, tab)),
240 goTo: n => update($, pages, m => capped(m, rowKey, Math.min(Math.max(n, 0), (model?.pageCount ?? 1) - 1))),
241 goCols: (n, count) => update($, pages, m => capped(m, colKey, Math.min(Math.max(n, 0), count - 1))),
242 openKb: x => openKb($, x),
243 loadUpstream: () => loadUpstream($, rowKey, model?.sourceName, model?.lineageRefs ?? []),
244 openExplorer: async (title, layers) => {
245 await update($, explore, () => ({ title, layers: layers.layers, edges: layers.edges, trail: [] }))
246 await $.ui.open({ id: LINEAGE_PANE, title: 'Lineage', closeOnEscape: true, focus: true })
247 },
248 openSql: async (title, sql) => {
249 await update($, sqlPane, () => ({ title, sql }))
250 await $.ui.open({ id: SQL_PANE, title, closeOnEscape: true, focus: true })
251 },
252 openResults: async () => {
253 rememberOpened(rowKey, result)
254 const title = `Results · ${model?.sourceName ?? 'query'}`
255 await update($, resultsView, () => ({ id: rowKey, title, query: '', sort: '', desc: false, top: 0 }))
256 // Wide enough for every column; a width the person dragged to still wins.
257 await $.ui.open({ id: RESULTS_PANE, title, closeOnEscape: true, focus: true, columns: resultsWidth(result) })
258 },
259 openDetails: async input => {
260 // Every tab's content is set up here, so a tab switch in the sidebar
261 // needs no second read.
262 rememberOpened(rowKey, result)
263 const source = model?.sourceName ?? 'query'
264 const sql = { base: clean(model?.baseSql ?? '') || undefined, runtime: clean(model?.runSql ?? '') || undefined, kind: input.sqlKind }
265 const shownSql = (input.sqlKind === 'base' ? sql.base : sql.runtime) ?? sql.base ?? sql.runtime ?? ''
266 await update($, resultsView, () => ({ id: rowKey, title: `Results · ${source}`, query: '', sort: '', desc: false, top: 0 }))
267 if (model) await update($, explore, () => ({ title: `${source} lineage`, layers: model!.layers.layers, edges: model!.layers.edges, trail: [] }))
268 await update($, sqlPane, () => ({ title: input.sqlKind === 'base' ? 'SQL as written' : 'SQL as run', sql: shownSql }))
269 await update($, details, () => ({ rowKey, title: `Query details · ${source}`, tab: input.tab, sql, kb: input.kb, rules: input.rules, open: [] }))
270 await $.ui.open({
271 id: DETAILS_PANE,
272 title: `Query details · ${source}`,
273 closeOnEscape: true,
274 focus: true,
275 columns: Math.max(DETAILS_COLUMNS, resultsWidth(result)),
276 })
277 // Each KB row shows its description, so read every definition now; each
278 // lands on its own and redraws its row.
279 await Promise.all(input.kb.map(x => loadDef($, x.kind, x.name)))
280 },
281 copy: text => $.ui.copy({ text, surface: e.surface }),
282 }
283 model = buildModel({
284 id,
285 rowKey,
286 command,
287 result,
288 header,
289 nav,
290 state: {
291 tab: (await read($, tabs))[id],
292 page: paged[rowKey],
293 colPage: paged[colKey],
294 upstream: (await read($, upstreams))[rowKey],
295 logoInner,
296 },
297 act,
298 })
299 return e.surface === 'desktop' && ui.Svg ? drawDesktopCard(ui, model) : drawTerminalCard(ui, model)
300}
301
302export const register: Register = on => {
303 // The terminal's result row carries no command, so record each graphit query
304 // here for the render gate below. Feature #1067: a large result is moved to
305 // a file and drawn with an empty output; the engine names that file in
306 // `persistedOutputPath`, kept in module memory - nothing is read or parsed
307 // here, so a query is never slower for the view (Feature #1077's marker is
308 // one small write).
309 on('tool.call', { tool: 'Bash' }, async ($, e, proceed) => {
310 const command = (e as { command?: unknown }).command
311 if (typeof command !== 'string' || !e.tool_use_id || !isGraphitQuery(command)) return proceed(e)
312 const id = e.tool_use_id
313 await stampDrawsMarker($)
314 await update($, commands, m => capped(m, id, command))
315 const out = await proceed(e)
316 if (queryReachesStdout(command)) rememberSaved(id, (out as { result?: unknown } | null)?.result)
317 return out
318 })
319
320 // The terminal draws a standalone Bash result as its own ToolResult; the
321 // desktop draws command and output as one ToolUse card. Hook both.
322 for (const component of ['ToolResult', 'ToolUse'] as const) {
323 on('ui.render', { component }, async ($, e, proceed) => {
324 if (e.props.tool !== 'Bash' || e.props.isErrored) return proceed(e)
325 // The desktop raises ToolResult for a standalone call too, beside its
326 // ToolUse card: drawing both put the same card in the transcript twice.
327 if (component === 'ToolResult' && e.surface === 'desktop') return proceed(e)
328 if ('isRunning' in e.props && e.props.isRunning) return proceed(e)
329 const command =
330 'input' in e.props ? (e.props.input as { command?: unknown } | null)?.command : (await read($, commands))[e.props.tool_use_id]
331 if (typeof command !== 'string' || !isGraphitQuery(command) || !queryReachesStdout(command)) {
332 return proceed(e)
333 }
334 const loaded = await loadResult($, e.props.tool_use_id, e.props.output)
335 if (!loaded) return proceed(e)
336 return drawLoaded($, e, loaded, e.props.tool_use_id, command, 'input' in e.props ? commandLine(command) : null)
337 })
338 }
339
340 // Feature #1067: the desktop folds a run of calls into one "Ran N commands"
341 // row. Keep that row as the app draws it and show the query card under it;
342 // several queries in one fold share a carousel. Unfolded, each row draws its
343 // own card.
344 on('ui.render', { component: 'ToolGroup' }, async ($, e, proceed) => {
345 if (e.props.isExpanded) return proceed(e)
346 const known = await read($, commands)
347 const groupKey = String(e.requestId)
348 const queries: Array<{ id: string; command: string; loaded: NonNullable<Loaded> }> = []
349 for (const [i, c] of e.props.calls.entries()) {
350 if (c.tool !== 'Bash' || c.isRunning || c.isErrored) continue
351 const input = (c.input as { command?: unknown } | null)?.command
352 const command = typeof input === 'string' ? input : c.tool_use_id ? known[c.tool_use_id] : undefined
353 if (typeof command !== 'string' || !isGraphitQuery(command) || !queryReachesStdout(command)) continue
354 const loaded = await loadResult($, c.tool_use_id, c.output)
355 if (loaded) queries.push({ id: c.tool_use_id ?? `${groupKey}:${i}`, command, loaded })
356 }
357 if (queries.length === 0) return proceed(e)
358 const engine = await proceed(e)
359 const stored = (await read($, slides))[groupKey]
360 const pos = Math.min(Math.max(stored ?? queries.length - 1, 0), queries.length - 1)
361 const q = queries[pos]
362 const { Box, Text, Button } = $.ui.resolve(e)
363 const nav =
364 queries.length > 1 ? (
365 <Box alignItems="center" gap={1} flexShrink={0}>
366 <Button
367 key={`slide-prev-${groupKey}`}
368 label="❮"
369 variant="secondary"
370 dimColor={pos === 0}
371 onPress={() => update($, slides, m => capped(m, groupKey, Math.max(pos - 1, 0)))}
372 />
373 <Button
374 key={`slide-next-${groupKey}`}
375 label="❯"
376 variant="secondary"
377 dimColor={pos === queries.length - 1}
378 onPress={() => update($, slides, m => capped(m, groupKey, Math.min(pos + 1, queries.length - 1)))}
379 />
380 <Text wrap="truncate">{`Query ${pos + 1} of ${queries.length}`}</Text>
381 </Box>
382 ) : null
383 // In a carousel the selected tab belongs to the group, so paging keeps it.
384 const card = await drawLoaded($, e, q.loaded, queries.length > 1 ? groupKey : q.id, q.command, commandLine(q.command), nav, q.id)
385 return (
386 <Box flexDirection="column">
387 {engine}
388 {card}
389 </Box>
390 )
391 })
392
393 // The desktop card's one sidebar. Its tabs draw the same panes the terminal
394 // card still opens one by one, from the same state.
395 on('ui.render', { component: 'Pane', requestId: DETAILS_PANE }, async ($, e) => {
396 try {
397 const d = await read($, details)
398 const ui = $.ui.resolve(e)
399 const copy = (text: string) => $.ui.copy({ text, surface: e.surface })
400 // A press redraws the pane and takes the pressed Button with it; hand
401 // the focus back so the next press is not spent taking it.
402 const refocus = () => (d ? $.ui.open({ id: DETAILS_PANE, title: d.title, closeOnEscape: true, focus: true }) : undefined)
403 const setDetails = async (fn: (v: DetailsView) => DetailsView) => {
404 await update($, details, v => (v ? fn(v) : v))
405 await refocus()
406 }
407 let body: unknown = null
408 if (d?.tab === 'results') {
409 const view = await read($, resultsView)
410 const set = (fn: (v: ResultsView) => ResultsView) => update($, resultsView, v => (v ? fn(v) : v))
411 body = drawResultsPane(ui, openedFor(view?.id), view, resultsActions(set, copy), paneRows(e), paneColumns(e))
412 } else if (d?.tab === 'sql') {
413 body = drawSqlPane(ui, await read($, sqlPane), copy)
414 } else if (d?.tab === 'lineage') {
415 body = drawExplorer(ui, await read($, explore), {
416 go: async to => {
417 await update($, explore, x => (x ? { ...x, selected: to, trail: [...x.trail, x.selected ?? ''].slice(-30) } : x))
418 await refocus()
419 },
420 back: async () => {
421 await update($, explore, x => (x && x.trail.length ? { ...x, selected: x.trail[x.trail.length - 1] || undefined, trail: x.trail.slice(0, -1) } : x))
422 await refocus()
423 },
424 all: async () => {
425 await update($, explore, x => (x ? { ...x, selected: undefined, trail: [...x.trail, x.selected ?? ''].slice(-30) } : x))
426 await refocus()
427 },
428 // A node's SQL opens in this sidebar's SQL tab.
429 openSql: async (title, sql) => {
430 await update($, sqlPane, () => ({ title, sql }))
431 await setDetails(v => ({ ...v, tab: 'sql' }))
432 },
433 copy,
434 }, paneColumns(e))
435 }
436 return drawDetailsPane(ui, d, body, await read($, defs), {
437 setTab: (tab: DetailsTab) => setDetails(v => ({ ...v, tab })),
438 toggle: (key: string) => setDetails(v => ({ ...v, open: v.open.includes(key) ? v.open.filter(k => k !== key) : [...v.open, key] })),
439 setSqlKind: async kind => {
440 const v = await read($, details)
441 const sql = v ? (kind === 'base' ? v.sql.base : v.sql.runtime) : undefined
442 if (sql) await update($, sqlPane, () => ({ title: kind === 'base' ? 'SQL as written' : 'SQL as run', sql }))
443 await setDetails(x => ({ ...x, sql: { ...x.sql, kind } }))
444 },
445 copy,
446 })
447 } catch (err) {
448 const { Text } = $.ui.resolve(e)
449 return <Text color="red">{`Query details failed: ${String(err instanceof Error ? err.message : err).slice(0, 300)}`}</Text>
450 }
451 })
452
453 on('ui.render', { component: 'Pane', requestId: KB_PANE }, async ($, e) => {
454 const sel = await read($, selected)
455 const def = sel ? (await read($, defs))[`${sel.kind}:${sel.name}`] : undefined
456 return drawKbPane($.ui.resolve(e), sel, def, text => $.ui.copy({ text, surface: e.surface }))
457 })
458 on('ui.render', { component: 'Pane', requestId: SQL_PANE }, async ($, e) =>
459 drawSqlPane($.ui.resolve(e), await read($, sqlPane), text => $.ui.copy({ text, surface: e.surface })),
460 )
461 // Feature #1067: Full results.
462 on('ui.render', { component: 'Pane', requestId: RESULTS_PANE }, async ($, e) => {
463 const view = await read($, resultsView)
464 const set = (fn: (v: ResultsView) => ResultsView) => update($, resultsView, v => (v ? fn(v) : v))
465 return drawResultsPane($.ui.resolve(e), openedFor(view?.id), view, resultsActions(set, text => $.ui.copy({ text, surface: e.surface })), paneRows(e), paneColumns(e))
466 })
467
468 // The results table draws only a window of rows, so the wheel over a pane
469 // showing it moves the window instead of the pane: the drawing stays inside
470 // the host's size bound however many rows the result has. Any other tab,
471 // and a table that fits whole, scrolls as usual. Where a surface does not
472 // raise ui.scroll for a pane's wheel (the desktop, as of this writing), the
473 // table's own ▲ ▼ buttons move the window instead.
474 for (const pane of [DETAILS_PANE, RESULTS_PANE]) {
475 on('ui.scroll', { requestId: pane }, async ($, e, next) => {
476 if (pane === DETAILS_PANE && (await read($, details))?.tab !== 'results') return next(e)
477 const view = await read($, resultsView)
478 const result = openedFor(view?.id)
479 if (!view || !result) return next(e)
480 const cols = columnsOf(result)
481 const total = viewRows(result.rows, cols, new Set((result.hidden_columns ?? []).map(String)), view).length
482 const win = windowRows(e.bodyRows, cols.length)
483 if (total <= win) return next(e)
484 const top = nextTop(view.top, e.by, total, win)
485 if (top !== view.top) {
486 await update($, resultsView, v => (v ? { ...v, top } : v))
487 // The engine leaves an unmoved window undrawn; ask for the redraw.
488 $.ui.invalidate('ui.render')
489 }
490 return {}
491 })
492 }
493 // Feature #1067: the lineage explorer. The trail keeps '' for the layer list,
494 // so Back returns to it too. A pane that throws draws nothing; say why.
495 on('ui.render', { component: 'Pane', requestId: LINEAGE_PANE }, async ($, e) => {
496 try {
497 // A press redraws the pane and the pressed Button goes with it, which
498 // left the pane without the focus: the next press only took it back.
499 // Each move hands the focus back to the pane.
500 const refocus = () => $.ui.open({ id: LINEAGE_PANE, title: 'Lineage', closeOnEscape: true, focus: true })
501 return drawExplorer($.ui.resolve(e), await read($, explore), {
502 go: async to => {
503 await update($, explore, x => (x ? { ...x, selected: to, trail: [...x.trail, x.selected ?? ''].slice(-30) } : x))
504 await refocus()
505 },
506 back: async () => {
507 await update($, explore, x => (x && x.trail.length ? { ...x, selected: x.trail[x.trail.length - 1] || undefined, trail: x.trail.slice(0, -1) } : x))
508 await refocus()
509 },
510 all: async () => {
511 await update($, explore, x => (x ? { ...x, selected: undefined, trail: [...x.trail, x.selected ?? ''].slice(-30) } : x))
512 await refocus()
513 },
514 openSql: async (title, sql) => {
515 await update($, sqlPane, () => ({ title, sql }))
516 await $.ui.open({ id: SQL_PANE, title, closeOnEscape: true, focus: true })
517 },
518 copy: text => $.ui.copy({ text, surface: e.surface }),
519 }, paneColumns(e))
520 } catch (err) {
521 const { Text } = $.ui.resolve(e)
522 return <Text color="red">{`The lineage explorer failed: ${String(err instanceof Error ? err.message : err).slice(0, 300)}`}</Text>
523 }
524 })
525}
526hooks/query-view/atoms.ts 21 lines1// The query view's pane ids and the cap on its state maps: every map keyed per
2// call or per group is capped, so a long session never grows it without bound.
3// The atoms themselves live in register.tsx - the state library reads only an
4// atom declared in the file that reads it.
5
6export const KB_PANE = 'graphit-kb'
7export const LINEAGE_PANE = 'graphit-lineage'
8export const SQL_PANE = 'graphit-sql'
9export const RESULTS_PANE = 'graphit-results'
10// The desktop card's one sidebar, with Results, SQL, Lineage and KB tabs.
11export const DETAILS_PANE = 'graphit-details'
12
13// Entries kept per map; the oldest drop past this.
14const MAX_ENTRIES = 200
15
16// `{ ...map, [key]: value }`, keeping only the newest MAX_ENTRIES keys.
17export function capped<T>(map: Record<string, T>, key: string, value: T): Record<string, T> {
18 const { [key]: _old, ...rest } = map
19 return Object.fromEntries([...Object.entries(rest), [key, value]].slice(-MAX_ENTRIES))
20}
21hooks/query-view/card.tsx 183 lines1// One query's card. The model below is what both surfaces draw: the desktop as
2// one frosted SVG with native controls laid over it (card-desktop.tsx), the
3// terminal as native rows (card-terminal.tsx). Pure: register.tsx reads the
4// state and supplies the actions (a mod's `$` never crosses an import).
5
6import { MAX_ROWS, OUTCOME_BADGE, REF_KIND, cell, clean, own, sqlFromCommand } from './result'
7import type { QueryResult } from './result'
8import { templateExpansions } from './sql'
9import type { Expansion } from './sql'
10import type { DetailsRule, DetailsTab, KbSelection, TabId, Upstream } from './state'
11import { lineageLayers, warehouseTables } from './upstream'
12import type { Layers } from './upstream'
13import { chartSpec } from './viz'
14import type { ChartSpec } from './viz'
15
16export type CardModel = {
17 // The tab state key (a carousel's group) and the per-query key (pages, upstream).
18 id: string
19 rowKey: string
20 command: string
21 header: string | null
22 nav: unknown
23 result: QueryResult
24 baseSql: string | undefined
25 // "As run": the governed rewrite, else the SQL as written - an ad-hoc query
26 // no rule touched returns no governed_sql, and it ran exactly as written.
27 runSql: string | undefined
28 active: TabId
29 tier: string
30 injections: NonNullable<NonNullable<NonNullable<QueryResult['provenance']>['injection_summary']>['injections']>
31 denied: NonNullable<NonNullable<NonNullable<QueryResult['provenance']>['injection_summary']>['override_denied']>
32 kbRefs: NonNullable<NonNullable<QueryResult['provenance']>['kb_references']>
33 kbCount: number
34 rowCount: number
35 hidden: Set<string>
36 meta: string[]
37 sourceName: string | undefined
38 cols: string[]
39 page: number
40 pageCount: number
41 first: number
42 shown: Array<Record<string, unknown>>
43 expansions: Expansion[]
44 chart: ChartSpec | null
45 upstream: Upstream | undefined
46 lineageRefs: Array<{ kind: string; name: string }>
47 layers: Layers
48 // The stored column page (the desktop clamps it to its own column sets) and
49 // the chalk G's inner markup ('' when the logo could not be read).
50 colPage: number
51 logoInner: string
52 expansionFor: (kind: string, name: string) => Expansion
53 act: CardActions
54}
55
56// What a control on the card does; each runs in register.tsx with `$`.
57export type CardActions = {
58 setTab: (tab: TabId) => Promise<unknown>
59 goTo: (page: number) => Promise<unknown>
60 goCols: (page: number, count: number) => Promise<unknown>
61 openKb: (x: Expansion) => Promise<unknown>
62 loadUpstream: () => Promise<unknown>
63 openExplorer: (title: string, layers: Layers) => Promise<unknown>
64 openSql: (title: string, sql: string) => Promise<unknown>
65 openResults: () => Promise<unknown>
66 // The desktop card's one sidebar: Query details, opened on a tab, carrying
67 // the KB assets and rules the card already has in hand.
68 openDetails: (input: { tab: DetailsTab; sqlKind: 'base' | 'runtime'; kb: KbSelection[]; rules: DetailsRule[] }) => Promise<unknown>
69 copy: (text: string) => unknown
70}
71
72// The state a card reads, by its keys.
73export type CardState = { tab?: TabId; page?: number; colPage?: number; upstream?: Upstream; logoInner: string }
74
75// eslint-disable-next-line @typescript-eslint/no-explicit-any
76export type Ui = Record<string, any>
77
78// The source the result came from: the response's own name unless it is the
79// generic "data_source", else --ds, else the table the SQL as run reads.
80function sourceOf(result: QueryResult, command: string, baseSql: string | undefined): string | undefined {
81 if (result.source && result.source !== 'data_source') return result.source
82 const ds = /--ds(?:=|\s+)(?:"([^"]+)"|'([^']+)'|(\S+))/.exec(command)
83 if (ds) return ds[1] ?? ds[2] ?? ds[3]
84 return warehouseTables(clean(result.governed_sql ?? baseSql ?? ''))[0]
85}
86
87export function buildModel(input: {
88 id: string
89 rowKey: string
90 command: string
91 result: QueryResult
92 header: string | null
93 nav: unknown
94 state: CardState
95 act: CardActions
96}): CardModel {
97 const { id, rowKey, command, result, header, nav, state, act } = input
98 const baseSql = result.sql ?? sqlFromCommand(command)
99 const prov = result.provenance ?? {}
100 const injections = prov.injection_summary?.injections ?? []
101 const kbRefs = prov.kb_references ?? []
102 const rowCount = result.row_count ?? result.rows.length
103 const hidden = new Set((result.hidden_columns ?? []).map(String))
104
105 // The query's own --limit is in its SQL tab; the meta never repeats it.
106 const meta: string[] = [`${rowCount.toLocaleString('en-US')} rows`]
107 if (typeof result.query_ms === 'number') meta.push(`${result.query_ms.toFixed(0)}ms`)
108
109 const cols = (result.columns?.length ? result.columns : Object.keys(result.rows[0] ?? {})).map(String)
110 // Feature #1067: the table pages through every returned row.
111 const pageCount = Math.max(1, Math.ceil(result.rows.length / MAX_ROWS))
112 const page = Math.min(Math.max(state.page ?? 0, 0), pageCount - 1)
113 const first = page * MAX_ROWS
114
115 // What each KB reference compiled to here, paired by select alias against
116 // the returned governed_sql - the masked copy, so the view never shows
117 // definition text the receipt hides.
118 const expansions = baseSql && result.governed_sql ? templateExpansions(clean(baseSql), clean(result.governed_sql)) : []
119 const sourceName = sourceOf(result, command, baseSql)
120 const upstream = state.upstream
121 const lineageRefs = kbRefs.map(ref => ({ kind: own(REF_KIND, ref.kind) ?? 'Metric', name: clean(ref.name ?? '') }))
122
123 return {
124 id,
125 rowKey,
126 command,
127 header,
128 nav,
129 result,
130 baseSql,
131 runSql: result.governed_sql ?? baseSql,
132 active: state.tab ?? 'results',
133 tier: clean(prov.tier ?? 'ad_hoc'),
134 injections,
135 denied: prov.injection_summary?.override_denied ?? [],
136 kbRefs,
137 kbCount: kbRefs.length || prov.kb_refs || 0,
138 rowCount,
139 hidden,
140 meta,
141 sourceName,
142 cols,
143 page,
144 pageCount,
145 first,
146 shown: result.rows.slice(first, first + MAX_ROWS),
147 expansions,
148 chart: chartSpec(cols, result.rows, hidden),
149 upstream,
150 lineageRefs,
151 layers: lineageLayers({
152 up: upstream,
153 sourceName,
154 rowCount,
155 columns: cols,
156 hidden,
157 refs: lineageRefs,
158 expansions,
159 rules: injections.map(inj => ({
160 name: cell(inj.rule_name ?? inj.source_id ?? 'rule'),
161 clauses: (inj.added_clauses ?? []).map(clean),
162 masks: (inj.transformations ?? []).map(t => cell(t.column)).filter(Boolean),
163 color: (own(OUTCOME_BADGE, inj.outcome) ?? { color: '#6b7280' }).color,
164 why: inj.why ? clean(inj.why) : undefined,
165 })),
166 }),
167 colPage: state.colPage ?? 0,
168 logoInner: state.logoInner,
169 expansionFor: (kind, name) => expansions.find(x => x.kind === kind && x.name === name) ?? { kind, name, alias: '', expr: '' },
170 act,
171 }
172}
173
174// A result too large for `$.fs.read`: said plainly instead of a vanished card.
175export function drawTooLarge(ui: Ui, size: number): unknown {
176 const { Box, Text } = ui
177 return (
178 <Box marginTop={1} borderStyle="round" borderDimColor paddingX={1}>
179 <Text dimColor>{`Graphit query result too large to draw${size > 0 ? ` (${(size / 1024 / 1024).toFixed(1)} MB)` : ''} - narrow it with --limit or a WHERE clause.`}</Text>
180 </Box>
181 )
182}
183hooks/query-view/card-desktop.tsx 262 lines1// The card on the desktop: one frosted SVG - header row, tab band, the panel,
2// a status bar - with native Buttons laid over its bands. An SVG draws as an
3// image (no clicks reach the mod), so every control is a Button placed with
4// `position: "absolute"`, in character cells (about 8 x 18 px).
5
6import type { CardModel, Ui } from './card'
7import { MAX_ROWS, OUTCOME_BADGE, REF_KIND, TIER_COLOR, TIER_LABEL, cell, clean, fmtNumber, marksFor, own } from './result'
8import { templateColor } from './spans'
9import { formatLines, lineText } from './sql'
10import type { DetailsTab, TabId } from './state'
11import { BAR_TABS_LEFT, CARD_CELLS, bodyHeightFor, codeLinesFor, columnWidths, fitColumns, renderCardSvg } from './svgcard'
12import type { SvgPanel } from './svgcard'
13
14// Bands the SVG leaves empty for the native tabs and the footer controls,
15// sized so a row laid 4 cells down sits on the tab band's center line.
16const TOOLBAR_PX = 46
17const FOOTER_PX = 56
18export function drawDesktopCard(ui: Ui, m: CardModel): unknown {
19 const { Box, Text, Button, Svg } = ui
20 const { active, result, injections, kbRefs, kbCount, hidden, cols, shown, upstream, layers } = m
21
22 // Right-aligned only when the page holds a number; an all-null (masked) column stays left.
23 const numeric = cols.map(c => !hidden.has(c) && shown.some(r => typeof r[c] === 'number') && shown.every(r => typeof r[c] === 'number' || r[c] === null))
24 // Columns page like rows: the ones that fit the card, then the next set.
25 const cellRows = shown.map(r => cols.map(c => (typeof r[c] === 'number' ? fmtNumber(r[c] as number) : cell(r[c]))))
26 const widths = columnWidths(cols, cellRows, hidden)
27 const colStarts: number[] = []
28 for (let at = 0; at < cols.length; at += fitColumns(widths, at)) colStarts.push(at)
29 const colPage = Math.min(Math.max(m.colPage, 0), Math.max(colStarts.length - 1, 0))
30 const cStart = colStarts[colPage] ?? 0
31 const cEnd = cStart + fitColumns(widths, cStart)
32 const goCols = (n: number) => m.act.goCols(n, colStarts.length)
33
34 const sqlPanel = (kind: 'base' | 'runtime', text: string | undefined): SvgPanel => ({
35 kind: 'code',
36 lines: formatLines(clean(text ?? '')).map(line => {
37 const marks = marksFor(line, kind, injections, m.expansions)
38 const notes = [...new Set(marks.map(mk => mk.note).filter(Boolean))]
39 return { tokens: line, mark: marks[0] ? { glyph: marks[0].marker, color: marks[0].color, note: notes.join(', ') } : undefined }
40 }),
41 maxLines: sqlLines,
42 // The count of lines past the card is said in the footer, beside Open full SQL.
43 moreNote: false,
44 })
45 const panels: Record<TabId, () => SvgPanel> = {
46 results: () => ({
47 kind: 'table',
48 columns: cols.slice(cStart, cEnd),
49 rows: cellRows.map(r => r.slice(cStart, cEnd)),
50 hidden,
51 numeric: numeric.slice(cStart, cEnd),
52 note: hidden.size > 0 ? `⊘ hidden by policy: ${[...hidden].join(', ')}` : undefined,
53 }),
54 chart: () => ({ kind: 'chart', spec: m.chart }),
55 lineage: () => ({ kind: 'layers', spec: layers }),
56 base: () => sqlPanel('base', m.baseSql),
57 runtime: () => sqlPanel('runtime', m.runSql),
58 // The KB tab holds the semantic references and, after them, the rules that
59 // changed the query: one tab, so the top bar keeps room for the meta.
60 kb: () => ({
61 kind: 'list',
62 items: [...kbItems(), ...ruleItems()],
63 }),
64 governance: () => ({ kind: 'list', items: [...kbItems(), ...ruleItems()] }),
65 }
66 function kbItems() {
67 return kbRefs.map(ref => {
68 const kindName = own(REF_KIND, ref.kind) ?? 'Metric'
69 const x = m.expansionFor(kindName, ref.name ?? '')
70 return {
71 title: cell(ref.name),
72 badge: { text: kindName.toUpperCase(), color: templateColor(kindName) },
73 lines: [`{{ ${kindName}('${cell(ref.name)}') }}`, ...(x.expr ? [`${x.expr === x.alias ? 'Column' : 'Compiles to'} ${x.expr}`] : [])],
74 }
75 })
76 }
77 function ruleItems() {
78 return injections.map(inj => {
79 const outcome = own(OUTCOME_BADGE, inj.outcome) ?? { label: clean(inj.outcome ?? 'applied').toUpperCase(), color: '#6b7280' }
80 return {
81 title: cell(inj.rule_name ?? inj.source_id ?? 'rule'),
82 badge: { text: outcome.label, color: outcome.color },
83 lines: [
84 ...(inj.why ? [clean(inj.why)] : []),
85 ...(inj.added_clauses ?? []).map(cl => `+ ${clean(cl)}`),
86 ...(inj.transformations ?? []).filter(t => t.column).map(t => `~ ${cell(t.column)} returned as NULL`),
87 ],
88 }
89 })
90 }
91
92 // Sized by the first page, so paging to a short last page keeps the height.
93 const bodyH = bodyHeightFor(Math.min(result.rows.length, MAX_ROWS), hidden.size > 0)
94 // The card shows this many SQL lines; the sidebar shows them all.
95 const sqlLines = codeLinesFor(bodyH)
96
97 const isSql = active === 'base' || active === 'runtime'
98 const segments: Array<{ id: TabId; label: string; on: boolean; go: TabId }> = [
99 { id: 'results', label: 'Results', on: active === 'results', go: 'results' },
100 { id: 'runtime', label: 'SQL', on: isSql, go: isSql ? active : 'runtime' },
101 { id: 'chart', label: 'Graph', on: active === 'chart', go: 'chart' },
102 { id: 'lineage', label: 'Lineage', on: active === 'lineage', go: 'lineage' },
103 { id: 'kb', label: `KB (${kbCount + injections.length})`, on: active === 'kb' || active === 'governance', go: 'kb' },
104 ]
105 const segment = (key: string, label: string, on: boolean, press: () => unknown) => (
106 // Every tab is an outlined button (the active one filled), so tabs read as
107 // controls and the plain text beside them reads as information.
108 <Button key={key} label={label} variant={on ? 'primary' : 'secondary'} onPress={press} />
109 )
110 const sqlText = clean((active === 'base' ? m.baseSql : m.runSql) ?? '')
111 // Feature #1067: every footer reads from the left - the desktop sizes the
112 // laid-over controls a little wider than the card's own cells, so a row
113 // anchored to the right edge runs past it.
114 const n = (x: number) => x.toLocaleString('en-US')
115 // The lineage status reads in the native footer, after its buttons.
116 const status =
117 active === 'lineage'
118 ? upstream?.status === 'ok'
119 ? upstream.notFound
120 ? `${upstream.notFound} isn't in your Graphit org - showing the query only`
121 : `Warehouse to result, read from Graphit at ${upstream.loadedAt ?? ''}`
122 : upstream?.status === 'loading'
123 ? 'Reading the warehouse, data source and KB definitions…'
124 : upstream?.status === 'error'
125 ? `Upstream not read: ${upstream.error ?? 'unknown error'}`
126 : 'Showing the query only; load the upstream for the full chain'
127 : undefined
128 const card = renderCardSvg({
129 logoInner: m.logoInner,
130 // Governed is the expected case and goes unsaid; Verified and Ad hoc keep their pill.
131 tierLabel: m.tier === 'governed' ? '' : (own(TIER_LABEL, m.tier) ?? clean(m.tier)),
132 tierColor: own(TIER_COLOR, m.tier) ?? TIER_COLOR.ad_hoc,
133 meta: m.meta.join(' · '),
134 source: m.sourceName ? cell(m.sourceName) : undefined,
135 panel: panels[active](),
136 toolbar: TOOLBAR_PX,
137 // Feature #1067: every tab keeps the footer band and the body height, so
138 // switching tabs never changes the card's height.
139 footer: FOOTER_PX,
140 body: bodyH,
141 compactHeader: true,
142 })
143 // The one way into the sidebar: every tab's footer starts with Details, which
144 // opens the Query details sidebar on the matching tab.
145 const detailsTab: DetailsTab = isSql ? 'sql' : active === 'lineage' ? 'lineage' : active === 'kb' || active === 'governance' ? 'kb' : 'results'
146 const details = (
147 <Button
148 key={`details-${m.rowKey}`}
149 label="Details ↗"
150 variant="secondary"
151 onPress={() =>
152 m.act.openDetails({
153 tab: detailsTab,
154 sqlKind: active === 'base' ? 'base' : 'runtime',
155 kb: kbRefs.map(ref => {
156 const kind = own(REF_KIND, ref.kind) ?? 'Metric'
157 const x = m.expansionFor(kind, ref.name ?? '')
158 // The full name: the sidebar reads the definition by it and shortens it itself.
159 return { kind, name: clean(ref.name ?? ''), alias: x.alias, expansion: x.expr }
160 }),
161 rules: ruleItems().map(r => ({ title: r.title, badge: r.badge.text, color: r.badge.color, lines: r.lines })),
162 })
163 }
164 />
165 )
166 const extras = active === 'results' && shown.length > 0 ? (
167 <Box justifyContent="flex-start" alignItems="center" gap={3}>
168 <Box alignItems="center" gap={2}>
169 <Box alignItems="center" gap={1}>
170 {m.pageCount > 2 ? <Button key={`pg-first-${m.rowKey}`} label="«" plain dimColor={m.page === 0} onPress={() => m.act.goTo(0)} /> : null}
171 {m.pageCount > 1 ? <Button key={`pg-prev-${m.rowKey}`} label="❮" variant="secondary" dimColor={m.page === 0} onPress={() => m.act.goTo(m.page - 1)} /> : null}
172 <Text dimColor>{`Rows ${n(m.first + 1)}-${n(m.first + shown.length)} of ${n(result.rows.length)}`}</Text>
173 {m.pageCount > 1 ? <Button key={`pg-next-${m.rowKey}`} label="❯" variant="secondary" dimColor={m.page === m.pageCount - 1} onPress={() => m.act.goTo(m.page + 1)} /> : null}
174 {m.pageCount > 2 ? <Button key={`pg-last-${m.rowKey}`} label="»" plain dimColor={m.page === m.pageCount - 1} onPress={() => m.act.goTo(m.pageCount - 1)} /> : null}
175 </Box>
176 {colStarts.length > 1 ? (
177 <Box alignItems="center" gap={1}>
178 <Button key={`col-prev-${m.rowKey}`} label="❮" variant="secondary" dimColor={colPage === 0} onPress={() => goCols(colPage - 1)} />
179 <Text dimColor>{`Columns ${cStart + 1}-${cEnd} of ${cols.length}`}</Text>
180 <Button key={`col-next-${m.rowKey}`} label="❯" variant="secondary" dimColor={colPage === colStarts.length - 1} onPress={() => goCols(colPage + 1)} />
181 </Box>
182 ) : null}
183 </Box>
184 </Box>
185 ) : active === 'lineage' ? (
186 <Box justifyContent="flex-start" alignItems="center" gap={1}>
187 <Button
188 key={`up-load-${m.rowKey}`}
189 label={upstream?.status === 'ok' ? 'Reload' : upstream?.status === 'loading' ? 'Loading…' : 'Load upstream'}
190 variant="secondary"
191 dimColor={upstream?.status === 'loading'}
192 onPress={() => m.act.loadUpstream()}
193 />
194 {status ? <Text dimColor wrap="truncate-end">{status}</Text> : null}
195 </Box>
196 ) : isSql ? (
197 <Box justifyContent="flex-start" alignItems="center" gap={3}>
198 {/* Which SQL the panel shows, as a highlighted toggle on the left. */}
199 <Box alignItems="center" gap={1}>
200 {(['base', 'runtime'] as const).map(kind => (
201 <Button
202 key={`sql-${kind === 'base' ? 'base' : 'run'}-${m.id}`}
203 label={kind === 'base' ? 'As written' : 'As run'}
204 variant={active === kind ? 'primary' : 'secondary'}
205 onPress={() => m.act.setTab(kind)}
206 />
207 ))}
208 </Box>
209 <Box alignItems="center" gap={1}>
210 {sqlText ? (
211 <Button key={`sql-copy-${m.id}`} label="Copy" plain onPress={() => m.act.copy(formatLines(sqlText).map(lineText).join('\n'))} />
212 ) : null}
213 {card.more > 0 ? <Text dimColor>{`+${card.more} more line${card.more === 1 ? '' : 's'}`}</Text> : null}
214 </Box>
215 </Box>
216 ) : null
217 const footer = (
218 <Box justifyContent="flex-start" alignItems="center" gap={3}>
219 {details}
220 {extras}
221 </Box>
222 )
223
224 return (
225 <Box flexDirection="column" marginTop={1} alignSelf="flex-start">
226 {/* Feature #1067: the lineage tab draws interactive, so a node's <title> shows its full name on hover. */}
227 <Svg key="card" source={card.svg} alt={`Graphit query result: ${m.meta.join(', ')}`} width={card.width} height={card.height} isInteractive={active === 'lineage' || undefined} />
228 {/* The one top bar after the mark: tabs on the left; the tier (unless governed) and meta on the
229 right, native text so they share the tabs' font and baseline. */}
230 {/* Flows left to right, never anchored to the right edge: native cells are
231 wider than the picture's pixels assume, so a right anchor lands past the card. */}
232 {/* A fixed width so the meta truncates inside the card: the desktop draws native cells
233 about 9px against the picture's 8, hence the margin on the right. */}
234 <Box position="absolute" top={1} left={BAR_TABS_LEFT} width={CARD_CELLS - BAR_TABS_LEFT - 8} alignItems="center" gap={1}>
235 <Box alignItems="center" gap={1} flexShrink={0}>
236 {segments.map(t =>
237 segment(`tab-${t.id}`, t.label, t.on, async () => {
238 await m.act.setTab(t.go)
239 if (t.go === 'lineage' && !upstream) await m.act.loadUpstream()
240 }),
241 )}
242 </Box>
243 <Box alignItems="center" gap={1} flexShrink={1} minWidth={0} marginLeft={1}>
244 {/* The divider between the tabs and the meta, mirroring the one after the mark. */}
245 <Text dimColor>│</Text>
246 {m.tier !== 'governed' ? <Text color={own(TIER_COLOR, m.tier) ?? TIER_COLOR.ad_hoc}>{`● ${own(TIER_LABEL, m.tier) ?? clean(m.tier)}`}</Text> : null}
247 {/* Meta and source as one line, so the source name is what truncates at the bar's end. */}
248 <Text dimColor wrap="truncate-end">{[m.meta.join(' · '), m.sourceName ? cell(m.sourceName) : ''].filter(Boolean).join(' · ')}</Text>
249 </Box>
250 </Box>
251 {/* The footer: the tab's controls, then the query switcher (a carousel's), flowing from the
252 left like the top bar so nothing lands past the card's right edge. */}
253 {footer || m.nav ? (
254 <Box position="absolute" bottom={2} left={2} alignItems="center" gap={3}>
255 {m.nav}
256 {footer}
257 </Box>
258 ) : null}
259 </Box>
260 )
261}
262hooks/query-view/card-terminal.tsx 342 lines1// The card on the terminal: native rows - a tier badge, tabs, the selected
2// panel - with clickable KB references that open the KB sidebar.
3
4import type { CardModel, Ui } from './card'
5import { MARK, OUTCOME_BADGE, REF_KIND, TIER_COLOR, cell, clean, fmtNumber, marksFor, own } from './result'
6import { templateColor, tokenSpans } from './spans'
7import { formatLines, lineText, tokenize } from './sql'
8import type { Expansion, Token } from './sql'
9import type { TabId } from './state'
10import { SERIES_COLORS } from './viz'
11
12export function drawTerminalCard(ui: Ui, m: CardModel): unknown {
13 const { Box, Text, Button } = ui
14 const { active, result, injections, denied, kbRefs, kbCount, hidden, cols, shown, chart, layers } = m
15
16 const tabList: Array<{ id: TabId; label: string }> = [
17 { id: 'results', label: `Results (${m.rowCount})` },
18 { id: 'base', label: 'Base query' },
19 { id: 'runtime', label: 'Runtime SQL' },
20 { id: 'chart', label: 'Graph' },
21 { id: 'lineage', label: 'Lineage' },
22 { id: 'kb', label: `KB assets (${kbCount})` },
23 { id: 'governance', label: `Governance (${injections.length})` },
24 ]
25
26 const openKb = (x: Expansion) => m.act.openKb(x)
27
28 const pager = (
29 <Box key={`pager-${m.rowKey}`} gap={1} alignItems="center">
30 {m.pageCount > 1
31 ? [
32 <Button key={`pg-prev-${m.rowKey}`} label="‹ Prev" dimColor={m.page === 0} onPress={() => m.act.goTo(m.page - 1)} />,
33 <Text key={`pg-at-${m.rowKey}`} dimColor>{`Rows ${(m.first + 1).toLocaleString('en-US')}-${(m.first + shown.length).toLocaleString('en-US')} of ${result.rows.length.toLocaleString('en-US')} · page ${m.page + 1} / ${m.pageCount.toLocaleString('en-US')}`}</Text>,
34 <Button key={`pg-next-${m.rowKey}`} label="Next ›" dimColor={m.page === m.pageCount - 1} onPress={() => m.act.goTo(m.page + 1)} />,
35 ]
36 : null}
37 <Button key={`results-full-${m.rowKey}`} label="Full results ›" onPress={() => m.act.openResults()} />
38 </Box>
39 )
40
41 // One Box per column, so the table aligns on a proportional font too.
42 const resultsTab =
43 cols.length === 0 || shown.length === 0 ? (
44 <Text dimColor>Query returned 0 rows.</Text>
45 ) : (
46 <Box flexDirection="column">
47 <Box gap={3}>
48 {cols.map((c, i) => (
49 <Box key={`col${i}`} flexDirection="column">
50 <Text bold color={hidden.has(c) ? 'gray' : undefined}>
51 {hidden.has(c) ? `${cell(c)} ⊘` : cell(c)}
52 </Text>
53 {shown.map((r, ri) => (
54 <Text key={`c${i}-${ri}`} dimColor={hidden.has(c)}>
55 {hidden.has(c) ? '•••' : (typeof r[c] === 'number' ? fmtNumber(r[c] as number) : cell(r[c])) || ' '}
56 </Text>
57 ))}
58 </Box>
59 ))}
60 </Box>
61 {pager}
62 {hidden.size > 0 ? <Text color="gray">⊘ hidden by policy: {[...hidden].map(cell).join(', ')}</Text> : null}
63 </Box>
64 )
65
66 const sqlTab = (kind: 'base' | 'runtime', text: string | undefined, missing: string) => {
67 if (!text) return <Text dimColor>{missing}</Text>
68 const lines = formatLines(clean(text))
69 const formatted = lines.map(lineText).join('\n')
70 const width = String(lines.length).length
71 return (
72 <Box flexDirection="column">
73 <Box justifyContent="space-between">
74 <Box gap={1}>
75 <Text bold>{kind === 'base' ? 'SQL as written' : 'SQL as run'}</Text>
76 <Text dimColor>{`${lines.length} lines`}</Text>
77 {kind === 'runtime' ? (
78 <Text>
79 <Text color={MARK.added.color}>{' + rule added'}</Text>
80 <Text color={MARK.masked.color}>{' ~ rule masked'}</Text>
81 <Text color={MARK.kb.color}>{' ◆ KB expansion'}</Text>
82 </Text>
83 ) : (
84 <Text color={MARK.kb.color}>{' ◆ KB reference - click it for the definition'}</Text>
85 )}
86 </Box>
87 <Button key={`copy-${kind}`} label="Copy" onPress={() => m.act.copy(formatted)} />
88 </Box>
89 {lines.map((line, i) => {
90 const marks = marksFor(line, kind, injections, m.expansions)
91 const lead = marks[0]
92 const notes = [...new Set(marks.map(mk => mk.note).filter(Boolean))]
93 // Split the line at each template so the reference itself is the button.
94 const segments: Array<{ tokens: Token[]; x?: Expansion }> = [{ tokens: [] }]
95 for (const t of line) {
96 segments[segments.length - 1].tokens.push(t)
97 if (t.kind === 'template') {
98 segments[segments.length - 1].x = m.expansionFor(t.templateKind ?? 'Metric', t.templateName ?? '')
99 segments.push({ tokens: [] })
100 }
101 }
102 return (
103 <Box key={`ln-${kind}-${i}`} gap={1}>
104 <Text dimColor>{String(i + 1).padStart(width)}</Text>
105 <Text color={lead?.color} bold>
106 {lead?.marker ?? ' '}
107 </Text>
108 <Box>
109 {segments.map((seg, si) => {
110 const plain = seg.x ? seg.tokens.slice(0, -1) : seg.tokens
111 const tpl = seg.x ? seg.tokens[seg.tokens.length - 1] : undefined
112 return (
113 <Box key={`sg${si}`}>
114 <Text>{tokenSpans(Text, plain, `t${si}-`)}</Text>
115 {seg.x && tpl ? (
116 <Button
117 key={`kb-${kind}-${i}-${si}`}
118 label={`{{ ${cell(tpl.templateKind)}('${cell(tpl.templateName)}') }}`}
119 plain
120 hover={{ color: templateColor(tpl.templateKind) }}
121 onPress={() => openKb(seg.x as Expansion)}
122 />
123 ) : null}
124 </Box>
125 )
126 })}
127 </Box>
128 {notes.length > 0 ? <Text color={lead.color}>{` ← ${notes.join(', ')}`}</Text> : null}
129 </Box>
130 )
131 })}
132 </Box>
133 )
134 }
135
136 const label = (text: string) => (
137 <Box minWidth={12}>
138 <Text dimColor>{text}</Text>
139 </Box>
140 )
141 const badge = (text: string, color: string) => (
142 <Text backgroundColor={color} color="#ffffff" bold>
143 {` ${text} `}
144 </Text>
145 )
146
147 const kbTab =
148 kbRefs.length > 0 ? (
149 <Box flexDirection="column" gap={1}>
150 {kbRefs.map((ref, i) => {
151 const kindName = own(REF_KIND, ref.kind) ?? 'Metric'
152 const color = templateColor(kindName)
153 const x = m.expansionFor(kindName, ref.name ?? '')
154 return (
155 <Box key={`kb${i}`} flexDirection="column">
156 <Box gap={1}>
157 {badge(kindName.toUpperCase(), color)}
158 <Button key={`kb-tab-${i}`} label={cell(ref.name)} plain hover={{ color }} onPress={() => openKb(x)} />
159 {ref.deprecated ? badge('DEPRECATED', '#dc2626') : null}
160 </Box>
161 <Box gap={2}>
162 {label('Reference')}
163 <Text>{tokenSpans(Text, tokenize(`{{ ${kindName}('${cell(ref.name)}') }}`), `kbr${i}-`)}</Text>
164 </Box>
165 {x.expr ? (
166 <Box gap={2}>
167 {label(x.expr === x.alias ? 'Column' : 'Compiles to')}
168 <Text>{tokenSpans(Text, tokenize(x.expr), `kbe${i}-`)}</Text>
169 </Box>
170 ) : null}
171 {x.alias ? (
172 <Box gap={2}>
173 {label('Used as')}
174 <Text bold>{cell(x.alias)}</Text>
175 </Box>
176 ) : null}
177 </Box>
178 )
179 })}
180 </Box>
181 ) : (
182 <Text dimColor>{kbCount > 0 ? `${kbCount} KB assets referenced; this CLI version does not send their names.` : 'No KB assets referenced.'}</Text>
183 )
184
185 const filtersAdded = injections.reduce((n, inj) => n + (inj.added_clauses?.length ?? 0), 0)
186 const columnsMasked = injections.reduce((n, inj) => n + (inj.transformations ?? []).filter(t => t.column).length, 0)
187 const summary = [
188 `${injections.length} rule${injections.length === 1 ? '' : 's'} applied`,
189 filtersAdded ? `${filtersAdded} filter${filtersAdded === 1 ? '' : 's'} added` : '',
190 columnsMasked ? `${columnsMasked} column${columnsMasked === 1 ? '' : 's'} masked` : '',
191 denied.length ? `${denied.length} override${denied.length === 1 ? '' : 's'} denied` : '',
192 ].filter(Boolean)
193
194 const governanceTab =
195 injections.length === 0 && denied.length === 0 ? (
196 <Text dimColor>No governance rules applied.</Text>
197 ) : (
198 <Box flexDirection="column" gap={1}>
199 <Text dimColor>{summary.join(' · ')}</Text>
200 {injections.map((inj, i) => {
201 const name = cell(inj.source === 'deprecated_asset' ? inj.source_id : inj.rule_name ?? inj.source_id ?? 'rule')
202 const outcome = own(OUTCOME_BADGE, inj.outcome) ?? { label: clean(inj.outcome ?? 'applied').toUpperCase(), color: '#6b7280' }
203 return (
204 <Box key={`inj${i}`} flexDirection="column">
205 <Box gap={1}>
206 {badge(outcome.label, outcome.color)}
207 <Text bold>{name}</Text>
208 </Box>
209 {inj.why ? <Text>{clean(inj.why)}</Text> : null}
210 {(inj.added_clauses ?? []).map((cl, j) => (
211 <Box key={`cl${j}`} gap={2}>
212 {label(j === 0 ? 'Adds filter' : '')}
213 <Text>
214 <Text color={MARK.added.color} bold>
215 {'+ '}
216 </Text>
217 {tokenSpans(Text, tokenize(clean(cl)), `cl${i}-${j}-`)}
218 </Text>
219 </Box>
220 ))}
221 {(inj.transformations ?? [])
222 .filter(t => t.column)
223 .map((t, j) => (
224 <Box key={`tr${j}`} gap={2}>
225 {label(j === 0 ? 'Masks column' : '')}
226 <Text>
227 <Text color={MARK.masked.color} bold>
228 {'~ '}
229 </Text>
230 <Text bold>{cell(t.column)}</Text>
231 <Text dimColor>{' returned as NULL'}</Text>
232 </Text>
233 </Box>
234 ))}
235 {inj.reason ? (
236 <Box gap={2}>
237 {label('Note')}
238 <Text dimColor>{clean(inj.reason)}</Text>
239 </Box>
240 ) : null}
241 </Box>
242 )
243 })}
244 {denied.map((d, i) => (
245 <Box key={`den${i}`} flexDirection="column">
246 <Box gap={1}>
247 {badge('OVERRIDE DENIED', '#dc2626')}
248 <Text bold>{cell(d.rule_name ?? 'rule')}</Text>
249 </Box>
250 {d.reason ? <Text>{clean(d.reason)}</Text> : null}
251 </Box>
252 ))}
253 </Box>
254 )
255
256 // Feature #1067: the graph as bars of block characters, one row per value.
257 const peak = chart ? Math.max(1, ...chart.series.flatMap(s => s.values.map(v => Math.abs(v ?? 0)))) : 1
258 const chartTab = !chart ? (
259 <Text dimColor>Nothing to graph: the result needs a category or date column and a number column.</Text>
260 ) : (
261 <Box flexDirection="column">
262 <Text bold>{`${chart.measure} by ${chart.x}`}</Text>
263 {chart.categories.map((c, i) => (
264 <Box key={`bar${i}`} flexDirection="column">
265 {chart.series.map((s, si) => (
266 <Box key={`bar${i}-${si}`} gap={1}>
267 <Box minWidth={12}>
268 <Text dimColor>{si === 0 ? cell(c) : ''}</Text>
269 </Box>
270 <Text color={SERIES_COLORS[si]}>{'█'.repeat(Math.max(1, Math.round((Math.abs(s.values[i] ?? 0) / peak) * 40)))}</Text>
271 <Text>{`${s.values[i] === null ? '-' : fmtNumber(s.values[i] as number)}${chart.series.length > 1 ? ` ${cell(s.name)}` : ''}`}</Text>
272 </Box>
273 ))}
274 </Box>
275 ))}
276 {chart.note ? <Text dimColor>{chart.note}</Text> : null}
277 </Box>
278 )
279
280 // Feature #1067: the lineage as its layers, top to bottom.
281 const lineageTab = (
282 <Box flexDirection="column">
283 {layers.layers.map((layer, li) => (
284 <Box key={`lay${li}`} gap={1}>
285 <Box minWidth={20}>
286 <Text dimColor bold>
287 {layer.label}
288 </Text>
289 </Box>
290 <Text>{layer.nodes.map(n => cell(n.title)).join(' · ')}</Text>
291 </Box>
292 ))}
293 </Box>
294 )
295
296 const body: Record<TabId, unknown> = {
297 results: resultsTab,
298 chart: chartTab,
299 lineage: lineageTab,
300 base: sqlTab('base', m.baseSql, 'The base query is not in this result.'),
301 runtime: sqlTab('runtime', m.runSql, 'No runtime SQL in this result.'),
302 kb: kbTab,
303 governance: governanceTab,
304 }
305
306 return (
307 <Box flexDirection="column">
308 {m.header ? (
309 <Text key="command" dimColor wrap="truncate-end">
310 {`Bash $ ${m.header}`}
311 </Text>
312 ) : null}
313 <Box gap={1} justifyContent="space-between">
314 <Box gap={1}>
315 <Text key="badge" backgroundColor={own(TIER_COLOR, m.tier) ?? 'gray'} color="black" bold>
316 {` ${m.tier.replace('_', '-')} `}
317 </Text>
318 <Text dimColor>
319 {m.meta.join(' · ')}
320 {m.sourceName ? <Text bold dimColor={false}>{` · ${cell(m.sourceName)}`}</Text> : null}
321 </Text>
322 </Box>
323 {m.nav}
324 </Box>
325 <Box gap={1} marginTop={1} flexWrap="wrap">
326 {tabList.map(t => (
327 <Button
328 key={`tab-${t.id}`}
329 label={t.id === active ? `▸ ${t.label}` : t.label}
330 variant={t.id === active ? 'primary' : 'secondary'}
331 dimColor={t.id !== active}
332 onPress={() => m.act.setTab(t.id)}
333 />
334 ))}
335 </Box>
336 <Box key={`panel-${active}`} flexDirection="column" borderStyle="round" borderDimColor paddingX={1}>
337 {body[active]}
338 </Box>
339 </Box>
340 )
341}
342hooks/query-view/details-pane.tsx 210 lines1// The desktop card's one sidebar, Query details: Results, SQL, Lineage and KB
2// as tabs, so every card opens the same place from one Details button. The
3// Results, SQL and Lineage tabs draw the panes the card used to open one by one
4// (register.tsx draws them and hands the body in); the KB tab lists the query's
5// metrics, dimensions and rules, one line each, a click opening a row in place.
6// Pure: register.tsx reads the state and supplies the actions.
7
8import type { Ui } from './card'
9import { KIND_LABEL, capitalize, cell, clean, own } from './result'
10import type { DetailsTab, DetailsView, KbDef, KbSelection } from './state'
11
12export type DetailsActions = {
13 setTab: (tab: DetailsTab) => unknown
14 setSqlKind: (kind: 'base' | 'runtime') => unknown
15 // Open or close one KB tab row: `${kind}:${name}`, or `rule:${i}`.
16 toggle: (key: string) => unknown
17 copy: (text: string) => unknown
18}
19
20const TABS: Array<{ id: DetailsTab; label: string }> = [
21 { id: 'results', label: 'Results' },
22 { id: 'sql', label: 'SQL' },
23 { id: 'lineage', label: 'Lineage' },
24 { id: 'kb', label: 'KB' },
25]
26
27export function drawDetailsPane(ui: Ui, d: DetailsView | null, body: unknown, defs: Record<string, KbDef>, act: DetailsActions): unknown {
28 const { Box, Text, Button } = ui
29 if (!d) return <Text dimColor>Press Details on a query result.</Text>
30 const kbCount = d.kb.length + d.rules.length
31 return (
32 <Box flexDirection="column" gap={1}>
33 <Box gap={1} paddingX={1} alignItems="center">
34 {TABS.map(t => (
35 <Button
36 key={`dt-tab-${t.id}`}
37 label={t.id === 'kb' ? `KB (${kbCount})` : t.label}
38 variant={d.tab === t.id ? 'primary' : 'secondary'}
39 onPress={() => act.setTab(t.id)}
40 />
41 ))}
42 </Box>
43 {d.tab === 'kb' ? drawKbTab(ui, d, defs, act) : body}
44 {/* Which SQL is shown, under the SQL it switches. */}
45 {d.tab === 'sql' && d.sql.base && d.sql.runtime ? (
46 <Box gap={1} paddingX={1} alignItems="center">
47 <Button key="dt-sql-base" label="As written" variant={d.sql.kind === 'base' ? 'primary' : 'secondary'} onPress={() => act.setSqlKind('base')} />
48 <Button key="dt-sql-run" label="As run" variant={d.sql.kind === 'runtime' ? 'primary' : 'secondary'} onPress={() => act.setSqlKind('runtime')} />
49 </Box>
50 ) : null}
51 </Box>
52 )
53}
54
55// A dimension's qualified name ("platform_activity_ds_row__event_month") reads
56// as its own last part; the entity prefix only matters to the compiler.
57export function shortName(name: string): string {
58 const at = name.lastIndexOf('__')
59 return at >= 0 && at < name.length - 2 ? name.slice(at + 2) : name
60}
61
62// HUMAN_ENGAGEMENT_ONLY -> Human engagement only.
63export function ruleName(name: string): string {
64 return /^[A-Z0-9_]+$/.test(name) ? capitalize(name.toLowerCase().replace(/_/g, ' ')) : name
65}
66
67// A rule's explanation without the CLI hint at its end; no added clause the
68// server redacted to '?' placeholders.
69function ruleText(lines: string[]): string[] {
70 return lines
71 .map(line => line.replace(/\s*Read the full rule with:.*$/, '').trim())
72 .filter(line => line && !/'\?'/.test(line))
73}
74
75// The first sentence, for a row's one line.
76function firstSentence(text: string): string {
77 const m = /^(.+?[.!?])(\s|$)/.exec(text)
78 return (m ? m[1] : text).replace(/[.]$/, '')
79}
80
81// An open row's panel: a soft grey fill and a hairline edge.
82const PANEL_FILL = '#F5F5F7'
83const PANEL_BORDER = '#E5E5EA'
84
85// Kinds in the order a reader meets them, each its own section.
86const SECTIONS: Array<{ kind: string; title: string }> = [
87 { kind: 'Metric', title: 'METRICS' },
88 { kind: 'Measure', title: 'MEASURES' },
89 { kind: 'Dimension', title: 'DIMENSIONS' },
90]
91
92// One section per kind, then the rules: a row is the name and one line of
93// what it is; pressing it opens the detail under it.
94function drawKbTab(ui: Ui, d: DetailsView, defs: Record<string, KbDef>, act: DetailsActions): unknown {
95 const { Box, Text, Button } = ui
96 const kinds = [...SECTIONS, ...[...new Set(d.kb.map(x => x.kind))].filter(k => !SECTIONS.some(s => s.kind === k)).map(k => ({ kind: k, title: `${k.toUpperCase()}S` }))]
97
98 // An open row drops its one line: the panel under it says it in full.
99 const row = (key: string, isOpen: boolean, label: string, line: string) => (
100 <Box key={`${key}-row`} gap={2} alignItems="center">
101 <Box minWidth={26} alignItems="center">
102 <Button key={`dt-kb-${key}`} label={`${isOpen ? '▾' : '▸'} ${label}`} plain onPress={() => act.toggle(key)} />
103 </Box>
104 {isOpen ? null : (
105 <Text dimColor wrap="truncate-end">
106 {line}
107 </Text>
108 )}
109 </Box>
110 )
111 // What an open row shows, set apart on a soft panel with room inside.
112 const panel = (key: string, children: unknown) => (
113 <Box
114 key={key}
115 flexDirection="column"
116 gap={1}
117 marginLeft={2}
118 marginTop={1}
119 marginBottom={1}
120 paddingX={2}
121 paddingY={1}
122 borderStyle="round"
123 borderColor={PANEL_BORDER}
124 backgroundColor={PANEL_FILL}
125 >
126 {children}
127 </Box>
128 )
129 const fact = (key: string, label: string, value: string, code = false) => (
130 <Box key={key} gap={2}>
131 <Box minWidth={10}>
132 <Text dimColor>{label}</Text>
133 </Box>
134 {code ? <Text bold>{value}</Text> : <Text>{value}</Text>}
135 </Box>
136 )
137
138 const asset = (x: KbSelection, i: number) => {
139 const key = `${x.kind}:${x.name}`
140 const isOpen = d.open.includes(key)
141 const def = defs[key]
142 const desc = def?.status === 'ok' && def.description ? clean(def.description) : ''
143 const line = desc ? firstSentence(desc) : def?.status === 'loading' ? 'Loading…' : x.expansion ? clean(x.expansion) : ''
144 const reference = `{{ ${x.kind}('${x.name}') }}`
145 const facts: unknown[] = []
146 if (isOpen) {
147 if (def?.status === 'ok' && def.type) facts.push(fact(`${key}-type`, 'Type', own(KIND_LABEL, def.type) ?? def.type))
148 for (const [pi, part] of (def?.parts ?? []).entries()) facts.push(fact(`${key}-p${pi}`, capitalize(part.label), cell(part.value), true))
149 if (x.expansion) facts.push(fact(`${key}-sql`, 'Compiles to', clean(x.expansion), true))
150 const where = [def?.group, def?.lifecycle].filter(Boolean).join(' · ')
151 if (where) facts.push(fact(`${key}-grp`, 'Group', where))
152 facts.push(fact(`${key}-ref`, 'In query', `${reference}${x.alias ? ` AS ${x.alias}` : ''}`, true))
153 }
154 return (
155 <Box key={`dk-${i}`} flexDirection="column">
156 {row(key, isOpen, shortName(x.name), line)}
157 {isOpen
158 ? panel(`dk-p-${i}`, [
159 desc ? <Text key={`${key}-desc`}>{desc}</Text> : null,
160 <Box key={`${key}-facts`} flexDirection="column">
161 {facts}
162 </Box>,
163 <Box key={`${key}-btns`} gap={1}>
164 <Button key={`dt-copy-ref-${key}`} label="Copy reference" variant="secondary" onPress={() => act.copy(reference)} />
165 {x.expansion ? <Button key={`dt-copy-sql-${key}`} label="Copy SQL" variant="secondary" onPress={() => act.copy(clean(x.expansion))} /> : null}
166 </Box>,
167 ])
168 : null}
169 </Box>
170 )
171 }
172
173 const rule = (r: DetailsView['rules'][number], i: number) => {
174 const key = `rule:${i}`
175 const isOpen = d.open.includes(key)
176 const text = ruleText(r.lines)
177 return (
178 <Box key={`dr-${i}`} flexDirection="column">
179 {row(key, isOpen, ruleName(r.title), text[0] ? firstSentence(text[0]) : r.badge.toLowerCase())}
180 {isOpen
181 ? panel(`dr-p-${i}`, [
182 ...text.map((line, j) => <Text key={`dr-${i}-${j}`}>{line}</Text>),
183 fact(`dr-${i}-name`, 'Rule', r.title, true),
184 ])
185 : null}
186 </Box>
187 )
188 }
189
190 const section = (key: string, title: string, children: unknown[]) =>
191 children.length ? (
192 <Box key={key} flexDirection="column">
193 <Text dimColor bold>{`${title} · ${children.length}`}</Text>
194 {children}
195 </Box>
196 ) : null
197
198 return (
199 <Box flexDirection="column" gap={1} paddingX={1}>
200 {kbCount(d) === 0 ? <Text dimColor>This query uses no KB assets and no rules changed it.</Text> : null}
201 {kinds.map(s => section(`dks-${s.kind}`, s.title, d.kb.map((x, i) => (x.kind === s.kind ? asset(x, i) : null)).filter(Boolean)))}
202 {section('dks-rules', 'RULES', d.rules.map(rule))}
203 </Box>
204 )
205}
206
207function kbCount(d: DetailsView): number {
208 return d.kb.length + d.rules.length
209}
210hooks/query-view/loaders.ts 87 lines1// Feature #1067: bookkeeping for what the view reads beyond the Bash output - a
2// large result Claude Code saved to a file, and the lineage upstream. Pure: the
3// reads themselves run in register.tsx (a mod's `$` never crosses an import).
4// None of it runs on a query's path: tool.call only remembers a path.
5
6import type { QueryResult } from './result'
7
8// `$.fs.read` refuses a file past this; such a result is reported, not read.
9export const READ_LIMIT = 4 * 1024 * 1024
10const MAX_SAVED = 200
11const MAX_PARSED = 4
12export const MAX_PARALLEL_READS = 3
13
14export type Loaded = { result: QueryResult } | { tooLarge: number } | null
15
16// tool_use_id -> the file Claude Code moved a large output to, from the
17// engine's own `persistedOutputPath` (never from text a command printed).
18// Module memory, set synchronously: no state write sits on the query path.
19const saved = new Map<string, { path: string; size: number }>()
20// Parsed saved results by path, so redraws never re-read megabytes.
21const parsed = new Map<string, QueryResult | null>()
22
23export function rememberSaved(id: string, result: unknown): void {
24 const r = result as { persistedOutputPath?: unknown; persistedOutputSize?: unknown } | null
25 if (typeof r?.persistedOutputPath !== 'string') return
26 saved.set(id, { path: r.persistedOutputPath, size: typeof r.persistedOutputSize === 'number' ? r.persistedOutputSize : 0 })
27 if (saved.size > MAX_SAVED) saved.delete(saved.keys().next().value as string)
28}
29
30export function savedFor(id: string | undefined): { path: string; size: number } | undefined {
31 return id ? saved.get(id) : undefined
32}
33
34// The desktop draws its card where the call's tool.call never reached this
35// module's memory, and passes the engine's own stand-in for the moved output:
36// `<persisted-output>` naming the file. Only a file in a session's
37// tool-results folder is taken, and only when the stand-in opens the output.
38const PERSISTED = /^<persisted-output>\s*\nOutput too large \(([\d.]+)(KB|MB)\)\. Full output saved to: (\/\S+\/\.claude\/projects\/[^/\s]+\/[^/\s]+\/tool-results\/[\w-]+\.txt)\s*$/m
39
40export function savedFromPreview(output: unknown): { path: string; size: number } | undefined {
41 const text = typeof output === 'string' ? output : (output as { stdout?: unknown } | null)?.stdout
42 if (typeof text !== 'string' || !text.startsWith('<persisted-output>')) return undefined
43 const m = PERSISTED.exec(text)
44 if (!m) return undefined
45 return { path: m[3], size: Math.ceil(Number(m[1]) * (m[2] === 'MB' ? 1024 * 1024 : 1024)) }
46}
47
48export function parsedFor(path: string): QueryResult | null | undefined {
49 return parsed.get(path)
50}
51
52export function rememberParsed(path: string, result: QueryResult | null): void {
53 parsed.set(path, result)
54 if (parsed.size > MAX_PARSED) parsed.delete(parsed.keys().next().value as string)
55}
56
57// Feature #1067: the results a Full results sidebar shows, by row key - kept
58// here, not in session state, so ten thousand rows never cross into it. A
59// module reload forgets them; the sidebar then asks to open it again.
60const opened = new Map<string, QueryResult>()
61
62export function rememberOpened(id: string, result: QueryResult): void {
63 opened.delete(id)
64 opened.set(id, result)
65 if (opened.size > MAX_PARSED) opened.delete(opened.keys().next().value as string)
66}
67
68export function openedFor(id: string | undefined): QueryResult | undefined {
69 return id ? opened.get(id) : undefined
70}
71
72// Every `graphit` read the view makes - each card's lineage and the KB
73// sidebar - shares one cap, so open cards never crowd the user's own queries.
74let reading = 0
75const waiting: Array<() => void> = []
76
77export async function withReadSlot<T>(task: () => Promise<T>): Promise<T> {
78 if (reading >= MAX_PARALLEL_READS) await new Promise<void>(resolve => waiting.push(resolve))
79 reading += 1
80 try {
81 return await task()
82 } finally {
83 reading -= 1
84 waiting.shift()?.()
85 }
86}
87hooks/query-view/panes.tsx 330 lines1// The query view's sidebars: the KB definition (Feature #1062), and the
2// lineage explorer and full SQL the card opens (Feature #1067). Panes are
3// native, so they scroll and every row is clickable. Pure: register.tsx reads
4// the state and supplies the actions (a mod's `$` never crosses an import).
5
6import type { Ui } from './card'
7import { KIND_LABEL, capitalize, cell, clean, own } from './result'
8import { templateColor, tokenSpans } from './spans'
9import { codeChunks, formatLines, prettySql, tokenize } from './sql'
10import type { Explore, KbDef, KbSelection, SqlPane } from './state'
11import { CELL_W, renderFlowSvg } from './flow'
12import { renderHeroSvg } from './svgcard'
13import { chainOf } from './upstream'
14import type { Layers } from './upstream'
15
16// The inspector's inset grouped lists.
17const INSET_FILL = '#FFFFFF'
18const INSET_BORDER = '#E5E5EA'
19
20export function drawKbPane(ui: Ui, sel: KbSelection | null, def: KbDef | undefined, copy: (text: string) => unknown): unknown {
21 const { Box, Text, Button } = ui
22 if (!sel) return <Text dimColor>Click a KB reference in a query result to see its definition.</Text>
23 const color = templateColor(sel.kind)
24 const reference = `{{ ${cell(sel.kind)}('${cell(sel.name)}') }}`
25 const compiled = clean(sel.expansion)
26 const alias = sel.alias ? ` AS ${sel.alias}` : ''
27
28 const rows: Array<{ label: string; value: string; isCode?: boolean }> = []
29 rows.push({ label: 'Kind', value: own(KIND_LABEL, def?.type) ?? sel.kind })
30 if (sel.kind === 'Dimension' && compiled === sel.name) rows.push({ label: 'Column', value: compiled, isCode: true })
31 for (const part of def?.parts ?? []) rows.push({ label: capitalize(part.label), value: part.value, isCode: true })
32 if (def?.group) rows.push({ label: 'Group', value: def.group })
33 if (def?.lifecycle) rows.push({ label: 'Lifecycle', value: def.lifecycle })
34 if (def?.domains?.length) rows.push({ label: 'Access', value: def.domains.join(', ') })
35
36 const heading = (text: string, key: string) => (
37 <Text key={key} dimColor bold>
38 {text}
39 </Text>
40 )
41
42 return (
43 <Box flexDirection="column" gap={1} paddingX={1}>
44 <Box flexDirection="column">
45 <Box gap={1}>
46 <Text backgroundColor={color} color="#ffffff" bold>
47 {` ${sel.kind.toUpperCase()} `}
48 </Text>
49 <Text bold>{cell(sel.name)}</Text>
50 </Box>
51 {def?.status === 'loading' ? <Text dimColor>Loading the definition…</Text> : null}
52 {def?.status === 'error' ? <Text color="red">{clean(def.error)}</Text> : null}
53 {def?.description ? <Text>{clean(def.description)}</Text> : null}
54 {def?.status === 'unsupported' ? (
55 <Text dimColor>{`No ${sel.kind.toLowerCase()} definition read in this CLI version.`}</Text>
56 ) : null}
57 </Box>
58
59 <Box flexDirection="column">
60 {heading('DEFINITION', 'h-def')}
61 {rows.map((row, i) => (
62 <Box key={`row${i}`} gap={2}>
63 <Box minWidth={10}>
64 <Text dimColor>{row.label}</Text>
65 </Box>
66 {row.isCode ? (
67 <Text color={color} bold>{cell(row.value)}</Text>
68 ) : (
69 <Text>{cell(row.value)}</Text>
70 )}
71 </Box>
72 ))}
73 </Box>
74
75 <Box flexDirection="column">
76 {heading('IN THIS QUERY', 'h-query')}
77 <Box gap={2}>
78 <Box minWidth={10}>
79 <Text dimColor>Written</Text>
80 </Box>
81 <Text>{tokenSpans(Text, tokenize(`${reference}${alias}`), 'w-')}</Text>
82 </Box>
83 {compiled ? (
84 formatLines(`${compiled}${alias}`).map((line, i) => (
85 <Box key={`c${i}`} gap={2}>
86 <Box minWidth={10}>
87 <Text dimColor>{i === 0 ? 'Compiled' : ''}</Text>
88 </Box>
89 <Text>{tokenSpans(Text, line, `c${i}-`)}</Text>
90 </Box>
91 ))
92 ) : (
93 <Text dimColor>Used outside the SELECT list; see Runtime SQL.</Text>
94 )}
95 </Box>
96
97 <Box gap={1}>
98 <Button key="kb-copy-ref" label="Copy reference" onPress={() => copy(reference)} />
99 {compiled ? (
100 <Button key="kb-copy-sql" label="Copy SQL" onPress={() => copy(compiled)} />
101 ) : null}
102 </Box>
103 </Box>
104 )
105}
106
107// The full SQL, native and scrollable: the card shows only its first lines.
108export function drawSqlPane(ui: Ui, pane: SqlPane | null, copy: (text: string) => unknown): unknown {
109 const { Box, Text, Button, Code } = ui
110 if (!pane) return <Text dimColor>Open the SQL tab on a query result, then Open full SQL.</Text>
111 const pretty = prettySql(pane.sql)
112 const lines = formatLines(pretty)
113 const width = String(lines.length).length
114 return (
115 <Box flexDirection="column" gap={1} paddingX={1}>
116 <Box justifyContent="space-between">
117 <Text bold>{`${pane.title} · ${lines.length} lines`}</Text>
118 <Button key="sqlp-copy" label="Copy" onPress={() => copy(pretty)} />
119 </Box>
120 {Code ? (
121 codeChunks(pretty).map((c, ci) => <Code key={`sqlp-c${ci}`} source={c.source} language="sql" startLine={c.startLine} />)
122 ) : (
123 <Box flexDirection="column">
124 {lines.map((line, i) => (
125 <Box key={`sp${i}`} gap={1}>
126 <Text dimColor>{String(i + 1).padStart(width)}</Text>
127 <Text>{tokenSpans(Text, line, `sp${i}-`)}</Text>
128 </Box>
129 ))}
130 </Box>
131 )}
132 </Box>
133 )
134}
135
136// The lineage explorer: with no node chosen it lists every layer; a node shows
137// its facts and the nodes it comes from and feeds, each one a click away.
138// What the explorer's controls do; each runs in register.tsx with `$`.
139export type ExploreActions = {
140 go: (id: string) => unknown
141 back: () => unknown
142 all: () => unknown
143 openSql: (title: string, sql: string) => unknown
144 copy: (text: string) => unknown
145}
146
147// A node's SQL shows this many lines in the explorer; Open full SQL has the rest.
148const SQL_PREVIEW_LINES = 12
149
150// `columns`: the pane body's width in cells. The flow is laid out across all of
151// it, so a wide layer spreads out instead of wrapping, and a wider (or
152// maximized) pane redraws it wider.
153export function drawExplorer(ui: Ui, ex: Explore | null, act: ExploreActions, columns?: number): unknown {
154 const { Box, Text, Button, Code, Svg } = ui
155 if (!ex) return <Text dimColor>Open Lineage on a query result, then Explore lineage.</Text>
156 const nodes = ex.layers.flatMap(l => l.nodes.map(n => ({ ...n, layer: l.label })))
157 const byId = new Map(nodes.map(n => [n.id, n]))
158 const byTitle = new Map(nodes.map(n => [n.title, n]))
159 const sel = ex.selected ? byId.get(ex.selected) : undefined
160 const go = act.go
161 const titleCase = (t: string) => t.charAt(0) + t.slice(1).toLowerCase()
162
163 // An inset grouped list: rounded, white, on the pane's own background.
164 const group = (key: string, header: string, children: unknown) => (
165 <Box key={key} flexDirection="column">
166 <Text dimColor bold>{` ${header}`}</Text>
167 <Box flexDirection="column" borderStyle="round" borderColor={INSET_BORDER} backgroundColor={INSET_FILL} paddingX={1}>
168 {children}
169 </Box>
170 </Box>
171 )
172 // A navigation row: colored dot, title, muted subtitle, chevron.
173 const navRow = (n: { id: string; title: string; color: string; subtitle?: string }, key: string) => (
174 <Box key={key} justifyContent="space-between" alignItems="center">
175 <Box gap={1} alignItems="center" flexShrink={1}>
176 <Text color={n.color}>{'●'}</Text>
177 <Button key={`${key}-b`} label={n.title} plain onPress={() => go(n.id)} />
178 {n.subtitle ? (
179 <Text dimColor wrap="truncate-end">
180 {n.subtitle}
181 </Text>
182 ) : null}
183 </Box>
184 <Text dimColor>{'›'}</Text>
185 </Box>
186 )
187 const hero = (kind: string, title: string, subtitle: string | undefined, color: string) => {
188 // Never name a local `h`: the JSX factory is `h`.
189 const heroSvg = renderHeroSvg({ kind, title, subtitle, color })
190 return Svg ? (
191 <Svg key="lx-hero" source={heroSvg.svg} alt={`${titleCase(kind)}: ${title}`} width={heroSvg.width} height={heroSvg.height} />
192 ) : (
193 <Text bold>{`${titleCase(kind)}: ${title}`}</Text>
194 )
195 }
196 // Only inside a node, and saying where it goes: the node visited before this
197 // one, or the overview. The overview needs no bar: its tab already says Lineage.
198 const prev = ex.trail.length ? byId.get(ex.trail[ex.trail.length - 1]) : undefined
199 const navBar = (
200 <Box alignItems="center">
201 <Button key="lx-back" label={prev ? `‹ ${prev.title}` : '‹ All layers'} variant="secondary" onPress={() => act.back()} />
202 </Box>
203 )
204
205 // The chain drawn top to bottom: all of it on the overview, one node's own
206 // upstream and downstream on its page. Each node is a native box with its
207 // name as a Button, laid out in flow; only the links between layers are
208 // drawn (flow.ts). Pressing a node opens it here.
209 const flow = (key: string, spec: Layers, focus?: string) => {
210 if (!Svg) return null
211 // The body's cells less the explorer's own padding, never narrower than the old fixed 400px.
212 const width = columns ? Math.max(400, (columns - 4) * CELL_W) : undefined
213 const drawn = renderFlowSvg(spec, { focus, width })
214 const alt = focus ? `Lineage of ${sel?.title ?? ''}` : `${ex.title}, top to bottom`
215 return (
216 <Box key={key} flexDirection="column" alignSelf="flex-start">
217 {drawn.strips.map(strip =>
218 strip.kind === 'link' ? (
219 <Svg key={`${key}-${strip.key}`} source={strip.svg} alt={alt} width={drawn.width} height={strip.height} />
220 ) : (
221 // A node is native, so its name takes the first press and no
222 // drawing has to line up with it.
223 <Box key={`${key}-${strip.key}`} flexDirection="row" marginLeft={strip.lead} marginTop={strip.first ? 0 : 1}>
224 {strip.nodes.map(n => (
225 <Box
226 key={`${key}-box-${n.id}`}
227 width={n.cols}
228 marginLeft={n.gap}
229 flexDirection="column"
230 borderStyle="round"
231 borderColor={n.color}
232 backgroundColor={n.focus ? '#F2F8F7' : '#FFFFFF'}
233 paddingX={1}
234 >
235 <Button key={`${key}-n-${n.id}`} label={n.label} plain dimColor={n.muted || undefined} onPress={() => (n.focus ? undefined : go(n.id))} />
236 {n.subtitle ? (
237 <Text dimColor wrap="truncate-end">
238 {n.subtitle}
239 </Text>
240 ) : null}
241 </Box>
242 ))}
243 </Box>
244 ),
245 )}
246 </Box>
247 )
248 }
249 const spec: Layers = { layers: ex.layers, edges: ex.edges }
250
251 if (!sel) {
252 return (
253 <Box flexDirection="column" gap={1} paddingX={1}>
254 {hero('LINEAGE', ex.title, `${ex.layers.length} layers · ${nodes.length} nodes`, '#4DB6AC')}
255 {/* The drawing is the navigation; without one (the terminal), the layers as rows. */}
256 {Svg ? flow('lx-flow', spec) : ex.layers.map((layer, li) => group(`ly${li}`, layer.label, layer.nodes.map((n, ni) => navRow(n, `ln${li}-${ni}`))))}
257 </Box>
258 )
259 }
260
261 const uniq = <T extends { id: string }>(list: T[]) => list.filter((n, i) => list.findIndex(m => m.id === n.id) === i)
262 const from = uniq(ex.edges.filter(x => x.to === sel.id).map(x => byId.get(x.from)).filter((n): n is NonNullable<typeof n> => !!n))
263 const into = uniq(ex.edges.filter(x => x.from === sel.id).map(x => byId.get(x.to)).filter((n): n is NonNullable<typeof n> => !!n))
264 const facts = sel.facts ?? []
265 const plainFacts = facts.filter(f => !f.code)
266 const codeFacts = facts.filter(f => f.code)
267 // A value naming other nodes ("ua_installs, cpi_num") becomes chips that open them.
268 const factValue = (value: string, key: string) => {
269 const parts = value.split(/,\s*/)
270 const linked = parts.length > 0 && parts.every(p => byTitle.has(p))
271 if (!linked) return <Text key={key}>{value}</Text>
272 return (
273 <Box key={key} gap={1} flexWrap="wrap" justifyContent="flex-end">
274 {parts.map((p, pi) => (
275 <Button key={`${key}-${pi}`} label={p} variant="secondary" onPress={() => go(byTitle.get(p)!.id)} />
276 ))}
277 </Box>
278 )
279 }
280 return (
281 <Box flexDirection="column" gap={1} paddingX={1}>
282 {navBar}
283 {hero(sel.layer, sel.title, sel.subtitle, sel.color)}
284 {plainFacts.length > 0
285 ? group(
286 'lx-facts',
287 'DETAILS',
288 plainFacts.map((f, i) => (
289 <Box key={`lf${i}`} justifyContent="space-between" gap={2}>
290 <Text dimColor>{f.label}</Text>
291 {factValue(f.value, `lfv${i}`)}
292 </Box>
293 )),
294 )
295 : null}
296 {flow('lx-chain', chainOf(spec, sel.id), sel.id)}
297 {codeFacts.map((f, i) => {
298 // A long query (a source's SQL runs to hundreds of lines) shows its
299 // head here; the full SQL sidebar is wider and holds every line.
300 const pretty = prettySql(f.value)
301 const lines = pretty.split('\n')
302 const label = f.label || 'SQL'
303 const cut = lines.length > SQL_PREVIEW_LINES
304 const shown = cut ? lines.slice(0, SQL_PREVIEW_LINES).join('\n') : pretty
305 return (
306 <Box key={`lc${i}`} flexDirection="column">
307 <Box justifyContent="space-between" alignItems="center">
308 <Text dimColor bold>{` ${label.toUpperCase()}${lines.length > 1 ? ` · ${lines.length} lines` : ''}`}</Text>
309 <Box gap={1} alignItems="center">
310 <Button key={`lc${i}-copy`} label="Copy" plain onPress={() => act.copy(pretty)} />
311 {cut ? <Button key={`lc${i}-open`} label="Open full SQL" variant="secondary" onPress={() => act.openSql(`${sel.title} · ${label}`, f.value)} /> : null}
312 </Box>
313 </Box>
314 {Code ? (
315 codeChunks(shown).map((c, ci) => (
316 <Code key={`lc${i}-${ci}`} source={c.source} language="sql" startLine={lines.length > 1 ? c.startLine : undefined} />
317 ))
318 ) : (
319 <Text>{shown}</Text>
320 )}
321 {cut ? <Text dimColor>{` ${lines.length - SQL_PREVIEW_LINES} more lines - Open full SQL`}</Text> : null}
322 </Box>
323 )
324 })}
325 {!Svg && from.length > 0 ? group('lx-from', 'COMES FROM', from.map((n, i) => navRow(n, `lfrom${i}`))) : null}
326 {!Svg && into.length > 0 ? group('lx-into', 'FEEDS', into.map((n, i) => navRow(n, `linto${i}`))) : null}
327 </Box>
328 )
329}
330hooks/query-view/results-pane.tsx 221 lines1// Feature #1067: Full results - every row and every column of one query in a
2// sidebar that opens as wide as the table: search across the columns, sort by
3// a column header, copy as TSV or CSV. The table is a window over the rows: it
4// draws only what the pane shows, and register.tsx moves the window on the
5// person's wheel (ui.scroll), because the host refuses any drawing past
6// 100,000 serialized characters however much of it is on screen. Pure:
7// register.tsx keeps the view state and supplies the actions.
8
9import { cell } from './result'
10import type { QueryResult } from './result'
11import type { ResultsView } from './state'
12
13const MAX_COL_CHARS = 28
14// The widest sidebar the view asks for; the person can drag it wider.
15const MAX_PANE_COLUMNS = 240
16const COL_GAP = 3
17// The table's edge, its header and footer fill, and every other row's band.
18const TABLE_BORDER = '#E5E5EA'
19const HEAD_FILL = '#F5F5F7'
20const BAND_FILL = '#FAFAFA'
21// The window may spend this many serialized characters of the host's 100,000
22// per drawing: a cell costs its box, text, rule, keys and styles (about 280
23// measured), a row its own box and the row number on top.
24const TREE_CHARS = 60000
25const CELL_CHARS = 300
26const ROW_CHARS = 400
27// Pane rows above and around the table: the details tabs, search, status line,
28// gaps, and the table's border and header.
29const CHROME_ROWS = 10
30// The fewest rows a window shows, however short the pane.
31const MIN_WINDOW = 8
32
33type Row = Record<string, unknown>
34// eslint-disable-next-line @typescript-eslint/no-explicit-any
35type Ui = Record<string, any>
36
37export type ResultsActions = {
38 search: (query: string) => unknown
39 sortBy: (column: string) => unknown
40 // Move the window's first row (the ▲ ▼ buttons).
41 setTop: (top: number) => unknown
42 copy: (text: string) => unknown
43}
44
45// The narrowest a column shrinks to when the table must fit the pane.
46const MIN_COL = 6
47
48// Column widths that fit `room` cells: the widest are trimmed first, down to a
49// shared ceiling, so a short column never pays for a long one.
50export function fitWidths(widths: number[], room: number): number[] {
51 if (widths.reduce((a, b) => a + b, 0) <= room) return widths
52 let ceiling = Math.max(...widths)
53 while (ceiling > MIN_COL && widths.reduce((a, w) => a + Math.min(w, ceiling), 0) > room) ceiling -= 1
54 return widths.map(w => Math.min(w, ceiling))
55}
56
57// How many rows the table draws at once: what the pane's body has room for,
58// within the drawing's character budget.
59export function windowRows(bodyRows: number | undefined, columns: number): number {
60 const fit = Math.max(MIN_WINDOW, (bodyRows ?? 40) - CHROME_ROWS)
61 const budget = Math.max(MIN_WINDOW, Math.floor(TREE_CHARS / (ROW_CHARS + CELL_CHARS * columns)))
62 return Math.min(fit, budget)
63}
64
65// Where the window's first row lands after a wheel move of `by` rows.
66export function nextTop(top: number, by: number, total: number, window: number): number {
67 return Math.max(0, Math.min(top + by, Math.max(0, total - window)))
68}
69
70// The rows the view shows: matching the search (case-insensitive, any column
71// the policy did not mask), then sorted - numbers as numbers, empties last.
72export function viewRows(rows: Row[], cols: string[], hidden: Set<string>, view: Pick<ResultsView, 'query' | 'sort' | 'desc'>): Row[] {
73 const q = view.query.trim().toLowerCase()
74 const seen = cols.filter(c => !hidden.has(c))
75 const matched = q ? rows.filter(r => seen.some(c => r[c] != null && String(r[c]).toLowerCase().includes(q))) : rows
76 if (!view.sort || !cols.includes(view.sort)) return matched
77 const dir = view.desc ? -1 : 1
78 const key = view.sort
79 return [...matched].sort((a, b) => {
80 const x = a[key]
81 const y = b[key]
82 if (x == null || y == null) return x == null ? (y == null ? 0 : 1) : -1
83 if (typeof x === 'number' && typeof y === 'number') return (x - y) * dir
84 return String(x).localeCompare(String(y), 'en', { numeric: true }) * dir
85 })
86}
87
88// The rows as text a spreadsheet pastes: masked columns stay empty.
89export function delimited(cols: string[], rows: Row[], hidden: Set<string>, sep: '\t' | ','): string {
90 const field = (v: unknown): string => {
91 const s = v == null ? '' : String(v)
92 if (sep === '\t') return s.replace(/[\t\n\r]/g, ' ')
93 return /[",\n\r]/.test(s) ? `"${s.replace(/"/g, '""')}"` : s
94 }
95 return [cols.map(field).join(sep), ...rows.map(r => cols.map(c => (hidden.has(c) ? '' : field(r[c]))).join(sep))].join('\n')
96}
97
98// Every value exactly as the query returned it: no rounding, no thousands
99// separators, no date reshaping. The sidebar is where the raw result is read.
100const shownText = (v: unknown): string => (typeof v === 'number' ? String(v) : cell(v))
101
102export const columnsOf = (result: QueryResult): string[] => (result.columns?.length ? result.columns : Object.keys(result.rows[0] ?? {})).map(String)
103
104// The sidebar width that shows every column side by side, sized on the first
105// rows: the row number, each column at its widest (capped), the gaps, padding.
106export function resultsWidth(result: QueryResult): number {
107 const sample = result.rows.slice(0, 200)
108 const widths = columnsOf(result).map(c => Math.min(MAX_COL_CHARS, Math.max(c.length + 4, ...sample.map(r => shownText(r[c]).length))))
109 const total = widths.reduce((sum, w) => sum + w + COL_GAP, String(result.rows.length).length + COL_GAP + 4)
110 return Math.min(MAX_PANE_COLUMNS, Math.max(60, total))
111}
112
113// `bodyRows` and `bodyColumns`: the pane body's size in cells, as the surface laid it out.
114export function drawResultsPane(
115 ui: Ui,
116 result: QueryResult | undefined,
117 view: ResultsView | null,
118 act: ResultsActions,
119 bodyRows?: number,
120 bodyColumns?: number,
121): unknown {
122 const { Box, Text, Button, Input } = ui
123 if (!result || !view) return <Text dimColor>Open Full results on a query result.</Text>
124 const cols = columnsOf(result)
125 const hidden = new Set((result.hidden_columns ?? []).map(String))
126 const rows = viewRows(result.rows, cols, hidden, view)
127 // Only the window is drawn; the wheel moves it (register.tsx's ui.scroll hook).
128 const win = windowRows(bodyRows, cols.length)
129 const top = nextTop(view.top, 0, rows.length, win)
130 const shown = rows.slice(top, top + win)
131 const n = (x: number) => x.toLocaleString('en-US')
132
133 const parts = [view.query ? `${n(rows.length)} of ${n(result.rows.length)} rows match` : `${n(result.rows.length)} rows`]
134 if (view.sort) parts.push(`sorted by ${view.sort} ${view.desc ? 'high to low' : 'low to high'}`)
135 if (rows.length > shown.length) parts.push(`showing ${n(top + 1)}-${n(top + shown.length)}`)
136 const numWidth = Math.max(3, String(rows.length).length)
137 // Each column as wide as its header or widest shown value (capped), then
138 // trimmed so every column fits the pane - a cut value ends in "…" - and
139 // right-aligned when every value it holds is a number.
140 const natural = cols.map(c => Math.min(MAX_COL_CHARS, Math.max(cell(c).length + 3, ...shown.map(r => shownText(r[c]).length))))
141 // The pane less its padding, the table's border and padding, the row number, and a rule and gap per column.
142 const room = (bodyColumns ?? 120) - 2 - 4 - numWidth - 1 - 3 * cols.length
143 const widths = fitWidths(natural, room)
144 const atTop = top === 0
145 const atEnd = top + shown.length >= rows.length
146 const pager =
147 rows.length > shown.length ? (
148 <Box key="rs-pager" gap={1} alignItems="center">
149 <Button key="rs-up" label="▲" variant="secondary" dimColor={atTop} onPress={() => (atTop ? undefined : act.setTop(nextTop(top, -win, rows.length, win)))} />
150 <Button key="rs-down" label="▼" variant="secondary" dimColor={atEnd} onPress={() => (atEnd ? undefined : act.setTop(nextTop(top, win, rows.length, win)))} />
151 </Box>
152 ) : null
153 const numeric = cols.map(c => !hidden.has(c) && shown.some(r => typeof r[c] === 'number') && shown.every(r => r[c] == null || typeof r[c] === 'number'))
154 // One table row: the row number, then each cell after a dim column rule.
155 const tableRow = (key: string, fill: string | undefined, num: unknown, cells: unknown[]) => (
156 <Box key={key} backgroundColor={fill} paddingX={1} gap={1}>
157 <Box minWidth={numWidth} width={numWidth} flexShrink={0}>
158 {num}
159 </Box>
160 {cells.flatMap((c, ci) => [
161 <Text key={`${key}-rule-${ci}`} color={TABLE_BORDER}>
162 │
163 </Text>,
164 c,
165 ])}
166 </Box>
167 )
168
169 return (
170 <Box flexDirection="column" gap={1} paddingX={1}>
171 {Input ? (
172 <Input key="rs-search" label="Search" placeholder="Filter rows by any value" value={view.query} autoFocus onInput={(v: string) => act.search(v)} onSubmit={(v: string) => act.search(v)} />
173 ) : null}
174 <Box justifyContent="space-between" alignItems="center">
175 {/* The arrows lead, so a status that grows or shrinks never moves them. */}
176 <Box gap={2} alignItems="center">
177 {pager}
178 <Text key="rs-status" dimColor>{parts.join(' · ')}</Text>
179 </Box>
180 <Box gap={1}>
181 <Button key="rs-copy-tsv" label="Copy for Sheets" variant="secondary" onPress={() => act.copy(delimited(cols, rows, hidden, '\t'))} />
182 <Button key="rs-copy-csv" label="Copy CSV" variant="secondary" onPress={() => act.copy(delimited(cols, rows, hidden, ','))} />
183 </Box>
184 </Box>
185 {rows.length === 0 ? (
186 <Text dimColor>{view.query ? `No row matches "${view.query}".` : 'Query returned 0 rows.'}</Text>
187 ) : (
188 // A real table: a bordered box, a shaded header of sort buttons, a dim
189 // rule between every two columns, banded rows, numbers right-aligned.
190 <Box key="rs-table" flexDirection="column" borderStyle="round" borderColor={TABLE_BORDER}>
191 {tableRow('rs-head', HEAD_FILL, <Text dimColor>#</Text>, cols.map((c, ci) => {
192 const masked = hidden.has(c)
193 const arrow = view.sort === c ? (view.desc ? ' ↓' : ' ↑') : ''
194 return (
195 <Box key={`rs-h-${c}`} width={widths[ci]} flexShrink={0} justifyContent={numeric[ci] ? 'flex-end' : 'flex-start'}>
196 <Button key={`rs-sort-${c}`} label={`${cell(c)}${masked ? ' ⊘' : ''}${arrow}`} plain dimColor={view.sort !== c} onPress={() => act.sortBy(c)} />
197 </Box>
198 )
199 }))}
200 {shown.map((r, wi) => {
201 // Keys and banding follow the row's place in the whole result, so a
202 // row keeps its key and its shade as the window moves over it.
203 const i = top + wi
204 return tableRow(`rs-row-${i}`, i % 2 === 1 ? BAND_FILL : undefined, <Text dimColor>{String(i + 1)}</Text>, cols.map((c, ci) => {
205 const masked = hidden.has(c)
206 return (
207 <Box key={`rs-c-${c}-${i}`} width={widths[ci]} flexShrink={0} justifyContent={numeric[ci] ? 'flex-end' : 'flex-start'}>
208 <Text dimColor={masked} wrap="truncate-end">
209 {masked ? '•••' : shownText(r[c]) || ' '}
210 </Text>
211 </Box>
212 )
213 }))
214 })}
215 </Box>
216 )}
217 {hidden.size > 0 ? <Text color="gray">⊘ hidden by policy: {[...hidden].map(cell).join(', ')}</Text> : null}
218 </Box>
219 )
220}
221hooks/query-view/result.ts 338 lines1// Pure parts of the query view: the payload's shape, its parsing and the
2// per-line marks. No `$` here - every engine call stays in register.tsx.
3
4import type { KbDef } from './state'
5import { lineText } from './sql'
6import type { Expansion, Token } from './sql'
7
8export const MAX_ROWS = 10
9const MAX_COL = 24
10
11type Injection = {
12 outcome?: string
13 source?: string
14 rule_name?: string
15 source_id?: string
16 why?: string
17 added_clauses?: string[]
18 transformations?: Array<{ column?: string }>
19 reason?: string
20}
21
22// Feature #1062: the CLI's allowlist - see serialize_kb_references (backend).
23export type KbReference = { kind?: string; name?: string; deprecated?: boolean }
24
25// The gateway's reference kinds, as template kinds.
26export const REF_KIND: Record<string, string> = { metric: 'Metric', metric_raw: 'Measure', dim: 'Dimension' }
27
28// Feature #1099: a lookup keyed by query data (a ref kind, an outcome, a tier)
29// must never reach Object.prototype - `constructor` would return a function.
30export function own<T>(map: Record<string, T>, key: string | undefined): T | undefined {
31 return key !== undefined && Object.prototype.hasOwnProperty.call(map, key) ? map[key] : undefined
32}
33
34export type QueryResult = {
35 rows: Array<Record<string, unknown>>
36 columns?: string[]
37 row_count?: number
38 truncated?: boolean
39 query_ms?: number
40 source?: string
41 sql?: string
42 governed_sql?: string
43 hidden_columns?: string[]
44 provenance?: {
45 tier?: string
46 kb_refs?: number
47 kb_references?: KbReference[]
48 rules_enforced?: number
49 injection_summary?: {
50 injections?: Injection[]
51 override_denied?: Array<{ rule_name?: string; reason?: string }>
52 }
53 }
54}
55
56export const OUTCOME_BADGE: Record<string, { label: string; color: string }> = {
57 rewritten: { label: 'REWROTE', color: '#2e9e5b' },
58 conditional_applied: { label: 'APPLIED', color: '#2e9e5b' },
59 conditional_default_fire: { label: 'APPLIED BY DEFAULT', color: '#2e9e5b' },
60 validated: { label: 'VALIDATED', color: '#3b82f6' },
61 blocked: { label: 'BLOCKED', color: '#dc2626' },
62 overridden: { label: 'OVERRIDDEN', color: '#6b7280' },
63 conditional_skipped: { label: 'SKIPPED', color: '#6b7280' },
64}
65
66// Feature #1067: tier colors - Energy Teal for governed, a calm blue for
67// verified, system gray for ad hoc - and their labels.
68export const TIER_COLOR: Record<string, string> = {
69 governed: '#4DB6AC',
70 verified: '#5B8DEF',
71 ad_hoc: '#8E8E93',
72}
73
74export const TIER_LABEL: Record<string, string> = {
75 governed: 'Governed',
76 verified: 'Verified',
77 ad_hoc: 'Ad hoc',
78}
79
80// Query data is untrusted: strip ANSI, C0/C1 controls and bidi overrides.
81export function clean(value: unknown): string {
82 const s = value === null || value === undefined ? '' : String(value)
83 return s
84 .replace(/\u001b\[[0-9;:?]*[ -/]*[@-~]/g, '')
85 .replace(/\u001b[@-_]/g, '')
86 .replace(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f--]/g, '')
87}
88
89export function cell(value: unknown): string {
90 const s = clean(value).replace(/\n/g, ' ')
91 return s.length > MAX_COL ? `${s.slice(0, MAX_COL - 1)}…` : s
92}
93
94export function fmtNumber(n: number): string {
95 return n.toLocaleString('en-US', { maximumFractionDigits: Math.abs(n) >= 100 ? 2 : 4 })
96}
97
98function firstJsonObject(text: string): string | null {
99 const start = text.indexOf('{')
100 if (start < 0) return null
101 let depth = 0
102 let inStr = false
103 let esc = false
104 for (let i = start; i < text.length; i += 1) {
105 const ch = text[i]
106 if (inStr) {
107 if (esc) esc = false
108 else if (ch === '\\') esc = true
109 else if (ch === '"') inStr = false
110 continue
111 }
112 if (ch === '"') inStr = true
113 else if (ch === '{') depth += 1
114 else if (ch === '}') {
115 depth -= 1
116 if (depth === 0) return text.slice(start, i + 1)
117 }
118 }
119 return null
120}
121
122export function parseQueryResult(output: unknown): QueryResult | null {
123 // The terminal passes Bash's record ({ stdout, stderr }); the desktop's
124 // ToolUse card passes the output as one string.
125 const stdout =
126 typeof output === 'string'
127 ? output
128 : output && typeof output === 'object'
129 ? (output as { stdout?: unknown }).stdout
130 : undefined
131 if (typeof stdout !== 'string') return null
132 const json = firstJsonObject(stdout)
133 if (!json) return null
134 try {
135 const parsed = JSON.parse(json) as Partial<QueryResult>
136 const isQuery = Array.isArray(parsed.rows) && ('columns' in parsed || 'provenance' in parsed)
137 return isQuery ? (parsed as QueryResult) : null
138 } catch {
139 return null
140 }
141}
142
143export const MARK = {
144 added: { marker: '+', color: '#2e9e5b' },
145 masked: { marker: '~', color: '#c2409a' },
146 kb: { marker: '◆', color: '#2a9d8f' },
147}
148
149type LineMark = { marker: string; color: string; note: string }
150
151function escapeRe(s: string): string {
152 return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
153}
154
155// An added clause arrives parameterized (MEDIA_SOURCE <> '?'): each ? stands
156// for the literal the runtime SQL bound in its place.
157function clauseMatcher(clause: string): RegExp {
158 const pattern = escapeRe(clause.trim())
159 .replace(/'\\\?'/g, "'(?:[^']|'')*'")
160 .replace(/\\\?/g, "(?:'(?:[^']|'')*'|[\\w.-]+)")
161 .replace(/\s+/g, '\\s+')
162 return new RegExp(pattern, 'i')
163}
164
165// What each SQL line owes to the KB and to governance, for its gutter and note.
166export function marksFor(
167 line: Token[],
168 mode: 'base' | 'runtime',
169 injections: Injection[],
170 expansions: Expansion[],
171): LineMark[] {
172 const text = lineText(line)
173 const marks: LineMark[] = []
174 if (mode === 'base') {
175 // The reference itself opens the sidebar; the gutter flags the line.
176 if (line.some(t => t.kind === 'template')) marks.push({ ...MARK.kb, note: '' })
177 return marks
178 }
179 for (const inj of injections) {
180 const rule = cell(inj.rule_name ?? inj.source_id ?? 'rule')
181 if ((inj.added_clauses ?? []).some(cl => cl && clauseMatcher(cl).test(text))) {
182 marks.push({ ...MARK.added, note: rule })
183 }
184 for (const t of inj.transformations ?? []) {
185 if (t.column && new RegExp(`NULL\\s+AS\\s+"?${escapeRe(t.column)}\\b`, 'i').test(text)) {
186 marks.push({ ...MARK.masked, note: `${rule} hid ${cell(t.column)}` })
187 }
188 }
189 }
190 for (const x of runtimeExpansions(line, expansions)) {
191 marks.push({ ...MARK.kb, note: `${x.kind} ${cell(x.name)}` })
192 }
193 return marks
194}
195
196// The KB expansions a runtime SQL line holds: the select item whose alias a
197// base-query template compiled into.
198function runtimeExpansions(line: Token[], expansions: Expansion[]): Expansion[] {
199 const text = lineText(line)
200 return expansions.filter(x => new RegExp(`\\bAS\\s+"?${escapeRe(x.alias)}"?\\s*,?\\s*$`, 'i').test(text))
201}
202
203// A `graphit kb get metric` answer, cut to what the sidebar shows.
204export function parseMetricDef(stdout: string): KbDef {
205 try {
206 const entity = (JSON.parse(stdout) as { entity?: Record<string, unknown> }).entity ?? {}
207 const tp = (entity.type_params ?? {}) as Record<string, unknown>
208 const parts: Array<{ label: string; value: string }> = []
209 const named = (v: unknown) => (v && typeof v === 'object' ? (v as { name?: unknown }).name : v)
210 for (const key of ['measure', 'numerator', 'denominator', 'expr']) {
211 const v = named(tp[key])
212 if (typeof v === 'string' && v) parts.push({ label: key, value: v })
213 }
214 if (Array.isArray(tp.metrics)) {
215 parts.push({ label: 'metrics', value: tp.metrics.map(named).filter(Boolean).join(', ') })
216 }
217 if (typeof entity.filter === 'string' && entity.filter) parts.push({ label: 'filter', value: entity.filter })
218 const meta = ((entity.meta as { graphit?: Record<string, unknown> } | undefined)?.graphit ?? {}) as Record<string, unknown>
219 return {
220 status: 'ok',
221 type: typeof entity.type === 'string' ? entity.type : undefined,
222 description: typeof entity.description === 'string' ? entity.description : undefined,
223 group: typeof entity.group === 'string' ? entity.group : undefined,
224 lifecycle: typeof meta.lifecycle === 'string' ? meta.lifecycle : undefined,
225 domains: Array.isArray(entity.domain_keys) ? entity.domain_keys.map(String) : undefined,
226 parts,
227 }
228 } catch {
229 const err = (() => {
230 try {
231 return String((JSON.parse(stdout) as { error?: unknown }).error ?? '')
232 } catch {
233 return ''
234 }
235 })()
236 return { status: 'error', error: err || 'Could not read the definition.' }
237 }
238}
239
240// The query's own SQL from `graphit query "<sql>"` in the Bash command, for a
241// CLI too old to echo `sql` in its JSON.
242export function sqlFromCommand(command: string): string | undefined {
243 const dq = /\bquery\s+"((?:[^"\\]|\\.)*)"/.exec(command)
244 if (dq) return dq[1].replace(/\\(["\\$`])/g, '$1')
245 const sq = /\bquery\s+'([^']*)'/.exec(command)
246 return sq ? sq[1] : undefined
247}
248
249export function commandOf(input: unknown): string | null {
250 const command = (input as { command?: unknown } | null)?.command
251 return typeof command === 'string' ? cell(command) : null
252}
253
254export const KIND_LABEL: Record<string, string> = {
255 dim: 'Dimension',
256 metric: 'Metric',
257 metric_raw: 'Measure',
258 simple: 'Simple metric',
259 ratio: 'Ratio metric',
260 derived: 'Derived metric',
261 cumulative: 'Cumulative metric',
262 conversion: 'Conversion metric',
263}
264
265export function capitalize(s: string): string {
266 return s ? s[0].toUpperCase() + s.slice(1) : s
267}
268
269// Feature #1062: Issue #1025's rule, the same one scripts/show-query-result.mjs
270// applies - a graphit query whose stdout reaches this Bash call's output. A
271// piped or redirected query, or another command's JSON, is left to the engine.
272// The two copies must agree; gate.test.tsx and show-query-result.test.mjs pin
273// the same cases.
274// Project #305: a verbatim copy of graphitInvocationSource("query") in
275// scripts/plugin-status/host.mjs (npx `@graphit/cli[@<v>] query` included);
276// test/cursor-hooks.test.mjs fails if the two literals differ.
277const QUERY_INVOCATION = /(?:graphit|index\.js|@graphit\/cli(?:@\S+)?)\s+query\b/
278
279// Feature #1062 (Gate 2): blank out quoted strings and `#` comments, keeping
280// every position, so an operator inside the SQL (`x <> 'y'`, `n > 2`) is not read
281// as a redirect, and `graphit query` inside another command's quotes or a
282// comment is not read as a query.
283function maskQuotesAndComments(command: string): string {
284 let out = ''
285 let quote: string | null = null
286 for (let i = 0; i < command.length; i += 1) {
287 const ch = command[i]
288 if (quote) {
289 if (ch === '\\' && quote === '"' && i + 1 < command.length) {
290 out += ' '
291 i += 1
292 } else if (ch === quote) {
293 quote = null
294 out += ch
295 } else {
296 out += ' '
297 }
298 continue
299 }
300 if (ch === "'" || ch === '"') {
301 quote = ch
302 out += ch
303 } else if (ch === '#' && (i === 0 || /\s/.test(command[i - 1]))) {
304 while (i < command.length && command[i] !== '\n') {
305 out += ' '
306 i += 1
307 }
308 if (i < command.length) out += '\n'
309 } else {
310 out += ch
311 }
312 }
313 return out
314}
315
316export function isGraphitQuery(command: string): boolean {
317 return QUERY_INVOCATION.test(maskQuotesAndComments(command))
318}
319
320export function queryReachesStdout(command: string): boolean {
321 const masked = maskQuotesAndComments(command)
322 for (const match of masked.matchAll(new RegExp(QUERY_INVOCATION.source, 'g'))) {
323 const tail = masked.slice(match.index).split(/\n|;|&&|\|\||(?<![|&>])&(?![&>])/)[0]
324 const withoutStderr = tail.replace(/2>&\d|2>>?\s*\S+/g, '')
325 if (!/(?<!\|)\|(?!\|)|>/.test(withoutStderr)) return true
326 // Feature #1067: a single pipe into head/tail (optional -n N / -N) still
327 // shows the document when it fits; a cut-short one fails to parse and
328 // stays raw. Anything after it, or any other pipe, does not count.
329 const pipeAt = withoutStderr.search(/(?<!\|)\|(?!\|)/)
330 if (pipeAt >= 0 && !/>/.test(withoutStderr.slice(0, pipeAt)) && HEAD_OR_TAIL.test(withoutStderr.slice(pipeAt + 1))) {
331 return true
332 }
333 }
334 return false
335}
336
337const HEAD_OR_TAIL = /^\s*(?:head|tail)(?:\s+(?:-n\s*\d+|-\d+))?\s*$/
338hooks/query-view/sql.ts 266 lines1// SQL tokenizer and formatter for the query view: pure functions, no `$`.
2
3export type TokenKind =
4 | 'kw'
5 | 'fn'
6 | 'str'
7 | 'num'
8 | 'param'
9 | 'comment'
10 | 'template'
11 | 'op'
12 | 'ident'
13 | 'punct'
14 | 'ws'
15
16export type Token = {
17 kind: TokenKind
18 text: string
19 // A KB template's kind and name: {{ Metric('revenue') }} -> Metric, revenue.
20 templateKind?: string
21 templateName?: string
22}
23
24const KEYWORDS = new Set(
25 (
26 'select from where and or not in is null as on join left right inner outer full cross group by order ' +
27 'having limit offset union all distinct case when then else end with over partition between like ilike ' +
28 'asc desc true false exists qualify interval cast using lateral window rows range preceding following ' +
29 'current row unbounded filter within except intersect values insert update delete set into'
30 ).split(' '),
31)
32
33const CLAUSE_STARTS = new Set(['select', 'from', 'where', 'having', 'limit', 'qualify', 'union', 'with', 'window', 'offset'])
34const TWO_WORD_CLAUSES = new Set(['group', 'order'])
35const JOIN_PREFIXES = new Set(['left', 'right', 'inner', 'full', 'cross', 'outer'])
36
37const RULES: Array<[TokenKind, RegExp]> = [
38 ['template', /^\{\{\s*([A-Za-z_]+)\(\s*['"]([^'"]+)['"]\s*\)\s*\}\}/],
39 ['comment', /^--[^\n]*/],
40 ['str', /^'(?:[^']|'')*'/],
41 ['ident', /^"[^"]*"/],
42 ['num', /^\d+(?:\.\d+)?\b/],
43 ['param', /^:[A-Za-z_]\w*/],
44 ['ident', /^[A-Za-z_][\w$]*/],
45 ['ws', /^\s+/],
46 ['op', /^(?:<>|!=|>=|<=|\|\||::|[=<>+\-*/%])/],
47]
48
49export function tokenize(sql: string): Token[] {
50 const tokens: Token[] = []
51 let rest = sql
52 while (rest.length > 0) {
53 let matched = false
54 for (const [kind, re] of RULES) {
55 const m = re.exec(rest)
56 if (!m) continue
57 const text = m[0]
58 if (kind === 'template') {
59 tokens.push({ kind, text, templateKind: m[1], templateName: m[2] })
60 } else if (kind === 'ident' && /^[A-Za-z_]/.test(text)) {
61 const after = rest.slice(text.length).trimStart()
62 const lower = text.toLowerCase()
63 tokens.push({ kind: KEYWORDS.has(lower) ? 'kw' : after.startsWith('(') ? 'fn' : 'ident', text })
64 } else {
65 tokens.push({ kind, text })
66 }
67 rest = rest.slice(text.length)
68 matched = true
69 break
70 }
71 if (!matched) {
72 tokens.push({ kind: 'punct', text: rest[0] })
73 rest = rest.slice(1)
74 }
75 }
76 return tokens
77}
78
79function trimEnd(line: Token[]): Token[] {
80 while (line.length > 0 && line[line.length - 1].kind === 'ws') line.pop()
81 return line
82}
83
84// A multi-line query keeps the author's layout; a one-line query gets one
85// clause per line, one select item per line, and AND/OR on their own lines.
86export function formatLines(sql: string): Token[][] {
87 const tokens = tokenize(sql.trim())
88 if (sql.trim().includes('\n')) {
89 const lines: Token[][] = [[]]
90 for (const t of tokens) {
91 if (t.kind === 'ws' && t.text.includes('\n')) {
92 const parts = t.text.split('\n')
93 for (let i = 1; i < parts.length; i += 1) lines.push([])
94 const indent = parts[parts.length - 1]
95 if (indent) lines[lines.length - 1].push({ kind: 'ws', text: indent })
96 } else {
97 lines[lines.length - 1].push(t)
98 }
99 }
100 return lines.map(trimEnd)
101 }
102
103 // Feature #1067: a subquery or CTE body - a "(" that opens a
104 // SELECT or WITH - is formatted like the top level, indented under its
105 // parenthesis; any other parenthesis (a call, an IN list) stays inline.
106 const lines: Token[][] = []
107 let line: Token[] = []
108 type Frame = { sub: boolean; indent: number; clause: string }
109 const frames: Frame[] = [{ sub: true, indent: 0, clause: '' }]
110 const top = () => frames[frames.length - 1]
111 let prevWord = ''
112 const newline = (indent: number) => {
113 if (trimEnd(line).length > 0) lines.push(line)
114 line = indent > 0 ? [{ kind: 'ws', text: ' '.repeat(indent) }] : []
115 }
116 const atLineStart = () => line.every(t => t.kind === 'ws')
117 const lineIndent = () => (line[0]?.kind === 'ws' ? line[0].text.length : 0)
118 const nextWord = (from: number) => {
119 for (let k = from; k < tokens.length; k += 1) if (tokens[k].kind !== 'ws') return tokens[k].text.toLowerCase()
120 return ''
121 }
122
123 tokens.forEach((t, i) => {
124 if (t.kind === 'ws') {
125 if (!atLineStart()) line.push({ kind: 'ws', text: ' ' })
126 return
127 }
128 if (t.text === '(') {
129 const opensQuery = ['select', 'with'].includes(nextWord(i + 1))
130 line.push(t)
131 if (opensQuery) {
132 const indent = lineIndent() + 4
133 frames.push({ sub: true, indent, clause: '' })
134 newline(indent)
135 } else {
136 frames.push({ sub: false, indent: top().indent, clause: top().clause })
137 }
138 return
139 }
140 if (t.text === ')') {
141 const frame = frames.length > 1 ? frames.pop()! : top()
142 if (frame.sub) newline(Math.max(frame.indent - 4, 0))
143 line.push(t)
144 return
145 }
146 const frame = top()
147 const word = t.kind === 'kw' || t.kind === 'ident' || t.kind === 'fn' ? t.text.toLowerCase() : ''
148 if (frame.sub && word) {
149 const startsJoin = word === 'join' && !JOIN_PREFIXES.has(prevWord)
150 if (CLAUSE_STARTS.has(word) || TWO_WORD_CLAUSES.has(word) || JOIN_PREFIXES.has(word) || startsJoin) {
151 if (!(JOIN_PREFIXES.has(prevWord) && (word === 'join' || word === 'outer')) && !(TWO_WORD_CLAUSES.has(prevWord) && word === 'by')) {
152 if (!atLineStart()) newline(frame.indent)
153 frame.clause = word
154 }
155 } else if ((word === 'and' || word === 'or') && (frame.clause === 'where' || frame.clause === 'having')) {
156 newline(frame.indent + 2)
157 }
158 }
159 line.push(t)
160 if (word) prevWord = word
161 if (frame.sub && word === 'select') newline(frame.indent + 2)
162 if (frame.sub && t.text === ',' && frame.clause === 'select') newline(frame.indent + 2)
163 })
164 if (trimEnd(line).length > 0) lines.push(line)
165 return lines
166}
167
168export function lineText(line: Token[]): string {
169 return line.map(t => t.text).join('')
170}
171
172type SelectItem = { alias: string; expr: string; templates: Token[] }
173
174// The top-level SELECT list: each item's alias (AS name, or a bare column)
175// and its expression text, with the KB templates it holds.
176function selectItems(sql: string): SelectItem[] {
177 const tokens = tokenize(sql)
178 const items: SelectItem[] = []
179 let depth = 0
180 let inSelect = false
181 let current: Token[] = []
182 const flush = () => {
183 const parts = current.filter(t => t.kind !== 'ws')
184 if (parts.length > 0) {
185 const asAt = parts.length >= 3 && parts[parts.length - 2].text.toLowerCase() === 'as' ? parts.length - 2 : -1
186 const aliasTok = asAt >= 0 ? parts[parts.length - 1] : parts.length === 1 ? parts[0] : undefined
187 const exprTokens = asAt >= 0 ? current.slice(0, current.lastIndexOf(parts[asAt])) : current
188 if (aliasTok) {
189 items.push({
190 alias: aliasTok.text.replace(/"/g, '').toLowerCase(),
191 expr: exprTokens.map(t => t.text).join('').trim(),
192 templates: parts.filter(t => t.kind === 'template'),
193 })
194 }
195 }
196 current = []
197 }
198 for (const t of tokens) {
199 if (t.text === '(') depth += 1
200 if (t.text === ')') depth -= 1
201 const word = t.kind === 'kw' ? t.text.toLowerCase() : ''
202 if (depth === 0 && word === 'select' && !inSelect && items.length === 0) {
203 inSelect = true
204 continue
205 }
206 if (!inSelect) continue
207 if (depth === 0 && word === 'from') {
208 flush()
209 break
210 }
211 if (depth === 0 && word === 'distinct' && current.every(c => c.kind === 'ws')) continue
212 if (depth === 0 && t.text === ',') flush()
213 else current.push(t)
214 }
215 return items
216}
217
218export type Expansion = { kind: string; name: string; alias: string; expr: string }
219
220// What each KB template of the base query compiled to, matched to the runtime
221// SQL by select alias: {{ Metric('cpi') }} AS cpi <-> (...) AS cpi.
222export function templateExpansions(baseSql: string, runtimeSql: string): Expansion[] {
223 const runtime = new Map(selectItems(runtimeSql).map(i => [i.alias, i.expr]))
224 const out: Expansion[] = []
225 for (const item of selectItems(baseSql)) {
226 const expr = runtime.get(item.alias)
227 if (!expr) continue
228 for (const t of item.templates) {
229 if (t.templateKind && t.templateName) {
230 out.push({ kind: t.templateKind, name: t.templateName, alias: item.alias, expr })
231 }
232 }
233 }
234 return out
235}
236
237// Feature #1067: SQL as the sidebars show it - re-flowed by the
238// formatter (one clause, one select item per line, CTEs indented) unless it
239// holds a line comment, whose end the layout must keep.
240export function prettySql(sql: string): string {
241 const text = sql.trim()
242 if (/--/.test(text.replace(/'(?:[^']|'')*'/g, "''"))) return text
243 return formatLines(text.replace(/\s+/g, ' ')).map(lineText).join('\n')
244}
245
246// Text for native Code blocks: whole lines, each block under `max` characters.
247export function codeChunks(text: string, max = 9500): Array<{ source: string; startLine: number }> {
248 const out: Array<{ source: string; startLine: number }> = []
249 let lines: string[] = []
250 let size = 0
251 let start = 1
252 text.split('\n').forEach((line, i) => {
253 const piece = line.length > max ? line.slice(0, max - 1) + '…' : line
254 if (size + piece.length + 1 > max && lines.length) {
255 out.push({ source: lines.join('\n'), startLine: start })
256 lines = []
257 size = 0
258 start = i + 1
259 }
260 lines.push(piece)
261 size += piece.length + 1
262 })
263 if (lines.length) out.push({ source: lines.join('\n'), startLine: start })
264 return out
265}
266hooks/query-view/upstream.ts 431 lines1// Feature #1067: the full lineage of a query result, from the
2// warehouse down to the result columns. Pure: parsing of what the graphit CLI
3// returns and the layer graph the card draws; the reads themselves run in
4// register.tsx.
5
6import type { Expansion } from './sql'
7import type { Upstream } from './state'
8
9// A fact the sidebar shows for a node; `code` values are drawn as SQL.
10export type Fact = { label: string; value: string; code?: boolean }
11export type LayerNode = { id: string; title: string; subtitle?: string; color: string; muted?: boolean; facts?: Fact[] }
12export type LayerEdge = { from: string; to: string; color: string; dashed?: boolean }
13export type Layers = { layers: Array<{ label: string; nodes: LayerNode[] }>; edges: LayerEdge[] }
14
15const KEYWORDS = new Set(
16 (
17 'SELECT FROM WHERE AND OR NOT CASE WHEN THEN ELSE END AS CAST DATE TIMESTAMP TIMESTAMP_NTZ INT INTEGER NUMBER ' +
18 'NUMERIC DECIMAL FLOAT DOUBLE VARCHAR STRING TEXT BOOLEAN TRUE FALSE NULL IS IN LIKE ILIKE BETWEEN DISTINCT ' +
19 'DAY WEEK MONTH QUARTER YEAR HOUR MINUTE SECOND INTERVAL ON JOIN LEFT RIGHT INNER OUTER FULL GROUP BY ORDER ' +
20 'HAVING LIMIT OVER PARTITION ROWS UNBOUNDED PRECEDING FOLLOWING CURRENT ROW WITH ASC DESC'
21 ).split(' '),
22)
23
24// Blank quoted text so an identifier search never reads inside a literal.
25const unquote = (sql: string) => sql.replace(/'(?:[^']|'')*'/g, "''")
26// Feature #1092: blank literals and drop comments in one left-to-right pass, so
27// neither fools the other - an apostrophe in `-- it's read from Firestore`
28// opened a fake literal that swallowed the next real FROM, and a `--` inside a
29// literal must stay text. A comment is prose, never a table.
30const uncomment = (sql: string) =>
31 sql.replace(/'(?:[^']|'')*'|--[^\n]*|\/\*[\s\S]*?\*\//g, m => (m.startsWith("'") ? "''" : ' '))
32// One name part: bare, "double quoted" (Snowflake) or `backticked` (BigQuery).
33const NAME_PART = '(?:"[^"]+"|`[^`]+`|[A-Za-z_][\\w$]*)'
34const FROM_TARGET = new RegExp(`\\b(?:FROM|JOIN)\\s+(${NAME_PART}(?:\\s*\\.\\s*${NAME_PART})*)`, 'gi')
35
36// FROM targets that are not tables: inline rows and table functions.
37const NOT_TABLES = new Set(['VALUES', 'LATERAL', 'TABLE', 'UNNEST', 'FLATTEN', 'GENERATOR', 'SELECT'])
38// A FROM inside EXTRACT(YEAR FROM col) or TRIM(x FROM col) names a column.
39const IN_FUNCTION = /\b(?:EXTRACT|TRIM|SUBSTRING|POSITION|OVERLAY)\s*\([^()]*$/i
40
41// Column identifiers an expression reads: bare names, not functions, keywords
42// or numbers; a qualified `o.AMOUNT` counts as AMOUNT.
43export function columnsOf(expr: string): string[] {
44 const out: string[] = []
45 for (const m of unquote(expr).matchAll(/(?:\b[A-Za-z_]\w*\.)?\b([A-Za-z_]\w*)\b(?!\s*\()/g)) {
46 const name = m[1].toUpperCase()
47 if (!KEYWORDS.has(name) && !out.includes(name)) out.push(name)
48 }
49 return out
50}
51
52// The warehouse tables a data source's SQL reads: FROM / JOIN targets that are
53// not its own CTE names, inline VALUES, table functions or comment text.
54export function warehouseTables(sql: string): string[] {
55 const text = uncomment(sql)
56 const ctes = new Set([...text.matchAll(/\b([A-Za-z_]\w*)\s+AS\s*\(/gi)].map(m => m[1].toUpperCase()))
57 const out: string[] = []
58 for (const m of text.matchAll(FROM_TARGET)) {
59 const name = m[1].replace(/\s*\.\s*/g, '.').replace(/["`]/g, '')
60 const upper = name.toUpperCase()
61 if (ctes.has(upper) || NOT_TABLES.has(upper) || IN_FUNCTION.test(text.slice(Math.max(0, (m.index ?? 0) - 80), m.index))) continue
62 if (!out.includes(name)) out.push(name)
63 }
64 return out
65}
66
67// snowflake -> Snowflake; the warehouse names the tables layer.
68export function warehouseLabel(kind: string): string {
69 return kind === 'snowflake' ? 'Snowflake' : kind === 'bigquery' ? 'BigQuery' : kind === 'file_upload' ? 'File upload' : kind.charAt(0).toUpperCase() + kind.slice(1)
70}
71
72// 2026-10-04T05:00:10Z -> "4 Oct 08:00" in Israel time.
73export function israelTime(iso?: string): string | undefined {
74 if (!iso) return undefined
75 const d = new Date(iso.includes('T') || iso.endsWith('Z') ? iso : iso.replace(' ', 'T'))
76 if (Number.isNaN(d.getTime())) return undefined
77 try {
78 // Built from parts: runtimes disagree on the joiner ("4 Oct, 08:00", "4 Oct at 08:00").
79 const parts = new Intl.DateTimeFormat('en-GB', { timeZone: 'Asia/Jerusalem', day: 'numeric', month: 'short', hour: '2-digit', minute: '2-digit', hour12: false }).formatToParts(d)
80 const part = (type: string) => parts.find(p => p.type === type)?.value ?? ''
81 return `${part('day')} ${part('month')} ${part('hour')}:${part('minute')}`
82 } catch {
83 return d.toISOString().slice(0, 16).replace('T', ' ')
84 }
85}
86
87// The first JSON value in a CLI's output, or null.
88export function jsonOf(text: string): unknown {
89 const at = text.search(/[[{]/)
90 if (at < 0) return null
91 try {
92 return JSON.parse(text.slice(at))
93 } catch {
94 return null
95 }
96}
97
98// The CLI's own failure text: the last `{"error": ...}` line on stderr, else
99// its last line, kept short for a one-line status.
100export function errorOf(stderr: string): string {
101 const lines = stderr.split('\n').map(l => l.trim()).filter(Boolean)
102 for (const line of [...lines].reverse()) {
103 const parsed = line.startsWith('{') ? (jsonOf(line) as { error?: unknown } | null) : null
104 if (typeof parsed?.error === 'string') return parsed.error.slice(0, 120)
105 }
106 return (lines[lines.length - 1] ?? '').slice(0, 120)
107}
108
109type DsRow = { id?: string; name?: string; connector_type?: string; source_sql?: string; row_count?: number; last_refreshed?: string; domain?: string }
110type Model = {
111 name?: string
112 group?: string
113 primary_entity?: string
114 dimensions?: Array<{ name?: string; expr?: string | null }>
115 measures?: Array<{ name?: string; agg?: string; expr?: string | null }>
116}
117type MetricEntity = {
118 name?: string
119 type?: string
120 group?: string
121 type_params?: {
122 measure?: { name?: string } | null
123 numerator?: { name?: string } | null
124 denominator?: { name?: string } | null
125 metrics?: Array<{ name?: string }> | null
126 }
127}
128
129// Assemble the upstream from the CLI's answers. Every input is optional: a
130// read that failed leaves its layer out rather than failing the lineage.
131export function assembleUpstream(input: {
132 sourceName?: string
133 dsList: unknown
134 history: unknown
135 models: unknown
136 metrics: unknown[]
137 refs: Array<{ kind: string; name: string }>
138}): Upstream {
139 const up: Upstream = { status: 'ok' }
140 const rows = ((input.dsList as { data_sources?: DsRow[] } | null)?.data_sources ?? []) as DsRow[]
141 const ds = input.sourceName ? rows.find(r => (r.name ?? '').toLowerCase() === input.sourceName!.toLowerCase()) : undefined
142 if (ds) {
143 const kind = ds.connector_type ?? 'warehouse'
144 const file = /Uploaded from:\s*([^,\n]+)/.exec(ds.source_sql ?? '')?.[1]?.trim()
145 up.warehouse = { kind, file }
146 if (kind !== 'file_upload' && ds.source_sql) up.tables = warehouseTables(ds.source_sql)
147 const run = Array.isArray(input.history) ? (input.history[0] as { started_at?: string; status?: string; type?: string; rows?: number } | undefined) : undefined
148 up.ds = {
149 name: ds.name ?? input.sourceName ?? '',
150 rows: run?.rows ?? ds.row_count,
151 refreshedAt: israelTime(run?.started_at ?? ds.last_refreshed),
152 refreshType: run?.type,
153 refreshStatus: run?.status,
154 domain: ds.domain,
155 sql: kind !== 'file_upload' ? ds.source_sql : undefined,
156 }
157 }
158
159 const metricEntities = input.metrics
160 .map(m => (m as { entity?: MetricEntity } | null)?.entity)
161 .filter((m): m is MetricEntity => !!m && !!m.name)
162 up.metrics = metricEntities.map(m => {
163 const p = m.type_params ?? {}
164 const inputs = [p.measure?.name, p.numerator?.name, p.denominator?.name, ...(p.metrics ?? []).map(x => x.name)].filter(
165 (x): x is string => !!x,
166 )
167 return { name: m.name!, type: m.type ?? 'metric', group: m.group, inputs }
168 })
169
170 // The model: the one holding the referenced dimensions and metric inputs.
171 const models = ((input.models as { items?: Model[] } | null)?.items ?? (Array.isArray(input.models) ? input.models : [])) as Model[]
172 const dimNames = input.refs.filter(r => r.kind === 'Dimension').map(r => r.name.split('__').pop() as string)
173 const inputNames = up.metrics.flatMap(m => m.inputs)
174 const score = (m: Model) =>
175 dimNames.filter(d => (m.dimensions ?? []).some(x => x.name === d)).length +
176 inputNames.filter(n => (m.measures ?? []).some(x => x.name === n)).length +
177 (input.sourceName && (m.name ?? '').toLowerCase() === input.sourceName.toLowerCase() ? 1 : 0)
178 const model = models.reduce<Model | undefined>((best, m) => (score(m) > 0 && (!best || score(m) > score(best)) ? m : best), undefined)
179 if (model) {
180 up.model = { name: model.name ?? '', group: model.group }
181 up.measures = (model.measures ?? [])
182 .filter(x => x.name && inputNames.includes(x.name))
183 .map(x => ({ name: x.name!, agg: (x.agg ?? '').toUpperCase(), expr: x.expr ?? x.name!, columns: columnsOf(x.expr ?? x.name!) }))
184 up.dims = (model.dimensions ?? [])
185 .filter(x => x.name && dimNames.includes(x.name))
186 .map(x => ({ name: x.name!, expr: x.expr ?? x.name!, columns: columnsOf(x.expr ?? x.name!) }))
187 }
188 return up
189}
190
191// Drop a set of nodes and join what fed them straight to what they fed, so
192// the chain stays connected.
193function bypass(spec: Layers, drop: Set<string>): Layers {
194 const into = spec.edges.filter(e => drop.has(e.to) && !drop.has(e.from))
195 const out = spec.edges.filter(e => drop.has(e.from) && !drop.has(e.to))
196 const kept = spec.edges.filter(e => !drop.has(e.from) && !drop.has(e.to))
197 const joined = into.flatMap(a => out.filter(b => b.from === a.to).map(b => ({ ...b, from: a.from })))
198 const seen = new Set<string>()
199 const edges = [...kept, ...joined].filter(e => {
200 const k = `${e.from}>${e.to}`
201 return seen.has(k) ? false : (seen.add(k), true)
202 })
203 const layers = spec.layers.map(l => ({ ...l, nodes: l.nodes.filter(n => !drop.has(n.id)) })).filter(l => l.nodes.length > 0)
204 return { layers, edges }
205}
206
207// The card's overview of the chain: tables, source, model, KB, rules, result.
208// Physical columns and measures are the model's detail - drawn on the card
209// they made eight columns too narrow to read a name in. The explorer keeps
210// every layer.
211const DETAIL_LAYERS = new Set(['COLUMNS', 'MEASURES'])
212export function overviewLayers(spec: Layers): Layers {
213 const drop = new Set(spec.layers.filter(l => DETAIL_LAYERS.has(l.label)).flatMap(l => l.nodes.map(n => n.id)))
214 return drop.size ? bypass(spec, drop) : spec
215}
216
217// One node's own chain: everything it comes from and everything it feeds.
218export function chainOf(spec: Layers, id: string): Layers {
219 const walk = (upward: boolean) => {
220 const seen = new Set([id])
221 const queue = [id]
222 while (queue.length) {
223 const at = queue.shift() as string
224 for (const e of spec.edges) {
225 const next = upward ? (e.to === at ? e.from : undefined) : e.from === at ? e.to : undefined
226 if (next && !seen.has(next)) {
227 seen.add(next)
228 queue.push(next)
229 }
230 }
231 }
232 return seen
233 }
234 const up = walk(true)
235 const down = walk(false)
236 const keep = new Set([...up, ...down])
237 return {
238 layers: spec.layers.map(l => ({ ...l, nodes: l.nodes.filter(n => keep.has(n.id)) })).filter(l => l.nodes.length > 0),
239 edges: spec.edges.filter(e => keep.has(e.from) && keep.has(e.to) && (up.has(e.to) || down.has(e.from))),
240 }
241}
242
243const C = {
244 ink: '#222224',
245 wh: '#2F6FDB',
246 ds: '#4DB6AC',
247 model: '#7A5AF8',
248 column: '#6E6E73',
249 measure: '#2A9D8F',
250 metric: '#2A9D8F',
251 dim: '#5B8DEF',
252 red: '#dc2626',
253 gray: '#AEAEB2',
254}
255
256// The layers top to bottom; a layer with nothing to show is left out.
257export function lineageLayers(input: {
258 up?: Upstream
259 sourceName?: string
260 rowCount: number
261 columns: string[]
262 hidden: Set<string>
263 refs: Array<{ kind: string; name: string }>
264 expansions: Expansion[]
265 rules: Array<{ name: string; clauses: string[]; masks: string[]; color: string; why?: string }>
266}): Layers {
267 const up = input.up?.status === 'ok' ? input.up : undefined
268 const layers: Layers['layers'] = []
269 const edges: LayerEdge[] = []
270 const add = (label: string, nodes: LayerNode[]) => nodes.length && layers.push({ label, nodes })
271 const link = (from: string, to: string, color: string, dashed?: boolean) => edges.push({ from, to, color, dashed })
272
273 // The warehouse tables (or the uploaded file) the source reads. The
274 // warehouse itself is the layer's name, not a node of its own: one box
275 // saying "Snowflake" told nothing the tables do not.
276 const warehouse = up?.warehouse ? warehouseLabel(up.warehouse.kind) : undefined
277 if (up?.warehouse?.kind === 'file_upload') {
278 add('FILE', [{ id: 'file', title: up.warehouse.file ?? 'Uploaded file', subtitle: 'file upload', color: C.wh, facts: [{ label: 'Kind', value: 'File upload' }, ...(up.warehouse.file ? [{ label: 'File', value: up.warehouse.file }] : [])] }])
279 } else if (warehouse) {
280 add(
281 `${warehouse.toUpperCase()} TABLES`,
282 (up?.tables ?? []).map(t => {
283 const parts = t.split('.')
284 return {
285 id: `tb:${t}`,
286 title: parts[parts.length - 1],
287 subtitle: parts.length > 1 ? parts.slice(0, -1).join('.') : 'table',
288 color: C.wh,
289 facts: [{ label: 'Table', value: t }, { label: 'Warehouse', value: warehouse }],
290 }
291 }),
292 )
293 }
294
295 // The cached data source.
296 const dsName = up?.ds?.name ?? input.sourceName
297 if (dsName) {
298 // Rows first: a clipped subtitle still says how big the source is.
299 const bits = [up?.ds?.rows != null ? `${up.ds.rows.toLocaleString('en-US')} rows` : undefined, up?.ds?.refreshedAt].filter(Boolean)
300 add('DATA SOURCE', [
301 {
302 id: 'ds',
303 title: dsName,
304 subtitle: bits.join(' · ') || 'cached source',
305 color: C.ds,
306 facts: [
307 ...(up?.ds?.rows != null ? [{ label: 'Rows', value: up.ds.rows.toLocaleString('en-US') }] : []),
308 ...(up?.ds?.refreshedAt ? [{ label: 'Last refresh', value: [up.ds.refreshType, up.ds.refreshedAt, up.ds.refreshStatus].filter(Boolean).join(' · ') }] : []),
309 ...(up?.ds?.domain ? [{ label: 'Access domain', value: up.ds.domain }] : []),
310 ...(up?.ds?.sql ? [{ label: 'Source SQL', value: up.ds.sql, code: true }] : []),
311 ],
312 },
313 ])
314 if (up?.warehouse?.kind === 'file_upload') link('file', 'ds', C.wh)
315 else for (const t of up?.tables ?? []) link(`tb:${t}`, 'ds', C.wh)
316 }
317
318 // Semantic model, its physical columns, its measures.
319 const ruleColumns = input.rules.flatMap(r => r.clauses.flatMap(columnsOf))
320 if (up?.model) {
321 add('SEMANTIC MODEL', [
322 {
323 id: 'model',
324 title: up.model.name,
325 subtitle: up.model.group ? `group ${up.model.group}` : 'model',
326 color: C.model,
327 facts: [
328 ...(up.model.group ? [{ label: 'Group', value: up.model.group }] : []),
329 { label: 'Measures used', value: (up.measures ?? []).map(m => m.name).join(', ') || 'none' },
330 { label: 'Dimensions used', value: (up.dims ?? []).map(d => d.name).join(', ') || 'none' },
331 ],
332 },
333 ])
334 if (dsName) link('ds', 'model', C.model)
335 const physical = [...new Set([...(up.measures ?? []).flatMap(m => m.columns), ...(up.dims ?? []).flatMap(d => d.columns), ...ruleColumns])]
336 add('COLUMNS', physical.map(c => ({ id: `col:${c}`, title: c, color: C.column, facts: [{ label: 'Physical column', value: c }] })))
337 for (const c of physical) link('model', `col:${c}`, C.gray)
338 add('MEASURES', (up.measures ?? []).map(m => ({ id: `ms:${m.name}`, title: m.name, subtitle: `${m.agg}(${m.expr})`, color: C.measure, facts: [{ label: 'Aggregation', value: m.agg }, { label: 'Expression', value: `${m.agg}(${m.expr})`, code: true }] })))
339 for (const m of up.measures ?? []) {
340 for (const c of m.columns) link(`col:${c}`, `ms:${m.name}`, C.measure)
341 // COUNT(1) reads no column: it comes from the model itself.
342 if (m.columns.length === 0) link('model', `ms:${m.name}`, C.measure)
343 }
344 }
345
346 // Metrics and dimensions the query references.
347 const refNodes: LayerNode[] = input.refs.map(r => {
348 const short = r.name.split('__').pop() as string
349 const metric = up?.metrics?.find(m => m.name === r.name)
350 const dim = up?.dims?.find(d => d.name === short)
351 const compiled = input.expansions.find(x => x.kind === r.kind && x.name === r.name)?.expr
352 return {
353 id: `ref:${r.kind}:${r.name}`,
354 title: short,
355 subtitle: r.kind === 'Metric' ? [metric?.type ?? 'metric', metric?.group].filter(Boolean).join(' · ') : 'dimension',
356 color: r.kind === 'Metric' ? C.metric : C.dim,
357 facts: [
358 { label: 'Reference', value: `{{ ${r.kind}('${r.name}') }}`, code: true },
359 ...(metric ? [{ label: 'Type', value: metric.type }, ...(metric.group ? [{ label: 'Group', value: metric.group }] : []), ...(metric.inputs.length ? [{ label: 'Inputs', value: metric.inputs.join(', ') }] : [])] : []),
360 ...(dim ? [{ label: 'Expression', value: dim.expr, code: true }] : []),
361 ...(compiled ? [{ label: 'Compiles to', value: compiled, code: true }] : []),
362 ],
363 }
364 })
365 add('KB ASSETS', refNodes)
366 for (const r of input.refs) {
367 const id = `ref:${r.kind}:${r.name}`
368 const short = r.name.split('__').pop() as string
369 if (r.kind === 'Metric') {
370 const inputs = up?.metrics?.find(m => m.name === r.name)?.inputs ?? []
371 const fromMeasures = inputs.filter(i => up?.measures?.some(m => m.name === i))
372 for (const i of fromMeasures) link(`ms:${i}`, id, C.metric)
373 if (fromMeasures.length === 0 && up?.model) link('model', id, C.metric)
374 if (!up?.model && dsName) link('ds', id, C.metric)
375 } else {
376 const dim = up?.dims?.find(d => d.name === short)
377 if (dim) for (const c of dim.columns) link(`col:${c}`, id, C.dim)
378 else if (up?.model) link('model', id, C.dim)
379 else if (dsName) link('ds', id, C.dim)
380 }
381 }
382
383 // Governance: a filter reads columns and narrows the rows; a mask hides one.
384 add(
385 'GOVERNANCE',
386 input.rules.map(r => ({
387 id: `rule:${r.name}`,
388 title: r.name,
389 subtitle: r.masks.length ? 'mask' : 'row filter',
390 color: r.color,
391 facts: [
392 ...(r.why ? [{ label: 'Why', value: r.why }] : []),
393 ...r.clauses.map((c, i) => ({ label: i === 0 ? 'Adds filter' : '', value: c, code: true })),
394 ...(r.masks.length ? [{ label: 'Masks', value: r.masks.join(', ') }] : []),
395 ],
396 })),
397 )
398 for (const r of input.rules) {
399 const cols = r.clauses.flatMap(columnsOf).filter(c => layers.some(l => l.nodes.some(n => n.id === `col:${c}`)))
400 if (cols.length) for (const c of cols) link(`col:${c}`, `rule:${r.name}`, r.color, true)
401 else if (dsName) link('ds', `rule:${r.name}`, r.color, true)
402 if (r.clauses.length) link(`rule:${r.name}`, 'rows', r.color, true)
403 for (const m of r.masks) link(`rule:${r.name}`, `out:${m}`, C.red, true)
404 }
405
406 // The result: its rows and columns.
407 add('RESULT', [
408 { id: 'rows', title: `${input.rowCount.toLocaleString('en-US')} rows`, color: C.ds, facts: [{ label: 'Rows returned', value: input.rowCount.toLocaleString('en-US') }] },
409 ...input.columns.map(c => ({
410 id: `out:${c}`,
411 title: c,
412 subtitle: input.hidden.has(c) ? 'masked' : undefined,
413 color: input.hidden.has(c) ? C.red : C.ink,
414 muted: input.hidden.has(c),
415 facts: [{ label: 'Result column', value: c }, ...(input.hidden.has(c) ? [{ label: 'Policy', value: 'Returned as NULL by a masking rule' }] : [])],
416 })),
417 ])
418 // The rows come from the source; a rule that filters them says so above.
419 if (dsName) link('ds', 'rows', C.ds)
420 for (const c of input.columns) {
421 const ref = input.refs.find(r => {
422 const x = input.expansions.find(e => e.kind === r.kind && e.name === r.name)
423 return c === x?.alias || c === r.name || c === r.name.split('__').pop()
424 })
425 if (ref) link(`ref:${ref.kind}:${ref.name}`, `out:${c}`, ref.kind === 'Metric' ? C.metric : C.dim)
426 else if (layers.some(l => l.nodes.some(n => n.id === `col:${c.toUpperCase()}`))) link(`col:${c.toUpperCase()}`, `out:${c}`, C.gray)
427 else if (dsName && !input.hidden.has(c)) link('ds', `out:${c}`, C.gray)
428 }
429 return { layers, edges }
430}
431