Dosi semantic layer in Claude Code: connect a warehouse, generate an Apache Ossie model, ask questions through metrics, see lineage, and (when you need it)…

English | 简体中文
Ask data questions in Claude Code (and other coding agents) and get answers computed from governed metrics. Dosi is a local semantic layer built on Apache Ossie (formerly OSI). From inside the agent it can:
Everything runs on your machine. There is no setup wizard. Install the plugin, ask a question, and the plugin introduces each feature when you need it.
Preview. Importing dbt / Cube connection settings needs
dosi migrate conf, which ships in the next dosi release. Until then, cloud warehouses are connected through a guided manual step. Local files (DuckDB, Parquet, CSV) work today.
Type at the Claude Code prompt:
/plugin marketplace add Datus-ai/dosi-plugins
/plugin install dosi@dosi-plugins
Then run /reload-plugins, or start a new session. On its first start the plugin downloads the dosi binary in the background (about 10 seconds), so there is nothing else to install.
On Claude Code 2.1.275 or later, one line does both steps: /plugin install dosi --marketplace Datus-ai/dosi-plugins. From a shell, run claude plugin install dosi --marketplace Datus-ai/dosi-plugins.
Say this to Codex, DeepSeek Harness, Gemini CLI, Grok, Cursor, or any other agent:
Install Dosi by following https://raw.githubusercontent.com/Datus-ai/dosi-plugins/main/agent-install.md
The agent installs dosi and the skills in the way that agent supports.
Use the sample dataset (200k orders, with customers and products) in an empty folder:
mkdir dosi-try && cd dosi-try
curl -fsSLO https://dosi.datus.ai/orders-200k.duckdb
claude
Then type each prompt below in order. Every step was run end to end, and the times are measured. At any point, /dosi shows where you are and what to try next.
Connect to my data
The plugin finds orders-200k.duckdb and connects with no questions. Expected: a one-line confirmation that the local connection (duckdb, orders-200k.duckdb) is up.
With your own data, this is where it detects your dbt project or Cube .env and asks which connection to use (see Your own data).
Build a semantic model for this data
A subagent reads the schema, writes dosi/model.yaml (Apache Ossie) and validates it. Expected: 3 datasets, 2 relationships and about 9 metrics. You then get at most three questions about business meaning, for example "should revenue include cancelled orders?". Each comes with a recommended answer; pick one or say "use the recommendations".
What is revenue by region and month?
Expected: a table, a one-line footer with the source and row count, and the SQL dosi compiled. Ask follow-ups freely: "only north", "by week", "month over month?".
How is revenue calculated?
Expected: a lineage tree in the chat (table → dataset → metric), plus a full interactive lineage page written locally. It opens in your browser when one is available; otherwise you get the file path.
List the 10 largest orders with customer region and product category
Expected: row-level results through dosi select, with joins chosen for you. Then try another entity question:
Which customers order the most?
After a couple of entity questions, the plugin offers an ontology once: your questions involve several business entities, and asking by business concept would be more accurate.
Answer "tell me more". A subagent drafts dosi/ontology.yaml with the concepts Customer, Order and Product and their links, validates it, and asks only if something is genuinely ambiguous. If you answer "later", it asks again only after 10 more questions.
In each product category, which region's customers buy the most?
Expected: the answer is computed through concept paths such as Order.placed_by.region and Order.purchases.category, which you can reuse in later questions.
In Claude Code the plugin also draws its own interface. None of it changes what Claude reads, and every step above works the same without it.
dosi · duckdb:local · 3 ds · 8 metrics · ontology 3. It updates after every dosi command and every edit to dosi/*.yaml./dosi: the connection, the model file and whether it validates, counts of datasets, metrics and dimensions, the ontology, and the next step. /dosi metrics lists every metric with its description./dosi lineage [metric]: opens a lineage pane. In the terminal it draws a tree, either what a metric is computed from or what depends on a table. In Claude Code Desktop it also draws the full graph with the selected path highlighted. Press h to write the HTML page as well.dosi … --format json result shows as a table, with the source and row count underneath and the SQL one click away. A failed command shows as the error, its cause and what to try next.Start Claude Code in your project folder and just ask a data question. The plugin behaves the same way as in the tutorial, with one difference in step 1:
| What the folder has | What step 1 does |
|---|---|
a dbt project (dbt_project.yml, ~/.dbt/profiles.yml) | Converts your profiles with dosi migrate conf and asks which target to use. The project's current target is recommended |
a Cube .env | Converts the CUBEJS_DB_* settings the same way |
.duckdb / .sqlite files | Connects directly, as in the tutorial |
| nothing | Asks where your data lives, then writes a connection whose secrets are ${VAR} references |
Claude never sees your passwords. When a variable is missing, you set it yourself with ! export NAME=.... Browser-SSO logins (authenticator: externalbrowser) are not supported yet; use key-pair auth or a password variable instead.
| Part | What it does |
|---|---|
skills/dosi-connect | Connects to a warehouse or local file. Converts dbt / Cube settings with dosi migrate conf. Secrets never enter the chat |
skills/dosi-model | Generates and edits dosi/model.yaml (Apache Ossie) |
skills/dosi-query | Answers with metrics (query), records (select) and change attribution (attribute) |
skills/dosi-view | Shows metric lineage and the ontology graph, in the chat and as a local HTML page |
skills/dosi-ontology | Builds dosi/ontology.yaml and answers questions by business concept |
agents/dosi-modeler, agents/dosi-ontologist | Subagents that read schemas, so your main conversation stays clean |
hooks/ | Installs the pinned binary, validates every model edit, blocks reads of connection configs, and decides which feature to suggest next. register.tsx is the Claude Code interface: status line, /dosi, the band, the lineage pane and result tables |
bin/dosi | Runs the dosi release pinned in DOSI_VERSION. Plugin fixes ship on every commit; the dosi binary changes only when that file does |
dosi/model.yaml # Apache Ossie semantic model: commit it
dosi/ontology.yaml # only once you build an ontology: commit it
dosi-connections.yaml # generated connections; may hold secrets, so it is added to .gitignore
| Symptom | Fix |
|---|---|
Plugin "dosi" not found in any marketplace | Your Claude Code is older than 2.1.275. Use the two-line install above |
dosi_installing | The first binary download is still running. Wait a few seconds; Claude retries on its own |
install_failed behind a restricted network | Set DOSI_SOURCE=oss (Aliyun mirror), or DOSI_SOURCE=cloudflare, then start a new session |
| You want the feature suggestions to start over | dosi-progress status shows the state. Delete the project's file under ~/.claude/plugins/data/<plugin>/progress/ |
To uninstall, run /plugin uninstall dosi@dosi-plugins. That also removes the downloaded binary.
Everything runs locally. The plugin makes two kinds of network request: the one-time binary download, and the queries you run against your own warehouse. There is no telemetry.
Elastic License 2.0.
hooks/register.tsx 211 lines1import { atom, memberOf, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { DosiFacts, DosiPaneTab } from '../types'
5import { progress, refresh, statusText } from './facts'
6import { extractJson } from './parse'
7import { band, classify, markdownTable, pane, resultRow } from './views'
8
9// L1 (Claude Code only): live facts in the status line and /dosi, a band above
10// the prompt when there is something to act on, a lineage pane, and dosi JSON
11// results drawn as tables. Presentation only: the model reads what it always
12// did, and with the mod off every skill works the same (RFC §6.8, issue #5).
13
14const PANE = 'dosi-lineage'
15// The same values facts.ts writes: the scan wants each file's own const.
16const facts = atom({ plugin: 'dosi', key: 'facts' } as const, null)
17const graph = atom({ plugin: 'dosi', key: 'graph' } as const, null)
18const calls = atom({ plugin: 'dosi', key: 'calls' } as const, {})
19const tab = atom({ plugin: 'dosi', key: 'tab' } as const, 'lineage')
20const focus = atom({ plugin: 'dosi', key: 'focus' } as const, '')
21const htmlPath = atom({ plugin: 'dosi', key: 'htmlPath' } as const, '')
22const isSqlOpen = atom({ plugin: 'dosi', key: 'isSqlOpen' } as const, false)
23
24const RUNS_DOSI = /(^|[\s/;&|(])dosi\s/
25const TOUCHES_DOSI = /(^|[\s/;&|(])dosi(-progress)?\s/
26const DOSI_FILE = /(^|\/)(dosi\/(model|ontology)\.yaml|dosi-connections\.yaml)$/
27const ANSWERS = ['yes', 'later', 'never'] as const
28
29async function sync($: EngineInterface, force = false): Promise<DosiFacts | null> {
30 try {
31 const f = await refresh($, force)
32 $.ui.status(statusText(f))
33 return f
34 } catch {
35 // a status line is never worth failing anything over
36 return null
37 }
38}
39
40async function openPane($: EngineInterface, to?: DosiPaneTab, at?: string) {
41 if (to) await update($, tab, () => to)
42 if (at) await update($, focus, () => at)
43 await $.ui.open({ id: PANE, title: 'dosi' })
44}
45
46function summary(f: DosiFacts | null, next: string): string {
47 if (!f) return 'dosi: no facts yet (the plugin is still starting).'
48 const lines: string[] = [`dosi · stage ${f.stage}${f.isBinReady ? '' : ' · binary still installing'}`]
49 const def = f.connections.find(c => c.isDefault) ?? f.connections[0]
50 const others = f.connections.filter(c => c !== def).map(c => c.name)
51 lines.push(
52 `connection ${def ? `${def.type || '?'}:${def.name}${def.isDefault ? ' (default)' : ''}${others.length ? ` · also ${others.join(', ')}` : ''}` : f.sources.length ? `none yet · found ${f.sources.join(', ')}` : 'none yet'}`,
53 )
54 if (f.model) {
55 const m = f.model
56 const health = m.issues.length ? `✗ ${m.issues.length} issue${m.issues.length === 1 ? '' : 's'}` : '✓ valid'
57 lines.push(
58 `model ${m.path} · ${health}${m.warnings ? ` (${m.warnings} warning${m.warnings === 1 ? '' : 's'})` : ''} · ${m.datasets} datasets · ${m.metrics.length} metrics · ${m.dimensions} dimensions`,
59 )
60 const names = m.metrics.map(x => x.name)
61 if (names.length) lines.push(`metrics ${names.slice(0, 6).join(', ')}${names.length > 6 ? ` … (+${names.length - 6})` : ''}`)
62 } else {
63 lines.push('model none yet')
64 }
65 lines.push(
66 `ontology ${f.ontology ? `${f.ontology.path} · ${f.ontology.concepts.length} concepts: ${f.ontology.concepts.join(', ')}` : '—'}`,
67 )
68 const hint = next.split('\n')[0]?.replace(/^(HINT|ASK): /, '').split(' | ')[0]
69 lines.push(`next ${hint || 'ask a data question'}`)
70 lines.push('more /dosi lineage [metric] · /dosi metrics · /dosi refresh')
71 return lines.join('\n')
72}
73
74export const register: Register = on => {
75 on('session.start', async ($, e, next) => {
76 await $.command.register({
77 name: 'dosi',
78 description: 'Dosi: connection, model, metrics and the next step; /dosi lineage opens the lineage pane',
79 argumentHint: '[lineage [metric] | metrics | refresh]',
80 })
81 await sync($, true)
82 return next(e)
83 })
84
85 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
86 const isDosi = TOUCHES_DOSI.test(e.command)
87 if (isDosi && RUNS_DOSI.test(e.command) && e.tool_use_id) {
88 const id = e.tool_use_id
89 await update($, calls, all => {
90 const kept = Object.entries(all).slice(-49)
91 return { ...Object.fromEntries(kept), [id]: e.command }
92 })
93 }
94 const ran = await next(e)
95 if (isDosi) await sync($)
96 return ran
97 }).catch(($, e, next) => next(e))
98
99 on('tool.call', async ($, e, next) => {
100 const ran = await next(e)
101 const path = (e as { file_path?: unknown }).file_path
102 if (['Write', 'Edit', 'MultiEdit'].includes(String(e.tool)) && typeof path === 'string' && DOSI_FILE.test(path)) {
103 await sync($)
104 }
105 return ran
106 }).catch(($, e, next) => next(e))
107
108 on('command.run', { command: 'dosi' }, async ($, e) => {
109 const [sub = '', arg = ''] = e.args.trim().split(/\s+/)
110 if (sub === 'lineage' || sub === 'graph') {
111 const f = await sync($)
112 const at = arg ? (arg.includes(':') ? arg : `metric:${arg}`) : undefined
113 await openPane($, 'lineage', at)
114 return { text: f?.model ? `Lineage pane opened${arg ? ` on ${arg}` : ''}.` : 'No semantic model yet: the pane will fill once dosi/model.yaml exists.' }
115 }
116 if (sub === 'metrics') {
117 const f = await sync($)
118 const ms = f?.model?.metrics ?? []
119 if (ms.length === 0) return { text: 'No metrics yet.' }
120 return { text: markdownTable(ms.map(m => ({ metric: m.name, kind: m.kind, description: m.description })), 200) }
121 }
122 const f = await sync($, sub === 'refresh')
123 return { text: summary(f, await progress($, ['peek'])) }
124 })
125
126 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
127 const els = $.ui.resolve(e)
128 const [f, g, t, at, html] = await Promise.all([
129 read($, facts),
130 read($, graph),
131 read($, tab),
132 read($, focus),
133 read($, htmlPath),
134 ])
135 return pane(els, {
136 facts: f,
137 graph: g,
138 tab: t,
139 focus: at,
140 htmlPath: html,
141 columns: e.props.bodyColumns,
142 onTab: to => void update($, tab, () => to),
143 onFocus: id => void update($, focus, () => id),
144 onHtml: async () => {
145 const root = await $.session.root()
146 // Into the temp dir, as the dosi-view skill does: never the project.
147 const write = 'out="${TMPDIR:-/tmp}/dosi-lineage.html"; sh "$0" lineage view --no-open --out "$out" >/dev/null && printf %s "$out"'
148 const run = await $.process.run(['sh', '-c', write, `${$.plugin.root}/bin/dosi`], {
149 cwd: root,
150 env: { CLAUDE_PROJECT_DIR: root },
151 timeoutMs: 20000,
152 })
153 const out = run.stdout.trim()
154 if (run.exitCode === 0 && out) {
155 await update($, htmlPath, () => out)
156 } else {
157 $.ui.toast('dosi: could not write the lineage page')
158 }
159 },
160 })
161 })
162
163 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
164 if (e.props.hasSurvey || e.props.isWorking || e.props.view.agentId) return next(e)
165 const f = await read($, facts)
166 if (!f) return next(e)
167 const els = $.ui.resolve(e)
168 const drawn = band(els, f, {
169 connect: () => void $.prompt.submit({ text: 'Connect to my data', asUser: true }),
170 issues: () => void openPane($, 'issues'),
171 answer: async i => {
172 const ask = f.ask
173 if (!ask) return
174 await progress($, ['next'])
175 await progress($, ['answer', ask.id, ANSWERS[i] ?? 'later'])
176 if (i === 0) {
177 await $.prompt.submit({ text: `${ask.text}\n→ ${ask.options[0] ?? ''}` })
178 }
179 await sync($)
180 },
181 })
182 return drawn ?? next(e)
183 })
184
185 on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {
186 if (e.props.tool !== 'Bash') return next(e)
187 const command = (await read($, calls))[e.props.tool_use_id]
188 if (!command || !/--format[\s=]json/.test(command)) return next(e)
189 const out = e.props.output
190 const text =
191 typeof out === 'string' ? out : out && typeof out === 'object' ? String((out as { stdout?: unknown }).stdout ?? '') : ''
192 const doc = extractJson(text)
193 if (classify(doc) === null) return next(e)
194 const f = await read($, facts)
195 const named = /--connection[\s=](\S+)/.exec(command)?.[1]
196 const conn = named ?? (f?.connections.find(c => c.isDefault) ?? f?.connections[0])?.name
197 const dialect = (doc as { dialect?: unknown }).dialect
198 const source = [typeof dialect === 'string' ? dialect : '', conn ?? ''].filter(Boolean).join(':') || 'dosi'
199 const sqlOpen = memberOf(isSqlOpen, e)
200 const els = $.ui.resolve(e)
201 return (
202 resultRow(els, doc, {
203 source,
204 isSqlOpen: await read($, sqlOpen),
205 toggleSql: () => void update($, sqlOpen, v => !v),
206 openPane: () => void openPane($, 'lineage'),
207 }) ?? next(e)
208 )
209 })
210}
211hooks/facts.ts 151 lines1// What the dosi mod knows about the project, gathered through `$` and never
2// through the model: the progress engine, the CLI's JSON and file existence.
3// The connections file is read here for names and types only (parse.ts).
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface } from 'claude-code'
6
7import type { DosiFacts } from '../types'
8import { extractJson, parseAsk, parseConnections, parseGraph, parseMetrics, parseValidate } from './parse'
9
10const facts = atom({ plugin: 'dosi', key: 'facts' } as const, null)
11const graph = atom({ plugin: 'dosi', key: 'graph' } as const, null)
12
13type Run = { code: number; out: string }
14
15async function sh($: EngineInterface, root: string, argv: string[]): Promise<Run> {
16 try {
17 const run = await $.process.run(['sh', ...argv], {
18 cwd: root,
19 env: { CLAUDE_PROJECT_DIR: root },
20 timeoutMs: 15000,
21 })
22 return { code: run.exitCode, out: run.stdout }
23 } catch {
24 return { code: -1, out: '' }
25 }
26}
27
28export async function progress($: EngineInterface, args: string[]): Promise<string> {
29 const root = await $.session.root()
30 const run = await sh($, root, [`${$.plugin.root}/bin/dosi-progress`, ...args])
31 return run.code === 0 ? run.out.trim() : ''
32}
33
34/** The pinned dosi through the plugin's shim, JSON out, parsed. */
35export async function dosi($: EngineInterface, root: string, args: string[]): Promise<unknown> {
36 const run = await sh($, root, [`${$.plugin.root}/bin/dosi`, '--format', 'json', ...args])
37 return extractJson(run.out)
38}
39
40async function mtime($: EngineInterface, path: string): Promise<number> {
41 try {
42 return (await $.fs.stat(path)).mtimeMs
43 } catch {
44 return 0
45 }
46}
47
48/** What step 1 could connect from, by existence only (as session-start.sh). */
49async function sources($: EngineInterface, root: string): Promise<string[]> {
50 const found: string[] = []
51 const has = (p: string) => $.fs.exists(`${root}/${p}`).catch(() => false)
52 if (await has('dbt_project.yml')) found.push('dbt')
53 if (await has('.env')) found.push('.env')
54 try {
55 const files = (await $.fs.list(root)).filter(f => f.kind === 'file')
56 for (const f of files) {
57 if (/\.(duckdb|sqlite|parquet|csv)$/.test(f.name)) found.push(f.name)
58 }
59 } catch {
60 // an unreadable folder only means nothing found
61 }
62 return found.slice(0, 4)
63}
64
65/**
66 * Re-reads the facts when a file they come from changed (or when `force`),
67 * and writes them to state; the status line, band and pane redraw from it.
68 */
69export async function refresh($: EngineInterface, force = false): Promise<DosiFacts | null> {
70 const root = await $.session.root()
71 const modelPath = `${root}/dosi/model.yaml`
72 const ontologyPath = `${root}/dosi/ontology.yaml`
73 const connPath = `${root}/dosi-connections.yaml`
74 const [m, o, c] = await Promise.all([mtime($, modelPath), mtime($, ontologyPath), mtime($, connPath)])
75 const [stage, peek] = await Promise.all([progress($, ['stage']), progress($, ['peek'])])
76 const signature = `${m}|${o}|${c}`
77 const prev = await read($, facts)
78 if (!force && prev && prev.signature === signature && prev.isBinReady) {
79 const next = { ...prev, stage: stage || prev.stage, ask: parseAsk(peek) }
80 await update($, facts, () => next)
81 return next
82 }
83
84 const connections = c ? parseConnections(await $.fs.read(connPath).catch(() => '')) : []
85 let isBinReady = true
86 let model: DosiFacts['model'] = null
87 let ontology: DosiFacts['ontology'] = null
88 if (m) {
89 const [ds, ms, dims, val, lin] = await Promise.all([
90 dosi($, root, ['list', 'datasets']),
91 dosi($, root, ['list', 'metrics']),
92 dosi($, root, ['list', 'dimensions']),
93 dosi($, root, ['validate']),
94 dosi($, root, ['lineage', 'dump']),
95 ])
96 const code = (ds as { code?: string } | undefined)?.code
97 isBinReady = code !== 'dosi_installing' && code !== 'install_failed'
98 const checked = parseValidate(val)
99 model = {
100 path: 'dosi/model.yaml',
101 datasets: Array.isArray(ds) ? ds.length : 0,
102 metrics: parseMetrics(ms),
103 dimensions: Array.isArray(dims) ? dims.length : 0,
104 issues: checked.issues,
105 warnings: checked.warnings,
106 }
107 await update($, graph, () => parseGraph(lin))
108 } else {
109 await update($, graph, () => null)
110 }
111 if (o) {
112 const described = (await dosi($, root, ['describe'])) as { concepts?: { name?: string }[] } | undefined
113 ontology = {
114 path: 'dosi/ontology.yaml',
115 concepts: (described?.concepts ?? []).map(x => String(x.name ?? '')).filter(Boolean),
116 }
117 }
118 const next: DosiFacts = {
119 stage: stage || 'S0',
120 ask: parseAsk(peek),
121 isBinReady,
122 sources: m ? [] : await sources($, root),
123 connections,
124 model,
125 ontology,
126 signature,
127 }
128 await update($, facts, () => next)
129 return next
130}
131
132/** The status line: the live facts in one short line. */
133export function statusText(f: DosiFacts | null): string {
134 if (!f) return 'dosi'
135 if (!f.isBinReady) return 'dosi · installing'
136 const parts = ['dosi']
137 const conn = f.connections.find(x => x.isDefault) ?? f.connections[0]
138 if (conn) parts.push(conn.type ? `${conn.type}:${conn.name}` : conn.name)
139 if (f.model) {
140 parts.push(`${f.model.datasets} ds · ${f.model.metrics.length} metrics`)
141 const errors = f.model.issues.length
142 if (errors) parts.push(`⚠ ${errors} issue${errors === 1 ? '' : 's'}`)
143 } else if (!conn) {
144 parts.push('not connected')
145 } else {
146 parts.push('no model')
147 }
148 if (f.ontology) parts.push(`ontology ${f.ontology.concepts.length}`)
149 return parts.join(' · ')
150}
151hooks/parse.ts 127 lines1// Pure parsers for the dosi mod: CLI JSON and project files → the shapes the
2// state contract declares. No `$` here, so the tests can run them as is.
3import type { DosiConnection, DosiEdge, DosiGraph, DosiIssue, DosiMetric, DosiNode } from '../types'
4
5type Json = Record<string, unknown>
6
7const asList = (v: unknown): Json[] => (Array.isArray(v) ? (v as Json[]) : [])
8const asText = (v: unknown): string => (typeof v === 'string' ? v : v == null ? '' : String(v))
9
10/**
11 * The JSON document in a tool's output text. Bash merges stderr warnings and,
12 * on a non-zero exit, prefixes the exit code, so the document is the first
13 * line opening with `{` or `[` up to its last closing bracket.
14 */
15export function extractJson(text: string): unknown {
16 const trimmed = text.trim()
17 try {
18 return JSON.parse(trimmed)
19 } catch {
20 // fall through to the line scan
21 }
22 const lines = trimmed.split('\n')
23 for (let i = 0; i < lines.length; i++) {
24 const head = lines[i]?.trimStart() ?? ''
25 if (!head.startsWith('{') && !head.startsWith('[')) continue
26 const rest = lines.slice(i).join('\n')
27 const close = Math.max(rest.lastIndexOf('}'), rest.lastIndexOf(']'))
28 try {
29 return JSON.parse(rest.slice(0, close + 1))
30 } catch {
31 // keep scanning
32 }
33 }
34 return undefined
35}
36
37/**
38 * Connection names, types and the default flag from `dosi-connections.yaml`.
39 * Reads only those three keys line by line; every other value (hosts, users,
40 * `${VAR}` references) is skipped and never leaves this function.
41 */
42export function parseConnections(yaml: string): DosiConnection[] {
43 const out: DosiConnection[] = []
44 let inBlock = false
45 let entryIndent = -1
46 for (const raw of yaml.split('\n')) {
47 const line = raw.replace(/\s+#.*$/, '')
48 if (!line.trim()) continue
49 const indent = line.length - line.trimStart().length
50 if (indent === 0) {
51 inBlock = /^datasources\s*:/.test(line)
52 entryIndent = -1
53 continue
54 }
55 if (!inBlock) continue
56 const key = /^(\s*)([A-Za-z0-9_.-]+)\s*:\s*(.*)$/.exec(line)
57 if (!key) continue
58 const [, , name = '', value = ''] = key
59 if (entryIndent < 0 || indent === entryIndent) {
60 entryIndent = indent
61 out.push({ name, type: '', isDefault: false })
62 continue
63 }
64 const last = out[out.length - 1]
65 if (!last || indent <= entryIndent) continue
66 if (name === 'type') last.type = value.replace(/^['"]|['"]$/g, '')
67 if (name === 'default') last.isDefault = /^true$/i.test(value)
68 }
69 return out
70}
71
72/** The `ASK:` line of `dosi-progress peek`: the question and its options. */
73export function parseAsk(peek: string): { id: string; text: string; options: string[] } | null {
74 const first = peek.split('\n')[0] ?? ''
75 if (!first.startsWith('ASK: ')) return null
76 const [text = '', ...options] = first.slice(5).split(' | ').map(s => s.trim())
77 const id = /dosi-progress answer (\S+)/.exec(peek)?.[1] ?? ''
78 return id ? { id, text, options } : null
79}
80
81export function parseMetrics(json: unknown): DosiMetric[] {
82 return asList(json).map(m => ({
83 name: asText(m.name),
84 kind: asText(m.kind),
85 datasets: asList(m.datasets).map(asText),
86 description: asText(m.description),
87 }))
88}
89
90export function parseValidate(json: unknown): { issues: DosiIssue[]; warnings: number } {
91 const doc = (json ?? {}) as Json
92 const toIssue = (i: Json): DosiIssue => ({
93 severity: asText(i.severity) || 'error',
94 code: asText(i.code),
95 location: asText(i.location),
96 message: asText(i.message),
97 })
98 return {
99 issues: [...asList(doc.issues), ...asList(doc.compile_errors)].map(toIssue),
100 warnings: asList(doc.warnings).length,
101 }
102}
103
104/** `dosi lineage dump` (graph contract v2), cut down to what the pane draws. */
105export function parseGraph(json: unknown): DosiGraph | null {
106 const doc = json as Json | undefined
107 if (!doc || !Array.isArray(doc.nodes) || !Array.isArray(doc.edges)) return null
108 const layers = asList(doc.layers).map(l => asText(l.kind))
109 const nodes: DosiNode[] = asList(doc.nodes).map(n => {
110 const d = (n.detail ?? {}) as Json
111 const detail = asText(d.expression) || asText(d.description) || asText(d.source) || asText(d.table)
112 return {
113 id: asText(n.id),
114 kind: asText(n.kind),
115 layer: typeof n.layer === 'number' ? n.layer : 0,
116 label: asText(n.label) || asText(n.name),
117 detail,
118 }
119 })
120 const edges: DosiEdge[] = asList(doc.edges).map(e => ({
121 source: asText(e.source),
122 target: asText(e.target),
123 kind: asText(e.kind),
124 }))
125 return { layers, nodes, edges }
126}
127hooks/views.tsx 299 lines1// The dosi mod's drawings: the lineage pane, the band above the prompt and
2// dosi result rows. Each takes the surface's element table from `$.ui.resolve`.
3import type { ElementTable } from 'claude-code'
4
5import type { DosiFacts, DosiGraph, DosiPaneTab } from '../types'
6import { focusChoices, isUpstream, kindLabel, lineageSvg, lineageTree } from './lineage'
7
8type Els = ElementTable
9
10const KIND_COLOR: Record<string, string> = {
11 physical_table: 'subtle',
12 dataset: 'success',
13 metric_atomic: 'warning',
14 metric_derived: 'merged',
15}
16
17const cell = (v: unknown): string => {
18 if (v === null || v === undefined) return '∅'
19 const s = typeof v === 'number' ? (Number.isInteger(v) ? String(v) : v.toLocaleString('en-US', { maximumFractionDigits: 4 })) : String(v)
20 return s.replace(/\|/g, '\\|').replace(/\n/g, ' ')
21}
22
23/** A Markdown table of up to `max` rows, columns in the order the rows give. */
24export function markdownTable(rows: Record<string, unknown>[], max = 20): string {
25 const cols = Object.keys(rows[0] ?? {})
26 if (cols.length === 0) return '_no rows_'
27 const head = `| ${cols.map(c => cell(c.replace(/__/g, '.'))).join(' | ')} |`
28 const rule = `| ${cols.map(() => '---').join(' | ')} |`
29 const body = rows.slice(0, max).map(r => `| ${cols.map(c => cell(r[c])).join(' | ')} |`)
30 return [head, rule, ...body].join('\n')
31}
32
33export type Tab = { tab: DosiPaneTab; label: string; hotkey: string }
34
35export function pane(
36 els: Els,
37 o: {
38 facts: DosiFacts | null
39 graph: DosiGraph | null
40 tab: DosiPaneTab
41 focus: string
42 htmlPath: string
43 columns: number
44 onTab: (t: DosiPaneTab) => void
45 onFocus: (id: string) => void
46 onHtml: () => void
47 },
48) {
49 const { Box, Text, Button, Markdown, Link } = els
50 const issues = o.facts?.model?.issues ?? []
51 const tabs: Tab[] = [
52 { tab: 'lineage', label: 'Lineage', hotkey: 'l' },
53 { tab: 'metrics', label: 'Metrics', hotkey: 'm' },
54 { tab: 'issues', label: issues.length ? `Issues (${issues.length})` : 'Issues', hotkey: 'i' },
55 ]
56 const bar = (
57 <Box key="tabs" flexDirection="row" gap={1}>
58 {tabs.map(t => (
59 <Button
60 key={`tab-${t.tab}`}
61 label={t.label}
62 hotkey={t.hotkey}
63 variant={t.tab === o.tab ? 'primary' : 'secondary'}
64 onPress={() => o.onTab(t.tab)}
65 />
66 ))}
67 </Box>
68 )
69 if (!o.facts?.model) {
70 return (
71 <Box flexDirection="column">
72 {bar}
73 <Text dimColor>No semantic model yet. Ask a data question, or say "build a semantic model".</Text>
74 </Box>
75 )
76 }
77 if (o.tab === 'metrics') {
78 const rows = o.facts.model.metrics.map(m => ({
79 metric: m.name,
80 kind: m.kind,
81 datasets: m.datasets.join(', '),
82 description: m.description,
83 }))
84 return (
85 <Box flexDirection="column">
86 {bar}
87 <Markdown key="metrics" text={markdownTable(rows, 200)} />
88 </Box>
89 )
90 }
91 if (o.tab === 'issues') {
92 return (
93 <Box flexDirection="column">
94 {bar}
95 {issues.length === 0 && <Text color="success">✓ dosi/model.yaml validates ({o.facts.model.warnings} warnings)</Text>}
96 {issues.map(i => (
97 <Box flexDirection="column" marginTop={1}>
98 <Text color="error">✗ {i.code}</Text>
99 <Text>{i.message}</Text>
100 <Text dimColor>{i.location}</Text>
101 </Box>
102 ))}
103 </Box>
104 )
105 }
106 const g = o.graph
107 if (!g || g.nodes.length === 0) {
108 return (
109 <Box flexDirection="column">
110 {bar}
111 <Text dimColor>The lineage graph is not available (the model does not validate yet).</Text>
112 </Box>
113 )
114 }
115 const choices = focusChoices(g)
116 const focus = choices.some(c => c.value === o.focus) ? o.focus : (choices[0]?.value ?? '')
117 const rows = lineageTree(g, focus)
118 const picker =
119 'Select' in els ? (
120 <els.Select
121 key="focus"
122 label={isUpstream(focus) ? 'Computed from' : 'Used by'}
123 value={focus}
124 options={choices}
125 onSelect={(v: string) => o.onFocus(v)}
126 />
127 ) : null
128 const svg =
129 'Svg' in els ? (
130 <els.Svg
131 source={lineageSvg(g, focus)}
132 alt={rows.map(r => r.node.label).join(' ← ')}
133 isInteractive
134 />
135 ) : null
136 const room = Math.max(20, o.columns - 4)
137 return (
138 <Box flexDirection="column">
139 {bar}
140 {picker}
141 {svg}
142 <Box key="tree" flexDirection="column" marginTop={1}>
143 {rows.map(r => (
144 <Text wrap="truncate-end">
145 <Text dimColor>{r.prefix}</Text>
146 <Text color={KIND_COLOR[r.node.kind] ?? 'text'} bold={r.node.id === focus}>
147 {r.node.label}
148 </Text>
149 <Text dimColor>
150 {' '}
151 {kindLabel(r.node.kind)}
152 {r.node.detail && r.prefix.length + r.node.label.length + 12 < room ? ` · ${r.node.detail}` : ''}
153 </Text>
154 </Text>
155 ))}
156 </Box>
157 <Box key="foot" flexDirection="row" gap={1} marginTop={1}>
158 <Button key="html" label="Write HTML page" hotkey="h" onPress={() => o.onHtml()} />
159 {o.htmlPath ? <Link href={`file://${o.htmlPath}`}>open {o.htmlPath}</Link> : null}
160 </Box>
161 </Box>
162 )
163}
164
165export function band(
166 els: Els,
167 f: DosiFacts,
168 on: { connect: () => void; issues: () => void; answer: (index: number) => void },
169) {
170 const { Box, Text, Button } = els
171 if (f.ask) {
172 const ask = f.ask
173 return (
174 <Box flexDirection="row" gap={1}>
175 <Text color="claude">dosi</Text>
176 <Text wrap="truncate-end">{ask.text}</Text>
177 {ask.options.map((opt, i) => (
178 <Button key={`ask-${i}`} label={opt} hotkey={String(i + 1)} variant={i === 0 ? 'primary' : 'secondary'} onPress={() => on.answer(i)} />
179 ))}
180 </Box>
181 )
182 }
183 const issues = f.model?.issues ?? []
184 if (issues.length > 0) {
185 return (
186 <Box flexDirection="row" gap={1}>
187 <Text color="error">dosi ⚠</Text>
188 <Text wrap="truncate-end">
189 dosi/model.yaml: {issues.length} issue{issues.length === 1 ? '' : 's'} · {issues[0]?.message ?? ''}
190 </Text>
191 <Button key="issues" label="Show" hotkey="s" onPress={() => on.issues()} />
192 </Box>
193 )
194 }
195 if (f.stage === 'S0' && f.connections.length === 0 && f.sources.length > 0) {
196 return (
197 <Box flexDirection="row" gap={1}>
198 <Text color="claude">dosi</Text>
199 <Text wrap="truncate-end">found {f.sources.join(', ')}</Text>
200 <Button key="connect" label="Connect" hotkey="c" variant="primary" onPress={() => on.connect()} />
201 </Box>
202 )
203 }
204 return null
205}
206
207type DosiDoc = Record<string, unknown>
208
209/** What kind of dosi JSON a result row holds, or null to leave the row alone. */
210export function classify(doc: unknown): 'rows' | 'error' | 'validate' | 'graph' | 'metrics' | null {
211 if (Array.isArray(doc)) {
212 const first = doc[0] as DosiDoc | undefined
213 return first && 'name' in first && 'kind' in first && 'datasets' in first ? 'metrics' : null
214 }
215 if (!doc || typeof doc !== 'object') return null
216 const d = doc as DosiDoc
217 if (Array.isArray(d.rows)) return 'rows'
218 if (typeof d.code === 'string' && typeof d.message === 'string') return 'error'
219 if (Array.isArray(d.issues) && Array.isArray(d.warnings)) return 'validate'
220 if (Array.isArray(d.nodes) && Array.isArray(d.edges)) return 'graph'
221 return null
222}
223
224export function resultRow(
225 els: Els,
226 doc: unknown,
227 o: { source: string; isSqlOpen: boolean; toggleSql: () => void; openPane: () => void },
228) {
229 const { Box, Text, Button, Markdown, Code } = els
230 const kind = classify(doc)
231 const d = doc as DosiDoc
232 if (kind === 'rows') {
233 const rows = d.rows as Record<string, unknown>[]
234 const sql = typeof d.sql === 'string' ? d.sql : ''
235 const more = rows.length > 20 ? ` · first 20 shown` : ''
236 return (
237 <Box flexDirection="column">
238 <Markdown key="table" text={markdownTable(rows)} />
239 <Box flexDirection="row" gap={1}>
240 <Text dimColor>
241 {o.source} · {rows.length} row{rows.length === 1 ? '' : 's'}
242 {more}
243 </Text>
244 {sql ? <Button key="sql" plain label={o.isSqlOpen ? 'SQL ▾' : 'SQL ▸'} onPress={() => o.toggleSql()} /> : null}
245 </Box>
246 {o.isSqlOpen && sql ? <Code source={sql} language="sql" /> : null}
247 </Box>
248 )
249 }
250 if (kind === 'error') {
251 const candidates = Array.isArray(d.candidates) ? (d.candidates as unknown[]).map(String) : []
252 const hint = typeof d.hint === 'string' ? d.hint : candidates.length ? `did you mean: ${candidates.slice(0, 6).join(', ')}` : ''
253 return (
254 <Box flexDirection="column">
255 <Text color="error">✗ {String(d.code)}</Text>
256 <Text>{String(d.message).split('\n')[0]}</Text>
257 {hint ? <Text dimColor>→ {hint}</Text> : null}
258 </Box>
259 )
260 }
261 if (kind === 'validate') {
262 const issues = [...(d.issues as DosiDoc[]), ...((d.compile_errors as DosiDoc[] | undefined) ?? [])]
263 const warnings = (d.warnings as unknown[]).length
264 if (issues.length === 0) {
265 return <Text color="success">✓ model validates{warnings ? ` · ${warnings} warning${warnings === 1 ? '' : 's'}` : ''}</Text>
266 }
267 return (
268 <Box flexDirection="column">
269 {issues.slice(0, 8).map(i => (
270 <Text>
271 <Text color="error">✗ {String(i.code ?? '')}</Text> {String(i.message ?? '')}
272 </Text>
273 ))}
274 </Box>
275 )
276 }
277 if (kind === 'graph') {
278 const count = (k: string) => (d.nodes as DosiDoc[]).filter(n => n.kind === k).length
279 return (
280 <Box flexDirection="row" gap={1}>
281 <Text dimColor>
282 lineage · {count('physical_table')} tables · {count('dataset')} datasets ·{' '}
283 {count('metric_atomic') + count('metric_derived')} metrics
284 </Text>
285 <Button key="pane" plain label="open lineage pane" onPress={() => o.openPane()} />
286 </Box>
287 )
288 }
289 if (kind === 'metrics') {
290 const rows = (doc as DosiDoc[]).map(m => ({
291 metric: m.name,
292 kind: m.kind,
293 description: m.description,
294 }))
295 return <Markdown key="metrics" text={markdownTable(rows, 50)} />
296 }
297 return null
298}
299hooks/lineage.ts 136 lines1// Lineage drawing for the dosi pane: a text tree for every surface, and an
2// SVG layered DAG where the surface has `Svg`. Pure functions of the graph.
3import type { DosiGraph, DosiNode } from '../types'
4
5export type TreeRow = { prefix: string; node: DosiNode }
6
7const KIND_LABEL: Record<string, string> = {
8 physical_table: 'table',
9 dataset: 'dataset',
10 metric_atomic: 'metric',
11 metric_derived: 'derived',
12}
13
14export const kindLabel = (kind: string): string => KIND_LABEL[kind] ?? kind.replace(/_/g, ' ')
15
16/** Upstream for a metric, downstream for a table or dataset. */
17export const isUpstream = (id: string): boolean => id.startsWith('metric:')
18
19/**
20 * The tree under `focus`: what it is computed from (a metric) or what depends
21 * on it (a table or dataset). Joins are lateral, not lineage, so they are
22 * left out; a node reached twice is drawn once more, marked, and not walked.
23 */
24export function lineageTree(graph: DosiGraph, focus: string): TreeRow[] {
25 const byId = new Map(graph.nodes.map(n => [n.id, n]))
26 const up = isUpstream(focus)
27 const next = new Map<string, string[]>()
28 for (const e of graph.edges) {
29 if (e.kind === 'join') continue
30 const [from, to] = up ? [e.target, e.source] : [e.source, e.target]
31 next.set(from, [...(next.get(from) ?? []), to])
32 }
33 const rows: TreeRow[] = []
34 const seen = new Set<string>()
35 const walk = (id: string, lead: string, branch: string) => {
36 const node = byId.get(id)
37 if (!node) return
38 rows.push({ prefix: lead + branch, node })
39 if (seen.has(id)) return
40 seen.add(id)
41 const kids = next.get(id) ?? []
42 const childLead = lead + (branch === '' ? '' : branch === '└─ ' ? ' ' : '│ ')
43 kids.forEach((kid, i) => walk(kid, childLead, i === kids.length - 1 ? '└─ ' : '├─ '))
44 }
45 walk(focus, '', '')
46 return rows
47}
48
49/** The ids on the tree under `focus`, for highlighting. */
50export function lineageIds(graph: DosiGraph, focus: string): Set<string> {
51 return new Set(lineageTree(graph, focus).map(r => r.node.id))
52}
53
54/** Choices for the focus picker: metrics first, then tables. */
55export function focusChoices(graph: DosiGraph): { value: string; label: string }[] {
56 const pick = (kinds: string[]) =>
57 graph.nodes
58 .filter(n => kinds.includes(n.kind))
59 .map(n => ({ value: n.id, label: `${kindLabel(n.kind)} · ${n.label}` }))
60 return [...pick(['metric_atomic', 'metric_derived']), ...pick(['physical_table', 'dataset'])]
61}
62
63const escapeXml = (s: string): string =>
64 s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"')
65
66const clip = (s: string, n: number): string => (s.length > n ? `${s.slice(0, n - 1)}…` : s)
67
68const TONE: Record<string, string> = {
69 physical_table: '#6b7f99',
70 dataset: '#3d8a7a',
71 metric_atomic: '#c07a2c',
72 metric_derived: '#9a5bb5',
73}
74
75/**
76 * A layered DAG: one column per layer (table → dataset → metric → derived),
77 * edges as curves, the focus's lineage drawn strong and the rest faded.
78 * Hover shows each node's detail through `<title>` (Svg `isInteractive`).
79 */
80export function lineageSvg(graph: DosiGraph, focus: string): string {
81 const lit = lineageIds(graph, focus)
82 const W = 168
83 const H = 26
84 const GAP_X = 56
85 const GAP_Y = 10
86 const PAD = 12
87 const layerCount = Math.max(1, ...graph.nodes.map(n => n.layer + 1))
88 const columns: DosiNode[][] = Array.from({ length: layerCount }, () => [])
89 for (const n of graph.nodes) columns[n.layer]?.push(n)
90 const pos = new Map<string, { x: number; y: number }>()
91 columns.forEach((col, i) =>
92 col.forEach((n, j) => pos.set(n.id, { x: PAD + i * (W + GAP_X), y: PAD + 18 + j * (H + GAP_Y) })),
93 )
94 const tallest = Math.max(1, ...columns.map(c => c.length))
95 const width = PAD * 2 + layerCount * W + (layerCount - 1) * GAP_X
96 const height = PAD * 2 + 18 + tallest * (H + GAP_Y)
97 const parts: string[] = []
98 columns.forEach((_, i) => {
99 const name = graph.layers[i] ?? ''
100 parts.push(
101 `<text x="${PAD + i * (W + GAP_X)}" y="${PAD + 8}" font-size="11" fill="#888">${escapeXml(kindLabel(name))}</text>`,
102 )
103 })
104 for (const e of graph.edges) {
105 const a = pos.get(e.source)
106 const b = pos.get(e.target)
107 if (!a || !b) continue
108 const on = lit.has(e.source) && lit.has(e.target) && e.kind !== 'join'
109 const dash = e.kind === 'join' ? ' stroke-dasharray="3 3"' : ''
110 const x1 = a.x + W
111 const y1 = a.y + H / 2
112 const x2 = b.x
113 const y2 = b.y + H / 2
114 const d =
115 e.kind === 'join'
116 ? `M${a.x + W / 2},${a.y + H} C${a.x + W / 2 + 24},${(y1 + y2) / 2} ${b.x + W / 2 + 24},${(y1 + y2) / 2} ${b.x + W / 2},${b.y}`
117 : `M${x1},${y1} C${x1 + GAP_X / 2},${y1} ${x2 - GAP_X / 2},${y2} ${x2},${y2}`
118 parts.push(
119 `<path d="${d}" fill="none" stroke="${on ? '#c07a2c' : '#999'}" stroke-opacity="${on ? 0.9 : 0.3}" stroke-width="${on ? 1.6 : 1}"${dash}/>`,
120 )
121 }
122 for (const n of graph.nodes) {
123 const p = pos.get(n.id)
124 if (!p) continue
125 const tone = TONE[n.kind] ?? '#888'
126 const on = lit.has(n.id)
127 const isFocus = n.id === focus
128 parts.push(
129 `<g opacity="${on ? 1 : 0.45}"><title>${escapeXml(`${kindLabel(n.kind)} ${n.label}${n.detail ? `\n${n.detail}` : ''}`)}</title>` +
130 `<rect x="${p.x}" y="${p.y}" width="${W}" height="${H}" rx="5" fill="${tone}" fill-opacity="${isFocus ? 0.35 : 0.14}" stroke="${tone}" stroke-width="${isFocus ? 2 : 1}"/>` +
131 `<text x="${p.x + 8}" y="${p.y + H / 2 + 4}" font-size="12" font-family="ui-monospace, monospace" fill="${tone}">${escapeXml(clip(n.label, 22))}</text></g>`,
132 )
133 }
134 return `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 ${width} ${height}" width="${width}" height="${height}">${parts.join('')}</svg>`
135}
136types/index.d.ts 59 lines1// The dosi mod's state contract: what its status line, band, pane and result
2// rows draw from. Values are presentation only; every fact comes from the
3// dosi CLI or files in the project, never from the model.
4
5export type DosiConnection = { name: string; type: string; isDefault: boolean }
6
7export type DosiIssue = { severity: string; code: string; location: string; message: string }
8
9export type DosiMetric = { name: string; kind: string; datasets: string[]; description: string }
10
11export type DosiNode = { id: string; kind: string; layer: number; label: string; detail: string }
12
13export type DosiEdge = { source: string; target: string; kind: string }
14
15export type DosiGraph = { layers: string[]; nodes: DosiNode[]; edges: DosiEdge[] }
16
17export type DosiFacts = {
18 /** S0..S6 from bin/dosi-progress. */
19 stage: string
20 /** A pending one-time question from `dosi-progress peek`: text and options. */
21 ask: { id: string; text: string; options: string[] } | null
22 /** False while the pinned binary is still downloading. */
23 isBinReady: boolean
24 /** What the project folder holds that step 1 can connect from. */
25 sources: string[]
26 connections: DosiConnection[]
27 model: {
28 path: string
29 datasets: number
30 metrics: DosiMetric[]
31 dimensions: number
32 issues: DosiIssue[]
33 warnings: number
34 } | null
35 ontology: { path: string; concepts: string[] } | null
36 /** mtimes of the files the facts were read from, to skip a refresh. */
37 signature: string
38}
39
40export type DosiPaneTab = 'lineage' | 'metrics' | 'issues'
41
42declare module 'claude-code' {
43 interface PluginState {
44 dosi: {
45 facts: DosiFacts | null
46 graph: DosiGraph | null
47 /** tool_use_id → command, for the Bash calls that ran dosi. */
48 calls: Record<string, string>
49 tab: DosiPaneTab
50 /** The node the lineage tab is centred on (`metric:x` or `table:y`). */
51 focus: string
52 /** Where the HTML page was last written, for the pane's link. */
53 htmlPath: string
54 /** Whether a result row shows its SQL, per tool_use_id. */
55 isSqlOpen: StateFamily<boolean>
56 }
57 }
58}
59