diff --git a/plugins/altimate-code/.claude-plugin/plugin.json b/plugins/altimate-code/.claude-plugin/plugin.json index 0e42c30d..5a71365a 100644 --- a/plugins/altimate-code/.claude-plugin/plugin.json +++ b/plugins/altimate-code/.claude-plugin/plugin.json @@ -20,5 +20,39 @@ "databricks", "column-lineage" ], - "types": "./types/index.d.ts" + "types": "./types/index.d.ts", + "userConfig": { + "maxScanBytes": { + "type": "number", + "title": "Largest BigQuery scan without asking (not used yet)", + "description": "Not used yet: the BigQuery scan check isn't in this version, so no run is held. When it ships, a dbt run, build or show that BigQuery estimates would scan more bytes than this waits for your approval (0 never waits; other warehouses are never held).", + "default": 10737418240, + "min": 0 + }, + "healthBlocksPush": { + "type": "boolean", + "title": "Project health blocks git push (not used yet)", + "description": "Not used yet: the project health check isn't in this version, so git push is never refused. When it ships, on refuses a push while the check finds new issues in the models you changed; off only shows them.", + "default": false + }, + "healthConfigPath": { + "type": "string", + "title": "Project health check config", + "description": "Not used yet: the project health check isn't in this version. Path to a DataPilot health check config file, relative to the dbt project. Empty uses the default checks.", + "default": "" + }, + "commentsPollSeconds": { + "type": "number", + "title": "Team comments refresh (seconds)", + "description": "Not used yet: team comments aren't in this version. How often the team's comments on shared docs are fetched again.", + "default": 900, + "min": 30 + }, + "commentsInContext": { + "type": "boolean", + "title": "Team comments in Claude's context", + "description": "Not used yet: team comments aren't in this version. When on, the open comments on a model Claude reads or edits are added to its context. Off keeps them out of Claude's context.", + "default": true + } + } } diff --git a/plugins/altimate-code/README.md b/plugins/altimate-code/README.md index 35d2cf4f..e2594739 100644 --- a/plugins/altimate-code/README.md +++ b/plugins/altimate-code/README.md @@ -134,6 +134,18 @@ Rule drafting uses altimate-code's own model (sign in to the Altimate LLM Gatewa - **The per-turn hooks never block**: they hand off to altimate-code in the background. Session start makes one bounded synchronous call (at most 15 seconds). All of them run only in a linked folder (or below it), as recorded in altimate-code's link cache in your own state directory: nothing in the repository turns them on. - **`ALTIMATE_LEARN=0`** turns all of it off: the hooks start nothing. +## Settings + +The plugin has five settings, shown when you enable it (`userConfig` in `.claude-plugin/plugin.json`). None is used yet: the features that read them are not in this version, so changing one changes nothing. The table says what each will control. + +| Setting | Default | What it controls | +| --- | --- | --- | +| `maxScanBytes` | 10 GiB | The largest BigQuery scan a dbt run, build or show may make before it waits for your approval (0 never waits; at least 0). Other warehouses are never held. | +| `healthBlocksPush` | off | When on, `git push` is refused while the project health check finds new issues in the models you changed. Off, the issues are only shown. | +| `healthConfigPath` | empty | The DataPilot health check config file, relative to the dbt project. Empty uses the default checks. | +| `commentsPollSeconds` | 900 | How often the team's comments on shared docs are fetched again (at least 30). | +| `commentsInContext` | on | Whether the open comments on a model Claude reads or edits are added to its context. | + ## Example prompts Once installed, try these in Claude Code (or prefix any of them with `/altimate-code:altimate`): diff --git a/plugins/altimate-code/hooks/altimate-cli.test.ts b/plugins/altimate-code/hooks/altimate-cli.test.ts new file mode 100644 index 00000000..0c2ab774 --- /dev/null +++ b/plugins/altimate-code/hooks/altimate-cli.test.ts @@ -0,0 +1,74 @@ +import { expect, test } from 'claude-code/testing' + +import { runTool, within } from './altimate-cli' + +/** A stand-in for `$` whose CLI answers every call and whose MCP connection attempts go through `connect`. */ +function standIn(connect: () => unknown, now = 0) { + const argvs: string[][] = [] + let mcpCalls = 0 + const $: any = { + process: { + run: async (argv: string[]) => { + argvs.push(argv) + return { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: 'done', metadata: { n: 1 } }) } + }, + }, + mcp: { + connect: async () => connect(), + // No answer: a call that does reach the server falls back to the CLI. + call: async () => (mcpCalls++, null), + }, + // A deadline that never fires, so the fallback is the no-answer one. + clock: { now: async () => now, after: () => {} }, + } + return { $, argvs, mcpCalls: () => mcpCalls } +} + +test('a read call goes without --allow-write; a write call goes through the CLI with it', async () => { + const { $, argvs } = standIn(() => null) + expect(await runTool($, 'dbt_manifest', { a: 1 })).toEqual({ metadata: { n: 1 }, text: 'done', ok: true }) + expect(await runTool($, 'dbt_manifest', { a: 1 }, { write: true })).toEqual({ metadata: { n: 1 }, text: 'done', ok: true }) + expect(argvs.map(argv => argv.slice(1))).toEqual([ + ['tool', 'run', 'dbt_manifest', '--args', '{"a":1}', '--json'], + ['tool', 'run', 'dbt_manifest', '--args', '{"a":1}', '--json', '--allow-write'], + ]) +}) + +test('a write call never asks the MCP server, even when one is connected', async () => { + let connects = 0 + const { $, argvs, mcpCalls } = standIn(() => { + connects++ + return { isConnected: true, server: 'altimate-code' } + }, 10 * 60_000) + await runTool($, 'dbt_manifest', {}, { write: true }) + expect(connects).toBe(0) + expect(argvs).toHaveLength(1) + // The same call without `write` does ask the server: the test above can fail. It gets no answer, so + // it goes through the CLI without --allow-write. + await runTool($, 'dbt_manifest', {}) + expect(connects).toBe(1) + expect(mcpCalls()).toBe(1) + expect(argvs.map(argv => argv.slice(1))[1]).toEqual(['tool', 'run', 'dbt_manifest', '--args', '{}', '--json']) +}) + +test('within handles the work\'s rejection before it sets the deadline, so a throwing clock leaves none unhandled', async () => { + let handled = false + // A work that rejects, recording when a rejection handler is attached. + const rejected = Promise.reject(new Error('rewrite failed')) + const work = { + then: (ok: (v: string) => unknown, failed?: (e: unknown) => unknown) => { + handled = typeof failed === 'function' + return rejected.then(ok, failed) + }, + } as unknown as Promise + const $: any = { + clock: { + after: () => { + expect(handled).toBe(true) + throw new Error('clock failed') + }, + }, + } + await expect(within($, 10, work)).rejects.toThrow('clock failed') + expect(handled).toBe(true) +}) diff --git a/plugins/altimate-code/hooks/altimate-cli.ts b/plugins/altimate-code/hooks/altimate-cli.ts index c71f4f0f..6fb0d6b4 100644 --- a/plugins/altimate-code/hooks/altimate-cli.ts +++ b/plugins/altimate-code/hooks/altimate-cli.ts @@ -53,3 +53,136 @@ export function later($: EngineInterface, work: () => Promise) { }) }) } + +// The plugin's own MCP server, by its key in .mcp.json. +const SERVER_KEY = 'altimate-code' +const TOOL_TIMEOUT_MS = 60_000 + +/** Resolves with the work's value, or null once `ms` pass or it fails. */ +export function within($: EngineInterface, ms: number, work: Promise): Promise { + return new Promise(resolve => { + let settled = false + const settle = (value: T | null) => { + if (settled) return + settled = true + resolve(value) + } + // The work's rejection is handled first, so a deadline that throws leaves none unhandled. + work.then(settle, () => settle(null)) + $.clock.after(ms, () => settle(null)) + }) +} + +let serverName: string | null = null +let connectFailedAt = -Infinity +const CONNECT_RETRY_MS = 60_000 + +/** The plugin's MCP server as $.mcp.call names it, or null when it is not connected (CLI mode); a failure is retried after a minute. */ +async function mcpServer($: EngineInterface): Promise { + if (serverName) return serverName + const now = await $.clock.now() + if (now - connectFailedAt < CONNECT_RETRY_MS) return null + const connected = await $.mcp.connect(SERVER_KEY).catch(() => null) + serverName = connected?.isConnected ? connected.server : null + if (!serverName) connectFailedAt = now + return serverName +} + +export function textOf(content: unknown): string { + if (typeof content === 'string') return content + const blocks = Array.isArray(content) ? content : Array.isArray((content as any)?.content) ? (content as any).content : [] + return blocks + .filter((block: any) => block?.type === 'text' && typeof block.text === 'string') + .map((block: any) => block.text) + .join('\n') +} + +/** + * The file a `` preview says holds the whole answer: null when the text is no such + * preview, undefined when it is one but names no file. + */ +export function persistedPath(text: string): string | null | undefined { + if (!/^\s*(?:<|<)persisted-output(?:>|>)/.test(text)) return null + return /Full output saved to: ([^\n]+?)\s*$/m.exec(text)?.[1] +} + +/** A file:// URI as a filesystem path; a Windows drive path keeps no leading slash. */ +function fileUriPath(uri: string): string { + const path = decodeURIComponent(new URL(uri).pathname) + return /^\/[A-Za-z]:/.test(path) ? path.slice(1) : path +} + +export type RunToolOptions = { + /** Straight to the CLI, whose --json carries the whole metadata. */ + cliOnly?: boolean + /** A deadline on the engine's clock: nothing starts once it has passed, and the CLI is stopped at it. */ + until?: number + /** + * The tool needs write permission (it starts the dbt adapter, or changes something): the call goes + * through the CLI with `--allow-write`, since the plugin's MCP server runs read-only. runTool asks + * nobody: a caller sets it only once the user has said yes to this write (README, "How it works", + * item 4), as the skill does before it adds `--allow-write`. + */ + write?: boolean +} + +/** + * Runs one altimate-code data tool: through the plugin's MCP server when it is connected (no + * permission prompt, structured content when the build sends it), else `altimate tool run --json`. + * `cliOnly` goes straight to the CLI, whose --json carries the whole metadata; a structured result + * the server left out for size is fetched that way too. + */ +export async function runTool($: EngineInterface, name: string, args: Record, options: RunToolOptions = {}) { + const { until, write = false } = options + const cliOnly = options.cliOnly === true || write + // With a deadline, nothing starts once it has passed, and the CLI is stopped at it. + const left = async () => { + const ms = until === undefined ? TOOL_TIMEOUT_MS : until - (await $.clock.now()) + if (ms <= 0) throw new Error('out of time') + return ms + } + const server = cliOnly ? null : await mcpServer($) + if (server) { + const ms = await left() + try { + // The engine's MCP call has no timeout of its own: one that never answers is given up on, so a + // shared trace does not hold every later edit of that column, and the CLI is tried instead. + const result = await within($, ms, $.mcp.call(server, name, args)) + if (!result) throw new Error('altimate-code did not answer over MCP') + let text = textOf(result.content) + // A long result comes back as a preview plus a link to the full text. + const link = result.content.find((block: any) => block?.type === 'resource_link' && String(block.uri).startsWith('file://')) as + | { uri: string } + | undefined + // Claude Code (2.1.319) swaps an answer of about 49 KB or more for a preview that names the file it + // saved the whole answer to, with no link block: the answer is that file. + const saved = link ? null : persistedPath(text) + if (!link && saved === undefined) throw new Error('a cut-off preview with no file named') + // An unreadable link or file leaves only the preview: fetch the whole answer through the CLI instead. + const full = link ? await $.fs.read(fileUriPath(link.uri)).catch(() => null) : saved ? await $.fs.read(saved).catch(() => null) : text + if (full === null) throw new Error('the full result could not be read') + text = full + // Claude Code hands a tool's structured content over as one JSON text block in place of the + // text; the structured content carries the text report as `report`. + const structured = (result.structuredContent ?? (text.trim().startsWith('{') ? parseJson(text) : null)) as any + if (structured?.truncated !== true) { + return { metadata: structured, text: typeof structured?.report === 'string' ? structured.report : text, ok: !result.isError } + } + } catch { + // Fall through to the CLI: the server may have gone away mid-session, so the next call reconnects. + serverName = null + } + } + const argv = ['tool', 'run', name, '--args', JSON.stringify(args), '--json', ...(write ? ['--allow-write'] : [])] + const result = await runAltimate($, argv, await left()) + if ((result as { isStdoutTruncated?: boolean }).isStdoutTruncated) { + return { metadata: null as any, text: `${name}'s answer was larger than the 4 MiB a plugin can read`, ok: false } + } + const data = parseJson<{ status?: string; output?: string; metadata?: unknown }>(result.stdout) + // Anything but the CLI's answer object (an altimate-code that exits before a pipe drains cuts it off) is a + // failure to report and ask again, not "no such model". + if (result.exitCode === 0 && (!data || typeof data !== 'object' || typeof data.status !== 'string')) { + return { metadata: null as any, text: 'the answer could not be read', ok: false } + } + return { metadata: (data?.metadata ?? null) as any, text: data?.output ?? '', ok: result.exitCode === 0 && data?.status !== 'error' } +} diff --git a/plugins/altimate-code/hooks/dbt-command.test.ts b/plugins/altimate-code/hooks/dbt-command.test.ts new file mode 100644 index 00000000..e399b130 --- /dev/null +++ b/plugins/altimate-code/hooks/dbt-command.test.ts @@ -0,0 +1,360 @@ +import { expect, test } from 'claude-code/testing' + +import { parseDbtCommand } from './dbt-command' + +/** The fields a caller decides on, without the offsets. */ +const shape = (line: string) => parseDbtCommand(line).map(({ start, end, subcommandEnd, ...rest }) => rest) + +const base = { select: [], target: null, targetPath: null, hasDefer: false, hasState: false, dynamic: false } + +test('a plain dbt command: subcommand, selections, target and target path', () => { + expect(shape('dbt build -s stg_orders --select +fct_orders -t prod --target-path tgt')).toEqual([ + { ...base, binary: 'dbt', subcommand: 'build', select: ['stg_orders', '+fct_orders'], target: 'prod', targetPath: 'tgt' }, + ]) + expect(shape('dbt run --models a b --target=dev')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['a', 'b'], target: 'dev' }]) +}) + +test('commands joined with &&, ; and pipes each give their dbt invocation, in order', () => { + expect(shape('cd jaffle && dbt deps && dbt run -s a; dbt test | tee log.txt')).toEqual([ + { ...base, binary: 'dbt', subcommand: 'deps' }, + { ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }, + { ...base, binary: 'dbt', subcommand: 'test' }, + ]) +}) + +test('uv run dbt, poetry run dbt and a path to dbt are dbt launchers', () => { + expect(shape('uv run dbt build -s a')).toEqual([{ ...base, binary: 'uv run dbt', subcommand: 'build', select: ['a'] }]) + expect(shape('poetry run dbt test')).toEqual([{ ...base, binary: 'poetry run dbt', subcommand: 'test' }]) + expect(shape('.venv/bin/dbt compile')).toEqual([{ ...base, binary: '.venv/bin/dbt', subcommand: 'compile' }]) +}) + +test('VAR=x in front of dbt is kept in the invocation; DBT_DEFER and DBT_STATE count as defer and state', () => { + const line = 'DBT_PROFILES_DIR=. dbt run -s a' + const [one] = parseDbtCommand(line) + expect(one).toEqual({ ...base, binary: 'dbt', subcommand: 'run', select: ['a'], start: 0, end: line.length, subcommandEnd: line.indexOf(' -s') }) + expect(shape('DBT_DEFER=1 DBT_STATE=prod dbt run')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', hasDefer: true, hasState: true }]) +}) + +test('--defer and --state are seen; the offsets cut the invocation out of the line', () => { + const line = 'echo hi && dbt build --defer --state prod-artifacts -s a > out.log' + const [one] = parseDbtCommand(line) + expect(one).toMatchObject({ subcommand: 'build', hasDefer: true, hasState: true }) + expect(line.slice(one!.start, one!.end)).toBe('dbt build --defer --state prod-artifacts -s a') + expect(line.slice(one!.start, one!.subcommandEnd)).toBe('dbt build') +}) + +test('a line without dbt, or one that cannot be read, gives no invocation', () => { + expect(parseDbtCommand('ls -la && git status')).toEqual([]) + expect(parseDbtCommand('echo "dbt run')).toEqual([]) + expect(parseDbtCommand('dbt run $(echo')).toEqual([]) + expect(parseDbtCommand('')).toEqual([]) + expect(parseDbtCommand('grep dbt run.log')).toEqual([]) +}) + +test('a bare dbt has no subcommand; quoted selections are unquoted', () => { + expect(shape('dbt')).toEqual([{ ...base, binary: 'dbt', subcommand: null }]) + expect(shape(`dbt ls -s "tag:nightly" --select 'path:models/staging'`)).toEqual([ + { ...base, binary: 'dbt', subcommand: 'ls', select: ['tag:nightly', 'path:models/staging'] }, + ]) +}) + +test('a heredoc, or an operator or redirection with nothing after it, makes the line unreadable', () => { + expect(parseDbtCommand('cat > run.sh < x.sh\ndbt build\nEOF\nbash x.sh")).toEqual([]) + expect(parseDbtCommand('cat <<-EOF\n\tdbt run\n\tEOF')).toEqual([]) + for (const line of ['dbt run >', 'dbt run &&', 'dbt run |', '&& dbt run', '; dbt run', 'dbt run )', 'dbt run (', '(dbt run', 'dbt run ; ;']) + expect(parseDbtCommand(line)).toEqual([]) + // A here-string is no heredoc; a subshell, a function and a trailing ; or & are fine. + expect(shape('dbt run <<< y')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run' }]) + expect(shape('(cd a && dbt run); f() { dbt test; }; dbt ls &')).toEqual([ + { ...base, binary: 'dbt', subcommand: 'run' }, + { ...base, binary: 'dbt', subcommand: 'test' }, + { ...base, binary: 'dbt', subcommand: 'ls' }, + ]) +}) + +test('parentheses inside a quoted string in a substitution are text', () => { + expect(shape('dbt run $(printf "(") -t dev')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', target: 'dev', dynamic: true }]) + expect(shape('dbt run "$(printf ")")" -t dev')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', target: 'dev', dynamic: true }]) +}) + +test('short options joined to their value, and global options that take one before the subcommand', () => { + expect(shape('dbt run -tprod -sorders -musers')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['orders', 'users'], target: 'prod' }]) + expect(shape(`dbt --warn-error-options '{"include":"all"}' -r timing.txt run -s a`)).toEqual([ + { ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }, + ]) + expect(shape('dbt build --indirect-selection cautious -s a')).toEqual([{ ...base, binary: 'dbt', subcommand: 'build', select: ['a'] }]) +}) + +test('env options that take a value; DBT_TARGET and DBT_TARGET_PATH in front of dbt, which the flags override', () => { + expect(shape('env FOO=1 dbt run')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run' }]) + expect(shape('DBT_TARGET=prod DBT_TARGET_PATH=tgt dbt run')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', target: 'prod', targetPath: 'tgt' }]) + expect(shape('DBT_TARGET=prod dbt run -t dev')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', target: 'dev' }]) +}) + +test('subshells after a keyword, case patterns, process substitution, arrays and arithmetic are read', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('time (dbt build)')).toEqual([{ ...base, binary: 'dbt', subcommand: 'build' }]) + for (const line of [ + 'if (cd proj && dbt run); then echo ok; fi', + '! (dbt run)', + '{ (dbt run); }', + 'dbt run 2> >(tee err.log)', + 'for ((i=0;i<3;i++)); do dbt run; done', + 'f() ( dbt run )', + 'case $t in\n a|b) dbt run;;\nesac', + ]) + expect(shape(line)).toEqual([run]) + expect(shape('case $t in prod) dbt run -t prod;; *) dbt run;; esac')).toEqual([{ ...run, target: 'prod' }, run]) + expect(shape('case $t in (prod) dbt run -t prod;; esac')).toEqual([{ ...run, target: 'prod' }]) + expect(shape('models=(orders users); for m in "${models[@]}"; do dbt run -s $m; done')).toEqual([{ ...run, dynamic: true }]) + const line = 'diff <(dbt ls -s a) <(dbt ls -s b)' + const found = parseDbtCommand(line) + expect(found.map(({ start, end }) => line.slice(start, end))).toEqual(['dbt ls -s a', 'dbt ls -s b']) +}) + +test('a function definition takes one name: `dbt run ()` is unreadable and a function named dbt is no invocation', () => { + expect(parseDbtCommand('dbt run ()')).toEqual([]) + expect(parseDbtCommand('case x in a) dbt run')).toEqual([]) + expect(shape('dbt() { echo hi; }; dbt test')).toEqual([{ ...base, binary: 'dbt', subcommand: 'test' }]) + expect(shape('function f() { dbt run; }')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run' }]) +}) + +test('a case pattern named dbt is no invocation', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + for (const line of ['case $t in a) x;; dbt) dbt run;; esac', 'case $t in a|dbt) dbt run;; esac', 'case $t in (dbt) dbt run;; esac']) + expect(shape(line)).toEqual([run]) +}) + +test("quotes in a heredoc inside a substitution are text, so Claude's commit form stays readable", () => { + const line = `dbt run -s a && git commit -m "$(cat <<'EOF'\nfix "foo it's\nEOF\n)"` + expect(shape(line)).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }]) +}) + +test('the commands of a `$(…)` or backtick substitution run too, quoted or not, nested or not', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('echo "$(dbt run -s orders)"')).toEqual([{ ...run, select: ['orders'] }]) + expect(shape('echo `dbt run`')).toEqual([run]) + expect(shape('x=$(dbt build); dbt test')).toEqual([ + { ...base, binary: 'dbt', subcommand: 'build' }, + { ...base, binary: 'dbt', subcommand: 'test' }, + ]) + expect(shape('echo $(echo $(dbt run))')).toEqual([run]) + expect(shape("echo '$(dbt run)'")).toEqual([]) + const line = 'echo "$(dbt run -s a)"' + expect(parseDbtCommand(line).map(({ start, end }) => line.slice(start, end))).toEqual(['dbt run -s a']) +}) + +test('quotes decide what a substitution is: an apostrophe inside double quotes hides nothing, single quotes hide it, and the commands come in the order written', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape(`echo "it's $(dbt run)"`)).toEqual([run]) + expect(shape(`echo "it's"'$(dbt run)'`)).toEqual([]) + expect(shape('dbt run --vars "$(dbt ls)"').map(i => i.subcommand)).toEqual(['run', 'ls']) + // A substitution in a leading assignment is written before the command it feeds. + expect(shape('TARGET=$(dbt run-operation get_target) dbt run').map(i => i.subcommand)).toEqual(['run-operation', 'run']) +}) + +test('a here-string inside a substitution is no heredoc', () => { + const line = `dbt run -s a && echo "$(cat <<< text\n)"` + expect(shape(line)).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }]) +}) + +test('a heredoc right after an escaped < is still a heredoc, so its quotes are text', () => { + const line = `dbt run -s a && echo "$(cat \\<<<'EOF'\nit's\nEOF\n)"` + expect(shape(line)).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }]) +}) + +test('the offsets leave out the keywords and prefix commands in front of dbt, but keep its assignments', () => { + const cut = (line: string) => parseDbtCommand(line).map(inv => line.slice(inv.start, inv.end)) + expect(cut('if dbt run; then echo ok; fi')).toEqual(['dbt run']) + expect(cut('time dbt run -s a')).toEqual(['dbt run -s a']) + expect(cut('! nohup dbt test')).toEqual(['dbt test']) + expect(cut('env DBT_TARGET=prod dbt run -s a')).toEqual(['DBT_TARGET=prod dbt run -s a']) + expect(cut('env X=1 Y=2 dbt build')).toEqual(['X=1 Y=2 dbt build']) + expect(cut('X=1 nohup dbt run')).toEqual(['dbt run']) + // Splicing a rewrite in keeps the line valid shell. + const line = 'if dbt run; then echo ok; fi' + const [one] = parseDbtCommand(line) + expect(line.slice(0, one!.start) + 'dbt run --target dev' + line.slice(one!.end)).toBe('if dbt run --target dev; then echo ok; fi') +}) + +test('prefix options: a lookup, env with options and a NAME=value after a wrapper are no invocation', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + for (const line of [ + 'command -v dbt run', + 'command -V dbt run', + 'env -u X dbt run', + 'env -i dbt run', + 'env -S "dbt run" dbt run', + 'env -u HOME X=1 dbt build', + 'DBT_TARGET=prod env -u DBT_TARGET dbt build', + 'nohup X=1 dbt run', + 'command X=1 dbt run', + 'exec X=1 dbt run', + ]) + expect(parseDbtCommand(line)).toEqual([]) + // `command -p` and `command --` still run the command; assignments after env's or a keyword stay assignments. + expect(shape('command -p dbt run')).toEqual([run]) + expect(shape('command -- dbt run')).toEqual([run]) + expect(shape('env -- dbt run')).toEqual([run]) + expect(shape('env X=1 Y=2 dbt run')).toEqual([run]) + expect(shape('if X=1 dbt run; then :; fi')).toEqual([run]) + expect(shape('time DBT_TARGET=prod dbt run')).toEqual([{ ...run, target: 'prod' }]) + expect(shape('env DBT_TARGET=prod dbt run')).toEqual([{ ...run, target: 'prod' }]) +}) + +test('a prefix or launcher option outside its grammar is no invocation: what runs is not known', () => { + for (const line of [ + 'command --help dbt run', + 'command -x dbt run', + 'command -pv dbt run', + 'nohup --help dbt run', + 'nohup -x dbt run', + 'exec -x dbt run', + 'time -x dbt run', + 'time -f %e dbt run', + 'time -- dbt run', + 'if -x dbt run; then :; fi', + 'uv run -- --project x dbt run', + 'poetry run -- --foo dbt run', + 'uv run --foo dbt run', + 'uv run --help dbt run', + 'uv run -h dbt run', + 'uvx --version dbt run', + 'pdm run -l dbt run', + // `exec -c` clears the environment, so the assignments in front are not what dbt sees. + 'DBT_TARGET=prod DBT_STATE=a DBT_DEFER=1 exec -c dbt build', + 'exec -cl dbt run', + // Each launcher reads only its own options. + 'uv run --no-interaction dbt run', + 'uv run --ansi dbt run', + 'poetry run --frozen dbt run', + 'pipenv run -q dbt run', + 'hatch run --project x dbt run', + ]) + expect(parseDbtCommand(line)).toEqual([]) + const run = { ...base, subcommand: 'run' } + // Each prefix's own options are read. + expect(shape('exec -a mydbt dbt run')).toEqual([{ ...run, binary: 'dbt' }]) + expect(shape('exec -l dbt run')).toEqual([{ ...run, binary: 'dbt' }]) + expect(shape('time -p dbt run')).toEqual([{ ...run, binary: 'dbt' }]) + expect(shape('nohup -- dbt run')).toEqual([{ ...run, binary: 'dbt' }]) + // Known launcher options, with or without `=`, and `--` before dbt. + expect(shape('uv run --project x --frozen -qq dbt run')).toEqual([{ ...run, binary: 'uv run --project x --frozen -qq dbt' }]) + expect(shape('uv run --with=dbt-duckdb -- dbt run')).toEqual([{ ...run, binary: 'uv run --with=dbt-duckdb -- dbt' }]) + expect(shape('poetry run -P x dbt run')).toEqual([{ ...run, binary: 'poetry run -P x dbt' }]) + expect(shape('poetry run -n -vv dbt run')).toEqual([{ ...run, binary: 'poetry run -n -vv dbt' }]) + expect(shape('pdm run -p x dbt run')).toEqual([{ ...run, binary: 'pdm run -p x dbt' }]) + expect(shape('uvx --from dbt-core dbt run')).toEqual([{ ...run, binary: 'uvx --from dbt-core dbt' }]) +}) + +test('a keyword where it is a program name is no invocation; time is a real program', () => { + for (const line of ['env if dbt run', 'env then dbt run', 'env ! dbt run', 'nohup ! dbt run', 'env X=1 if dbt run', 'X=1 if dbt run', 'nohup command dbt run', 'env exec dbt run']) + expect(parseDbtCommand(line)).toEqual([]) + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('nohup time dbt run')).toEqual([run]) + expect(shape('env nohup dbt run')).toEqual([run]) + expect(shape('command exec dbt run')).toEqual([run]) +}) + +test('a backslash ending the line makes it unreadable, so no offset passes its end', () => { + expect(parseDbtCommand('DBT_TARGET=x dbt test\\')).toEqual([]) + expect(parseDbtCommand('dbt run \\')).toEqual([]) + // A backslash-newline is a line continuation, still read. + expect(shape('dbt run \\\n-s a')).toEqual([{ ...base, binary: 'dbt', subcommand: 'run', select: ['a'] }]) +}) + +test('a quoted word is never an assignment, a keyword or a prefix command, but a quoted dbt is dbt', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(parseDbtCommand('"DBT_TARGET=prod" dbt run')).toEqual([]) + expect(parseDbtCommand("'DBT_TARGET=prod' dbt run")).toEqual([]) + expect(parseDbtCommand('DBT_\\TARGET=prod dbt run')).toEqual([]) + expect(parseDbtCommand('"if" dbt run')).toEqual([]) + expect(parseDbtCommand('"nohup" dbt run')).toEqual([]) + expect(parseDbtCommand("$'time' dbt run")).toEqual([]) + expect(shape('"dbt" run')).toEqual([run]) + // A quoted value is still an assignment's value. + expect(shape('DBT_TARGET="prod" dbt run')).toEqual([{ ...run, target: 'prod' }]) +}) + +test('an expansion is part of its word, and the invocation is dynamic; its values are never reported', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('dbt run --target "$DBT_TARGET"')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -t $T --target-path ${P:-a b}')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -s "$(printf orders)"')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -s $(printf a b)')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -s `echo a b` -s c')).toEqual([{ ...run, dynamic: true, select: ['c'] }]) + expect(shape('for m in a b; do dbt run -s $m; done')).toEqual([{ ...run, dynamic: true }]) + expect(shape('DBT_TARGET=$T dbt run')).toEqual([{ ...run, dynamic: true }]) + // An expansion in an assignment ahead of a prefix word still reaches dbt's environment. + expect(shape('DBT_TARGET=$T time dbt run')).toEqual([{ ...run, dynamic: true }]) + expect(shape('DBT_TARGET_PATH=$P nohup dbt run')).toEqual([{ ...run, dynamic: true }]) + expect(shape('DBT_TARGET=prod time dbt run')).toEqual([{ ...run, target: 'prod' }]) + // The flag wins over the environment, but a dynamic flag value is unknown, not the environment's. + expect(shape('DBT_TARGET=prod dbt run --target "$T"')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run --select=a,$x -s b')).toEqual([{ ...run, dynamic: true, select: ['b'] }]) + // Single quotes and escapes hold no expansion. + expect(shape("dbt run -s '$literal'")).toEqual([{ ...run, select: ['$literal'] }]) + expect(shape('dbt run -s \\$literal')).toEqual([{ ...run, select: ['$literal'] }]) + // A bare $ is text; an expansion in the binary or the subcommand is no invocation. + expect(shape('dbt run -s a$')).toEqual([{ ...run, select: ['a$'] }]) + expect(parseDbtCommand('dbt $CMD')).toEqual([]) + expect(parseDbtCommand('dbt "$(echo run)" -s a')).toEqual([]) + expect(parseDbtCommand('$(which dbt) run')).toEqual([]) + expect(parseDbtCommand('"$DBT" run')).toEqual([]) + // An unclosed ${ is unreadable. + expect(parseDbtCommand('dbt run -s ${a')).toEqual([]) +}) + +test('a redirection among the arguments with an argument after it is unsupported; a trailing one is left out of the range', () => { + for (const line of ['dbt run > run.log -s orders', 'dbt run 2>/dev/null --target dev', 'DBT_TARGET=a > log dbt run']) + expect(parseDbtCommand(line)).toEqual([]) + for (const line of ['dbt run -s orders > run.log', 'dbt run -s orders 2>&1 | tee x', 'dbt run -s orders >> run.log 2>&1']) { + const [one] = parseDbtCommand(line) + expect(line.slice(one!.start, one!.end)).toBe('dbt run -s orders') + expect(one!.select).toEqual(['orders']) + } + const lead = 'time 2>/dev/null dbt run -s a' + const [front] = parseDbtCommand(lead) + expect(lead.slice(front!.start, front!.end)).toBe('dbt run -s a') +}) + +test('global options that take a value come before the subcommand, and an unknown word does not hide the subcommand', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('dbt --partial-parse-file-path p run')).toEqual([run]) + expect(shape('dbt --packages-install-path pk --partial-parse-file-path=p run -s a')).toEqual([{ ...run, select: ['a'] }]) + // A flag this list does not know, with its value, in front of the subcommand. + expect(shape('dbt --some-new-option value build -s a')).toEqual([{ ...base, binary: 'dbt', subcommand: 'build', select: ['a'] }]) + const line = 'dbt --some-new-option value test' + const [one] = parseDbtCommand(line) + expect(line.slice(one!.start, one!.subcommandEnd)).toBe(line) + // No known subcommand: the first word is reported, as before. + expect(shape('dbt frobnicate')).toEqual([{ ...base, binary: 'dbt', subcommand: 'frobnicate' }]) +}) + +test('a backslash in double quotes is kept unless it escapes $, a backtick, a quote, a backslash or a newline', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('dbt run --target-path "target\\compiled"')).toEqual([{ ...run, targetPath: 'target\\compiled' }]) + expect(shape('dbt run -t "p\\"rod" ')).toEqual([{ ...run, target: 'p"rod' }]) + expect(shape('dbt run -t "pro\\\nd"')).toEqual([{ ...run, target: 'prod' }]) + expect(shape('dbt run -t pro\\\nd')).toEqual([{ ...run, target: 'prod' }]) +}) + +test('a $\'…\' word with an escape is not decoded: it is dynamic and reports no value', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape("dbt run -t $'pro\\x64'")).toEqual([{ ...run, dynamic: true }]) + expect(shape("dbt run -t $'prod'")).toEqual([{ ...run, target: 'prod' }]) +}) + +test('unquoted tilde, brace lists and patterns are expansions; $"…" is a quoted string; launcher help runs nothing', () => { + const run = { ...base, binary: 'dbt', subcommand: 'run' } + expect(shape('dbt run --target-path ~/dbt-target')).toEqual([{ ...run, dynamic: true }]) + expect(shape('DBT_TARGET_PATH=~/x dbt run')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -s {orders,users}')).toEqual([{ ...run, dynamic: true }]) + expect(shape('dbt run -s models/*.sql -t dev')).toEqual([{ ...run, dynamic: true, target: 'dev' }]) + expect(shape('dbt run -s "{orders,users}" --target-path "~/x" -t \\~')).toEqual([{ ...run, select: ['{orders,users}'], targetPath: '~/x', target: '~' }]) + expect(shape('dbt run -t $"prod"')).toEqual([{ ...run, target: 'prod' }]) + expect(shape('dbt run -t $-')).toEqual([{ ...run, dynamic: true }]) + expect(parseDbtCommand('uv run --help dbt run')).toEqual([]) + expect(parseDbtCommand('uvx --version dbt run')).toEqual([]) +}) diff --git a/plugins/altimate-code/hooks/dbt-command.ts b/plugins/altimate-code/hooks/dbt-command.ts new file mode 100644 index 00000000..d70adbf6 --- /dev/null +++ b/plugins/altimate-code/hooks/dbt-command.ts @@ -0,0 +1,854 @@ +// The dbt invocations in a shell command line, as Claude's Bash calls write them: `dbt build -s x`, +// `cd a && dbt run`, `uv run dbt test | tee log`, `DBT_PROFILES_DIR=. dbt run`. Each comes with its +// place in the line, so a caller can rewrite one without touching the rest. +// +// Supported-input contract: parseDbtCommand reports an invocation only when the static text shows dbt +// will start; when in doubt it returns no invocation, and values it cannot read statically are never +// reported as literal values. In particular, these give no invocation: +// - a line that can't be read (an unclosed quote, substitution or parenthesis, an operator or +// redirection with nothing after it, a heredoc outside a `$(…)` substitution); +// - a prefix word with an option outside its grammar. Only these are read: `command -p`, `exec -l`, +// `exec -a NAME`, `time -p`, and `--` after `command`, `exec`, `nohup` or `env`. So `command -v +// dbt …` (a lookup), `command --help dbt run`, `nohup --help dbt run`, `exec -c …` and `env -i …` +// (they clear the environment), `env -u X …` and `time -f …` give none; `env` with only +// NAME=value words (and `--`) is read; +// - an option outside the grammar of that launcher's `run` (`uv`, `uvx`, `poetry`, `pipenv`, `pdm`, +// `hatch`, `rye`; each has its own table): an unknown option may take a value, or print help or a +// version, so what runs is not known; and a word other than dbt after the launcher's `--` +// (`uv run -- --project x dbt run`); +// - a NAME=value word right after `nohup`, `command`, `exec` (it is the command's name, not an +// assignment), and a quoted NAME=value or quoted shell keyword (`"DBT_TARGET=prod" dbt run`, +// `"if" dbt run`), which is a command's name too; +// - a shell keyword other than `time` where it is a program's name, not a keyword: after a prefix +// command (`env if dbt run`, `nohup ! dbt run`) or after an assignment (`X=1 if dbt run`); and +// `command` or `exec` (shell builtins) as the program `env` or `nohup` runs; +// - a backslash as the line's last character; +// - a binary or subcommand word that holds an expansion (`dbt $CMD`, `$(which dbt) run`); +// - a redirection among the arguments with another argument after it (`dbt run > log -s a`): an +// unsupported form, since cutting the invocation out would cut the redirection too. A trailing +// redirection (`dbt run -s a > log`) is fine and is left out of the invocation's range. +// An expansion is `$(…)`, `${…}`, `$NAME`, `$1`, a backtick command, a `<(…)` / `>(…)` substitution, an +// unquoted `~`, brace list or pathname pattern, or a `$'…'` word with an escape, outside single quotes; +// a word holding one is a single word, whatever it holds. + +// Only what is written on the command is read: a DBT_TARGET exported earlier, inherited from the +// session or loaded by a launcher (`uv run --env-file .env`) is not seen, so a null target or target +// path means "none written here", not "none". +export type DbtInvocation = { + /** How dbt is launched, as written: `dbt`, `.venv/bin/dbt`, `uv run dbt`, `poetry run dbt`. */ + binary: string + /** The first known dbt subcommand after the launcher's options (`build`, `run`, `test`…); else the first other word; null when there is none. */ + subcommand: string | null + /** + * Every value given to -s, --select, -m, --models or --model, in order. A value that holds an expansion + * is left out, so when `dynamic` is true this list is unknown, not complete. + */ + select: string[] + /** + * The value of -t or --target, else of DBT_TARGET set in front of the command; null when neither, and + * null when the value holds an expansion. When `dynamic` is true it is unknown, not "none". + */ + target: string | null + /** + * The value of --target-path, else of DBT_TARGET_PATH set in front of the command; null when neither, + * and null when the value holds an expansion. When `dynamic` is true it is unknown, not "none". + */ + targetPath: string | null + /** + * Some word of the invocation (its leading assignments, launcher, flags or flag values) holds an + * expansion, so what the shell passes to dbt is not what the text says. A consumer treats `select`, + * `target` and `targetPath` of such an invocation as unknown, and does not rewrite it on their strength. + */ + dynamic: boolean + /** --defer or --no-defer is given, or DBT_DEFER is set in front of the command. */ + hasDefer: boolean + /** --state or --defer-state is given, or DBT_STATE / DBT_DEFER_STATE is set in front of the command. */ + hasState: boolean + /** + * Offset of the invocation's first character: its leading VAR=x assignments included, the shell + * keywords and prefix commands in front of them (`if`, `then`, `!`, `time`, `nohup`, `env` and its + * options) not, so `line.slice(start, end)` can be replaced without breaking what surrounds it. + */ + start: number + /** Offset just past its last argument (redirections and what follows a pipe excluded). */ + end: number + /** Offset just past the subcommand (past `binary` when there is none): where flags can be inserted. */ + subcommandEnd: number +} + +type Word = { + kind: 'word' + text: string + start: number + end: number + /** + * Where in `text` the first quoted part (single, double, `$'…'` or a backslash escape) begins; -1 when + * no part is quoted. A NAME=value word is an assignment only when its `=` comes before it. + */ + quotedAt: number + /** An expansion outside single quotes, or a `$'…'` holding an escape: `$(…)`, `${…}`, `$NAME`, `$1`, a backtick command, `<(…)`, `~/x`, `{a,b}`, `*.sql`. */ + dynamic: boolean +} +type Token = Word | { kind: 'op'; text: string; start: number; end: number } + +const OPERATORS = ['&&', '||', ';;', '|&', '|', '&', ';', '(', ')', '\n'] +const ARRAY_ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*(?:\[[^\]]*\])?\+?=$/ +const REDIRECT = /^(?:\d*(?:>>|>&|>\||>|<&|<<<|<<|<>|<)|&>>?)/ + +const HEREDOC = /^<<(-?)[ \t]*(?:'([^'\n]*)'|"([^"\n]*)"|([^\s;&|()<>'"]+))/ + +/** + * Offset of the newline that ends a heredoc's closing delimiter line, where `from` is the newline before + * the body; -1 when the delimiter never comes or nothing follows it. + */ +function heredocBodyEnd(line: string, from: number, delimiter: string, strip: boolean): number { + for (let at = from + 1; ; ) { + const eol = line.indexOf('\n', at) + if (eol < 0) return -1 + const row = line.slice(at, eol) + if ((strip ? row.replace(/^\t+/, '') : row) === delimiter) return eol + at = eol + 1 + } +} + +/** Offset just past the `$(…)` or backtick substitution that opens at `at`; -1 when it is not closed. */ +function substitutionEnd(line: string, at: number): number { + if (line[at] === '`') { + const close = line.indexOf('`', at + 1) + return close < 0 ? -1 : close + 1 + } + // `at` is the opening parenthesis: it counts as the first level. + let depth = 0 + // Heredocs opened on the line being read; their bodies start on the next line. + const heredocs: { delimiter: string; strip: boolean }[] = [] + for (let j = at; j < line.length; j++) { + const c = line[j] + if (c === '\n' && heredocs.length) { + for (const { delimiter, strip } of heredocs.splice(0)) { + j = heredocBodyEnd(line, j, delimiter, strip) + if (j < 0) return -1 + } + } else if (c === '<' && line[j + 1] === '<' && line[j + 2] === '<') { + // A here-string: its word is read as ordinary text, and its `<<` is no heredoc. + j += 2 + } else if (c === '<' && line[j + 1] === '<') { + // A heredoc's body is text: its quotes and parentheses are not read. + const heredoc = HEREDOC.exec(line.slice(j)) + if (heredoc) { + heredocs.push({ delimiter: heredoc[2] ?? heredoc[3] ?? heredoc[4]!, strip: heredoc[1] === '-' }) + j += heredoc[0].length - 1 + } + } else if (c === '\\') j++ + else if (c === "'") { + j = line.indexOf("'", j + 1) + if (j < 0) return -1 + } else if (c === '"') { + // A double-quoted string: its parentheses are text, but a substitution inside it still nests. + for (j++; j < line.length && line[j] !== '"'; j++) { + if (line[j] === '\\') j++ + else if (line[j] === '$' && line[j + 1] === '(') { + const end = substitutionEnd(line, j + 1) + if (end < 0) return -1 + j = end - 1 + } + } + if (j >= line.length) return -1 + } else if (c === '(') depth++ + else if (c === ')' && --depth === 0) return j + 1 + } + return -1 +} + +/** Offset just past the `${…}` whose `{` is at `at`; -1 when it is not closed. */ +function braceEnd(line: string, at: number): number { + let depth = 0 + for (let j = at; j < line.length; j++) { + const c = line[j] + if (c === '\\') j++ + else if (c === "'") { + j = line.indexOf("'", j + 1) + if (j < 0) return -1 + } else if (c === '"') { + for (j++; j < line.length && line[j] !== '"'; j++) { + if (line[j] === '\\') j++ + else if (line[j] === '$' && line[j + 1] === '(') { + const end = substitutionEnd(line, j + 1) + if (end < 0) return -1 + j = end - 1 + } + } + if (j >= line.length) return -1 + } else if (c === '$' && line[j + 1] === '(') { + const end = substitutionEnd(line, j + 1) + if (end < 0) return -1 + j = end - 1 + } else if (c === '{') depth++ + else if (c === '}' && --depth === 0) return j + 1 + } + return -1 +} + +/** A `$` that opens a variable: a name, a digit or one of the special parameters. */ +const startsVariable = (next: string | undefined) => next !== undefined && /[A-Za-z0-9_@*#?!$-]/.test(next) + +/** The words and operators of a command line, with their offsets; null when a quote or substitution is not closed. */ +function lex(line: string): Token[] | null { + const tokens: Token[] = [] + let i = 0 + let text = '' + let start = -1 + let quotedAt = -1 + let dynamic = false + const flush = (end: number) => { + if (start >= 0) tokens.push({ kind: 'word', text, start, end, quotedAt, dynamic }) + text = '' + start = -1 + quotedAt = -1 + dynamic = false + } + // A quoted part is about to add to `text`. + const quote = () => { + if (quotedAt < 0) quotedAt = text.length + } + while (i < line.length) { + const c = line[i]! + if (c === '\\' && line[i + 1] === '\n') { + i += 2 + continue + } + if (c === ' ' || c === '\t' || c === '\r') { + flush(i) + i++ + continue + } + if (c === '#' && start < 0) { + while (i < line.length && line[i] !== '\n') i++ + continue + } + // `<(…)` and `>(…)` (process substitution), `((…))` (arithmetic) and the `(…)` of `name=(…)` (an + // array) are one word, up to the matching parenthesis. + const paren = + (c === '<' || c === '>') && line[i + 1] === '(' && start < 0 + ? i + 1 + : c === '(' && (start < 0 ? line[i + 1] === '(' : quotedAt < 0 && ARRAY_ASSIGNMENT.test(text)) + ? i + : -1 + if (paren >= 0) { + const end = substitutionEnd(line, paren) + if (end < 0) return null + if (start < 0) start = i + // A process substitution's value is a path the shell makes up. + if (c === '<' || c === '>') dynamic = true + text += line.slice(i, end) + i = end + continue + } + const redirect = REDIRECT.exec(line.slice(i)) + if (redirect && (start < 0 || !/^\d/.test(redirect[0]))) { + flush(i) + tokens.push({ kind: 'op', text: redirect[0], start: i, end: i + redirect[0].length }) + i += redirect[0].length + continue + } + const op = OPERATORS.find(one => line.startsWith(one, i)) + if (op) { + flush(i) + tokens.push({ kind: 'op', text: op, start: i, end: i + op.length }) + i += op.length + continue + } + if (start < 0) start = i + if (c === '\\') { + // A backslash ending the line escapes nothing the shell can read here; inserting after it would + // be escaped. + if (i + 1 >= line.length) return null + quote() + text += line[i + 1]! + i += 2 + } else if (c === "'") { + const close = line.indexOf("'", i + 1) + if (close < 0) return null + quote() + text += line.slice(i + 1, close) + i = close + 1 + } else if (c === '$' && line[i + 1] === "'") { + // `$'…'`: a quoted string in which a backslash escapes the next character. Escapes (`\x64`, `\n`) + // are not decoded here, so a word that holds one is dynamic and its value is not reported. + let j = i + 2 + while (j < line.length && line[j] !== "'") j += line[j] === '\\' ? 2 : 1 + if (j >= line.length) return null + quote() + const body = line.slice(i + 2, j) + if (body.includes('\\')) dynamic = true + text += body + i = j + 1 + } else if (c === '$' && line[i + 1] === '"') { + // `$"…"` is a double-quoted string: the `$` is not part of the word. + i++ + } else if (c === '"') { + quote() + let j = i + 1 + while (j < line.length && line[j] !== '"') { + if (line[j] === '\\' && j + 1 < line.length) { + // Inside double quotes a backslash only escapes `$`, a backtick, `"`, `\` and a newline. + const next = line[j + 1] ?? '' + if (next === '\n') { + // line continuation: nothing is added + } else if ('$`"\\'.includes(next)) text += next + else text += '\\' + next + j += 2 + } else if ((line[j] === '$' && line[j + 1] === '(') || line[j] === '`') { + const end = substitutionEnd(line, line[j] === '$' ? j + 1 : j) + if (end < 0) return null + dynamic = true + text += line.slice(j, end) + j = end + } else if (line[j] === '$' && line[j + 1] === '{') { + const end = braceEnd(line, j + 1) + if (end < 0) return null + dynamic = true + text += line.slice(j, end) + j = end + } else { + if (line[j] === '$' && startsVariable(line[j + 1])) dynamic = true + text += line[j++] + } + } + if (j >= line.length) return null + i = j + 1 + } else if ((c === '$' && line[i + 1] === '(') || c === '`') { + const end = substitutionEnd(line, c === '$' ? i + 1 : i) + if (end < 0) return null + dynamic = true + text += line.slice(i, end) + i = end + } else if (c === '$' && line[i + 1] === '{') { + const end = braceEnd(line, i + 1) + if (end < 0) return null + dynamic = true + text += line.slice(i, end) + i = end + } else { + if (c === '$' && startsVariable(line[i + 1])) dynamic = true + // The shell expands these before dbt sees them: a home directory, a brace list, a pathname pattern. + if (c === '*' || c === '?' || c === '[') dynamic = true + // (also after the `=` of a NAME=value word, but not after a flag's `=`) + if (c === '~' && (i === start || /^[A-Za-z_][A-Za-z0-9_]*=$/.test(line.slice(start, i)))) dynamic = true + if (c === '{' && /^\{[^}]*(,|\.\.)[^}]*\}/.test(line.slice(i))) dynamic = true + text += c + i++ + } + } + flush(i) + return tokens +} + +const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/ +// Shell keywords after which a command still starts: assignments may follow them. +const KEYWORDS = new Set(['!', '{', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time']) +// Commands that run their first argument that is no option: a NAME=value there is the command's name. +const WRAPPERS = new Set(['command', 'exec', 'nohup', 'env']) +// The options each prefix word has: whether one takes a value. Any other option gives no invocation. +const PREFIX_OPTIONS: Record> = { + command: { '-p': 'flag' }, + // `exec -c` clears the environment dbt starts with: what it sees is not known, so it is not read. + exec: { '-l': 'flag', '-a': 'value' }, + time: { '-p': 'flag' }, +} +// Prefix words that end their options at `--`; `time` and the other keywords take no `--`. +const ENDS_AT_DASHES = new Set(['command', 'exec', 'nohup', 'env']) +// Launchers whose `run` subcommand (`uvx`: the launcher itself) runs the command after their own +// options, and the options each one's `run` takes: `flags` take no value, `values` take one. These are +// the only launcher options read: an unknown one may take a value, so which word runs is not known. +const UV_RUN_FLAGS = ['-q', '--quiet', '-v', '--verbose', '--isolated', '--offline', '--refresh', '--native-tls', '--no-config', '--no-cache'] +const UV_RUN_VALUES = ['--with', '--with-editable', '--with-requirements', '--python', '-p', '--directory', '--project', '--index', '--index-url', '--env-file'] +const RUNNER_OPTIONS: Record; values: Set }> = { + uv: { + flags: new Set([ + ...UV_RUN_FLAGS, + '--no-sync', + '--frozen', + '--locked', + '--active', + '--no-project', + '--all-extras', + '--all-packages', + '--no-dev', + '--no-env-file', + '--exact', + ]), + values: new Set([...UV_RUN_VALUES, '--extra', '--group', '--package']), + }, + uvx: { flags: new Set(UV_RUN_FLAGS), values: new Set([...UV_RUN_VALUES, '--from']) }, + poetry: { + flags: new Set(['-q', '--quiet', '-v', '--verbose', '-n', '--no-interaction', '--ansi', '--no-ansi', '--no-plugins', '--no-cache']), + values: new Set(['-P', '--project', '-C', '--directory']), + }, + pdm: { + flags: new Set(['-q', '--quiet', '-v', '--verbose', '-g', '--global', '-s', '--site-packages', '--recreate']), + values: new Set(['-p', '--project', '--venv']), + }, + rye: { flags: new Set(), values: new Set(['--pyproject']) }, + pipenv: { flags: new Set(), values: new Set() }, + hatch: { flags: new Set(), values: new Set() }, +} +// dbt options that take a value, so the value is not read as the subcommand or as a selector. +const DBT_VALUE_FLAGS = new Set([ + '--log-format', + '--log-format-file', + '--log-level', + '--log-level-file', + '--log-path', + '--profiles-dir', + '--project-dir', + '--profile', + '--target', + '-t', + '--target-path', + '--vars', + '--state', + '--defer-state', + '--threads', + '--printer-width', + '--exclude', + '--selector', + '--resource-type', + '--resource-types', + '--exclude-resource-type', + '--exclude-resource-types', + '--output', + '-o', + '--output-keys', + '--inline', + '--limit', + '--args', + '--macro', + '--warn-error-options', + '--record-timing-info', + '-r', + '--indirect-selection', + '--event-time-start', + '--event-time-end', + '--sample', + '--log-file-max-bytes', + '--add-package', + '--source', + '--partial-parse-file-path', + '--packages-install-path', +]) +// Short dbt options that take a value, which may also be written joined to it: `-tprod`, `-sorders`. +const SHORT_VALUE_FLAGS = new Set(['-s', '-m', '-t', '-o', '-r']) +const SELECT_FLAGS = new Set(['-s', '--select', '-m', '--models', '--model']) + +// dbt's subcommands: the first of these in the line is the one dbt runs. +const DBT_SUBCOMMANDS = new Set([ + 'build', + 'clean', + 'clone', + 'compile', + 'debug', + 'deps', + 'docs', + 'init', + 'list', + 'ls', + 'parse', + 'retry', + 'run', + 'run-operation', + 'seed', + 'show', + 'snapshot', + 'source', + 'test', +]) + +const isDbt = (word: string) => word.split('/').pop() === 'dbt' + +/** Whether `word` is a NAME=value assignment: a quoted part may only come after the `=`. */ +const isAssignment = (word: Word) => ASSIGNMENT.test(word.text) && (word.quotedAt < 0 || word.text.indexOf('=') < word.quotedAt) + +/** The dbt invocations in a shell command line, in the order written; [] when there are none or the line can't be read. */ +export function parseDbtCommand(line: string): DbtInvocation[] { + return scan(line).map(one => one.invocation) +} + +// An invocation with where its `dbt` word is written: leading `VAR=x` words don't move it. +type Found = { invocation: DbtInvocation; at: number } + +function scan(line: string): Found[] { + if (typeof line !== 'string' || !/\bdbt\b/.test(line)) return [] + const tokens = lex(line) + const notCommand = tokens && readable(tokens) + if (!tokens || !notCommand) return [] + const found: Found[] = [] + let simple: Token[] = [] + const finish = () => { + const read = readSimple(simple) + if (read) found.push({ invocation: read.invocation, at: read.at }) + simple = [] + } + for (let k = 0; k < tokens.length; k++) { + const token = tokens[k]! + if (notCommand.has(k)) continue + if (token.kind === 'op' && !/[<>]/.test(token.text)) finish() + else simple.push(token) + // The commands of a process substitution (`<(…)`, `>(…)`) run too: they are read as a line of their own. + if (token.kind === 'word' && /^[<>]\(/.test(line.slice(token.start, token.end))) { + const shift = token.start + 2 + for (const inner of scan(line.slice(shift, token.end - 1))) found.push(moved(inner, shift)) + } else if (token.kind === 'word') { + // So do the commands of a `$(…)` or backtick substitution in the word, outside single quotes. + for (const [from, to] of substitutionsIn(line, token.start, token.end)) { + for (const inner of scan(line.slice(from, to))) found.push(moved(inner, from)) + } + } + } + finish() + // An inner command (in a substitution) is listed where it is written, not before the command around it. + return found.sort((a, b) => a.at - b.at) +} + +const moved = ({ invocation: i, at }: Found, shift: number): Found => ({ + invocation: { ...i, start: i.start + shift, end: i.end + shift, subcommandEnd: i.subcommandEnd + shift }, + at: at + shift, +}) + +/** The commands' ranges of the `$(…)` and backtick substitutions written in line[start, end), outside single quotes. */ +function substitutionsIn(line: string, start: number, end: number): [number, number][] { + const found: [number, number][] = [] + // Single quotes hide a substitution; inside double quotes a `'` is a plain character. + let single = false + let double = false + for (let i = start; i < end; i++) { + const c = line[i] + if (single) single = c !== "'" + else if (c === '\\') i++ + else if (c === "'" && !double) single = true + else if (c === '"') double = !double + else if ((c === '$' && line[i + 1] === '(') || c === '`') { + const close = substitutionEnd(line, c === '$' ? i + 1 : i) + if (close < 0 || close > end) break + found.push([i + (c === '$' ? 2 : 1), close - 1]) + i = close - 1 + } + } + return found +} + +const isRedirect = (token: Token) => token.kind === 'op' && /[<>]/.test(token.text) + +// Words after which a command still starts, so a `(` there opens a subshell. +const COMMAND_KEYWORDS = new Set(['!', '{', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time']) +const NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/ + +/** + * Which words are not part of a command (`case` patterns, function names) when the tokens make a command + * line the shell would run; null when they don't. A line the shell would run is one where every + * redirection has a target, every `&&`, `||` and pipe has a command on both sides, `;` and `&` follow a command, parentheses pair up + * (subshells, `name()` function definitions, `case` patterns), and a `case` reaches its `esac`. A + * heredoc counts as unreadable, since its body lines are text, not commands (one inside `$(…)` is skipped + * when the substitution is read). + */ +function readable(tokens: Token[]): Set | null { + // Indices of words that are not part of a command: `case` patterns and function names. + const notCommand = new Set() + // Open subshells and `case` statements, innermost last. + const open: ('(' | 'case')[] = [] + // Words of the command being read, its leading keywords not counted; whether an operator still waits + // for a command; whether a `case` pattern is being read, up to its `)`; and how far a `case` head + // (`case WORD in`) has been read. + let words: string[] = [] + let waiting = false + let pattern = false + let caseHead: 'none' | 'case' | 'word' = 'none' + for (let k = 0; k < tokens.length; k++) { + const token = tokens[k]! + if (token.kind === 'word') { + waiting = false + // A quoted word is never a keyword. + const word = token.quotedAt >= 0 ? `\u0000${token.text}` : token.text + if (caseHead === 'case') caseHead = 'word' + else if (caseHead === 'word') { + if (word !== 'in') return null + caseHead = 'none' + pattern = true + } else if (!words.length && word === 'esac' && open.at(-1) === 'case') { + open.pop() + pattern = false + words = [token.text] + } else if (pattern) { + words.push(token.text) + notCommand.add(k) + } + else if (!words.length && word === 'case') { + open.push('case') + caseHead = 'case' + } else if (words.length || !COMMAND_KEYWORDS.has(word)) words.push(token.text) + continue + } + if (isRedirect(token)) { + if (/^\d*<<$/.test(token.text)) return null + if (tokens[k + 1]?.kind !== 'word') return null + // The target is not the command's word, but a redirection alone is a command (`> out`). + k++ + words.push(token.text) + waiting = false + continue + } + if (caseHead !== 'none' && token.text !== '\n') return null + switch (token.text) { + case '\n': + if (!waiting && !pattern) words = [] + continue + case '(': + // A pattern may open with `(`; where a command starts, `(` opens a subshell; after one name it + // defines a function, whose body follows. + if (pattern && !words.length) continue + if (!words.length) open.push('(') + else if ( + tokens[k + 1]?.text === ')' && + NAME.test(words.at(-1)!) && + (words.length === 1 || (words.length === 2 && words[0] === 'function')) + ) { + notCommand.add(k - 1) + if (words.length === 2) notCommand.add(k - 2) + k++ + words = [] + } else return null + continue + case ')': + if (pattern) { + if (!words.length) return null + pattern = false + words = [] + continue + } + if (open.at(-1) !== '(' || waiting) return null + open.pop() + words = [token.text] + continue + case ';;': + if (open.at(-1) !== 'case' || pattern) return null + words = [] + pattern = true + continue + case '|': + // Alternatives in a pattern. + if (pattern) { + if (!words.length) return null + words = [] + continue + } + // falls through + case '&&': + case '||': + case '|&': + if (!words.length || pattern) return null + words = [] + waiting = true + continue + default: + // `;` and `&` end the command before them. + if (!words.length || pattern) return null + words = [] + } + } + return !open.length && !waiting && !pattern && caseHead === 'none' ? notCommand : null +} + +function readSimple(tokens: Token[]): Found | null { + // Drop redirections and their targets: what is left is the command's words. + const words: Word[] = [] + for (let i = 0; i < tokens.length; i++) { + const token = tokens[i]! + if (token.kind === 'op') { + // A redirection takes the next word as its target (`> log`, `2>&1`). + i++ + continue + } + words.push(token) + } + if (words.length === 0) return null + // The first of the assignments right in front of the launcher; prefix words reset it. + let firstAssignment: number | null = null + let i = 0 + let hasDefer = false + let hasState = false + let envTarget: string | null = null + let envTargetPath: string | null = null + // Whether any assignment dbt is given holds an expansion; prefix words do not clear it. + let assignmentDynamic = false + // The prefix word whose options are being read (`env -u X`, `time -p`); whether it is a wrapper, after + // which the next word that is no option is the command itself. + let prefix: string | null = null + let wrapped = false + // Whether the prefix word's options may still come: not after an assignment. + let optionsOpen = false + for (; i < words.length; i++) { + const word = words[i]! + if (isAssignment(word)) { + // After `nohup`, `command` or `exec` this is the name of the command to run, not an assignment. + if (wrapped && prefix !== 'env') return null + const name = word.text.slice(0, word.text.indexOf('=')) + const assigned = word.dynamic ? null : word.text.slice(word.text.indexOf('=') + 1) + if (name === 'DBT_DEFER') hasDefer = true + if (name === 'DBT_STATE' || name === 'DBT_DEFER_STATE') hasState = true + if (name === 'DBT_TARGET') envTarget = assigned + if (name === 'DBT_TARGET_PATH') envTargetPath = assigned + if (word.dynamic) assignmentDynamic = true + firstAssignment ??= i + optionsOpen = false + continue + } + // A quoted word is a command's name, never a keyword or a prefix command. + const unquoted = word.quotedAt < 0 + if (unquoted && (KEYWORDS.has(word.text) || WRAPPERS.has(word.text))) { + // After a prefix command or an assignment, a keyword is the name of a program to run (`env if`); + // only `time` is one that exists (`X=1 time dbt run` runs the external time). + if (KEYWORDS.has(word.text) && word.text !== 'time' && (wrapped || firstAssignment !== null)) return null + // `env` and `nohup` run a program: the shell builtins `command` and `exec` are none. + if ((prefix === 'env' || prefix === 'nohup') && (word.text === 'command' || word.text === 'exec')) return null + prefix = word.text + wrapped = WRAPPERS.has(word.text) + optionsOpen = true + firstAssignment = null + continue + } + if (unquoted && word.text.startsWith('-') && prefix !== null && optionsOpen) { + if (word.text === '--' && ENDS_AT_DASHES.has(prefix)) { + // The next word is the command, or, after `env`, a NAME=value. + optionsOpen = false + firstAssignment = null + continue + } + // Only the prefix's own options are read: `command -v` looks dbt up, `env -u X` changes what dbt + // sees, and `--help` prints usage, so none of them runs dbt as written. + const takes = PREFIX_OPTIONS[prefix]?.[word.text] + if (!takes) return null + if (takes === 'value') i++ + firstAssignment = null + continue + } + break + } + if (i >= words.length) return null + const start = words[firstAssignment ?? i]!.start + const launcherStart = i + let binaryEnd: number + if (isDbt(words[i]!.text)) { + binaryEnd = i + } else if (Object.hasOwn(RUNNER_OPTIONS, words[i]!.text.split('/').pop()!)) { + const runner = words[i]!.text.split('/').pop()! + i++ + if (runner !== 'uvx') { + if (words[i]?.text !== 'run') return null + i++ + } + while (i < words.length && words[i]!.text.startsWith('-')) { + const flag = words[i]!.text + // `uv run --` ends the launcher's options: the next word is the command, whatever it looks like. + if (flag === '--') { + i++ + break + } + const name = flag.includes('=') ? flag.slice(0, flag.indexOf('=')) : flag + // An unknown option may take a value, or print help or a version and run nothing. + const options = RUNNER_OPTIONS[runner]! + // Repeated short flags (`-qq`, `-vv`) are read when the launcher has the single one. + const repeated = /^-([a-z])\1+$/.exec(flag) + if (options.values.has(name)) i += flag.includes('=') ? 1 : 2 + else if (!flag.includes('=') && (options.flags.has(flag) || (repeated && options.flags.has(`-${repeated[1]}`)))) i++ + else return null + } + if (i >= words.length || !isDbt(words[i]!.text)) return null + binaryEnd = i + } else return null + // A binary that holds an expansion is not known to be dbt. + if (words[binaryEnd]!.dynamic) return null + const end = words[words.length - 1]!.end + // A redirection among the arguments, with an argument after it, would be cut out with the invocation. + if (tokens.some(token => token.kind === 'op' && token.start > start && token.start < end)) return null + + const binary = words + .slice(launcherStart, binaryEnd + 1) + .map(one => one.text) + .join(' ') + let subcommand: string | null = null + let subcommandEnd = words[binaryEnd]!.end + // The first word that is no option, used when none is a known subcommand. + let firstOther: Word | null = null + const select: string[] = [] + let target: string | null = null + let targetPath: string | null = null + // A target or target path given by a value that holds an expansion: unknown, so null whatever else says. + let targetDynamic = false + let targetPathDynamic = false + let selecting = false + for (let j = binaryEnd + 1; j < words.length; j++) { + const current = words[j]! + const word = current.text + if (word.startsWith('-')) { + selecting = false + const eq = word.indexOf('=') + const joined = !word.startsWith('--') && word.length > 2 && SHORT_VALUE_FLAGS.has(word.slice(0, 2)) + const flag = joined ? word.slice(0, 2) : eq > 0 ? word.slice(0, eq) : word + const inline = joined ? word.slice(2) : eq > 0 ? word.slice(eq + 1) : null + // The flag's value and whether it holds an expansion (null value: none given). + const value = (): { text: string | null; dynamic: boolean } => { + if (inline !== null) return { text: inline, dynamic: current.dynamic } + j++ + return { text: words[j]?.text ?? null, dynamic: words[j]?.dynamic ?? false } + } + if (SELECT_FLAGS.has(flag)) { + if (inline !== null && !current.dynamic) select.push(...inline.split(/\s+/).filter(Boolean)) + selecting = true + } else if (flag === '-t' || flag === '--target') { + const given = value() + target = given.dynamic ? null : given.text + targetDynamic = given.dynamic + } else if (flag === '--target-path') { + const given = value() + targetPath = given.dynamic ? null : given.text + targetPathDynamic = given.dynamic + } else if (flag === '--defer' || flag === '--no-defer') hasDefer = true + else if (flag === '--state' || flag === '--defer-state') { + hasState = true + value() + } else if (DBT_VALUE_FLAGS.has(flag) && inline === null) j++ + continue + } + if (selecting) { + if (!current.dynamic) select.push(...word.split(/\s+/).filter(Boolean)) + continue + } + if (subcommand === null) { + // Which word dbt takes as the subcommand is not known when an expansion may be it. + if (current.dynamic) return null + if (DBT_SUBCOMMANDS.has(word)) { + subcommand = word + subcommandEnd = current.end + } else firstOther ??= current + } + } + if (subcommand === null && firstOther) { + subcommand = firstOther.text + subcommandEnd = firstOther.end + } + return { + at: words[launcherStart]!.start, + invocation: { + binary, + subcommand, + select, + target: targetDynamic ? null : (target ?? envTarget), + targetPath: targetPathDynamic ? null : (targetPath ?? envTargetPath), + dynamic: assignmentDynamic || words.slice(firstAssignment ?? launcherStart).some(one => one.dynamic), + hasDefer, + hasState, + start, + end, + subcommandEnd, + }, + } +} diff --git a/plugins/altimate-code/hooks/features/comments.tsx b/plugins/altimate-code/hooks/features/comments.tsx new file mode 100644 index 00000000..ecd7564a --- /dev/null +++ b/plugins/altimate-code/hooks/features/comments.tsx @@ -0,0 +1,53 @@ +// Team comments from shared dbt docs, in Claude's context and in /comments. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'comments', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/cost.tsx b/plugins/altimate-code/hooks/features/cost.tsx new file mode 100644 index 00000000..a9010a50 --- /dev/null +++ b/plugins/altimate-code/hooks/features/cost.tsx @@ -0,0 +1,53 @@ +// Cost check: BigQuery scans over the limit are held until allowed. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'cost', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/cte-profile.tsx b/plugins/altimate-code/hooks/features/cte-profile.tsx new file mode 100644 index 00000000..75dd00b2 --- /dev/null +++ b/plugins/altimate-code/hooks/features/cte-profile.tsx @@ -0,0 +1,53 @@ +// Profile CTEs: /profile-ctes times each CTE. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'cteProfile', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx new file mode 100644 index 00000000..c37aa855 --- /dev/null +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -0,0 +1,53 @@ +// Defer and target: --defer --state on dbt commands, and the target in the status line. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'defer', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/docs.tsx b/plugins/altimate-code/hooks/features/docs.tsx new file mode 100644 index 00000000..3fb211e5 --- /dev/null +++ b/plugins/altimate-code/hooks/features/docs.tsx @@ -0,0 +1,53 @@ +// Docs coverage and description propagation. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'docs', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/health.tsx b/plugins/altimate-code/hooks/features/health.tsx new file mode 100644 index 00000000..dc141a90 --- /dev/null +++ b/plugins/altimate-code/hooks/features/health.tsx @@ -0,0 +1,53 @@ +// Project health: new DataPilot insights on the models Claude changed. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'health', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/index.test.ts b/plugins/altimate-code/hooks/features/index.test.ts new file mode 100644 index 00000000..00a494a3 --- /dev/null +++ b/plugins/altimate-code/hooks/features/index.test.ts @@ -0,0 +1,58 @@ +import { expect, test } from 'claude-code/testing' + +import { + attempt, + featureBandLines, + featuresBashAfter, + featuresBashGate, + featuresBashRewrite, + featuresEditAfter, + featuresReadOrEditAfter, + featuresSessionEnd, + featuresSessionStart, + featuresTurnComplete, + featuresTurnStart, +} from './index' + +const engine = () => { + const logs: string[] = [] + // Enough of the engine for a feature that keeps state, reads files and registers commands; a stub needs none of it. + const $ = { + ui: { log: (text: string) => void logs.push(text) }, + fs: { exists: async () => false, read: async () => '' }, + state: { get: async () => ({ value: null }), set: async () => ({ isSet: true }), update: async () => ({ isSet: true }) }, + command: { register: async () => {} }, + } + return { logs, $: $ as any } +} + +test('attempt logs a feature function that throws at once, one that rejects, and passes a value on', async () => { + const { $, logs } = engine() + // Each phase wraps the call in attempt, so a function that throws before it returns a promise + // (not an async function) is caught like a rejection. + const syncThrow = (): Promise => { + throw new Error('at once') + } + expect(await attempt($, 'runs', 'sessionStart', syncThrow)).toBeUndefined() + expect(await attempt($, 'defer', 'bandLine', async () => Promise.reject(new Error('later')))).toBeUndefined() + expect(await attempt($, 'cost', 'bashGate', () => ({ deny: 'no' }))).toEqual({ deny: 'no' }) + expect(await attempt($, 'docs', 'bashRewrite', async () => 'dbt run')).toBe('dbt run') + expect(logs).toEqual(['runs · sessionStart failed: Error: at once', 'defer · bandLine failed: Error: later']) +}) + +test('with every feature a stub, each phase runs through the features and logs nothing', async () => { + const { $, logs } = engine() + const bash = { tool: 'Bash', command: 'dbt run -s a' } as any + const file = { tool: 'Edit', file_path: '/repo/models/a.sql' } as any + await featuresSessionStart($, {} as any) + await featuresTurnStart($, {} as any) + await featuresTurnComplete($, {} as any, {} as any) + await featuresSessionEnd($, {} as any) + expect(await featureBandLines($, {} as any)).toEqual([]) + expect(await featuresBashRewrite($, bash)).toBe('dbt run -s a') + expect(await featuresBashGate($, bash)).toBeNull() + expect(await featuresBashAfter($, bash, {} as any)).toEqual([]) + expect(await featuresEditAfter($, file, {} as any, { path: '/repo/models/a.sql', before: null })).toEqual([]) + expect(await featuresReadOrEditAfter($, file, {} as any, { path: '/repo/models/a.sql' })).toEqual([]) + expect(logs).toEqual([]) +}) diff --git a/plugins/altimate-code/hooks/features/index.ts b/plugins/altimate-code/hooks/features/index.ts new file mode 100644 index 00000000..f8a6a590 --- /dev/null +++ b/plugins/altimate-code/hooks/features/index.ts @@ -0,0 +1,352 @@ +// The dbt Power User features, each in its own file here, and the one place that calls them, in a +// fixed order: runs, defer, toModel, comments, cost, health, sqlGraph, docs, cteProfile. +// +// A plugin hooks each shared event once (a second hook on an event without a matcher is refused), and +// the engine refuses `$` handed to anything but a function it can name, so this file calls every +// feature's functions by name instead of looping over a list. A feature fills in its own file only. +// A function that throws, at once or as a rejection, is logged and skipped: one feature's failure never stops another or the call. +import type { Args, EngineInterface, EventResult, On, PluginOptions, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, EditedFile, FileCall } from '../tool-chain' +import { + register as runsRegister, + sessionStart as runsSessionStart, + turnStart as runsTurnStart, + turnComplete as runsTurnComplete, + sessionEnd as runsSessionEnd, + bandLine as runsBandLine, + bashRewrite as runsBashRewrite, + bashGate as runsBashGate, + bashAfter as runsBashAfter, + editAfter as runsEditAfter, + readOrEditAfter as runsReadOrEditAfter, + editReadsBefore as runsEditReadsBefore, +} from './runs' +import { + register as deferRegister, + sessionStart as deferSessionStart, + turnStart as deferTurnStart, + turnComplete as deferTurnComplete, + sessionEnd as deferSessionEnd, + bandLine as deferBandLine, + bashRewrite as deferBashRewrite, + bashGate as deferBashGate, + bashAfter as deferBashAfter, + editAfter as deferEditAfter, + readOrEditAfter as deferReadOrEditAfter, + editReadsBefore as deferEditReadsBefore, +} from './defer' +import { + register as toModelRegister, + sessionStart as toModelSessionStart, + turnStart as toModelTurnStart, + turnComplete as toModelTurnComplete, + sessionEnd as toModelSessionEnd, + bandLine as toModelBandLine, + bashRewrite as toModelBashRewrite, + bashGate as toModelBashGate, + bashAfter as toModelBashAfter, + editAfter as toModelEditAfter, + readOrEditAfter as toModelReadOrEditAfter, + editReadsBefore as toModelEditReadsBefore, +} from './to-model' +import { + register as commentsRegister, + sessionStart as commentsSessionStart, + turnStart as commentsTurnStart, + turnComplete as commentsTurnComplete, + sessionEnd as commentsSessionEnd, + bandLine as commentsBandLine, + bashRewrite as commentsBashRewrite, + bashGate as commentsBashGate, + bashAfter as commentsBashAfter, + editAfter as commentsEditAfter, + readOrEditAfter as commentsReadOrEditAfter, + editReadsBefore as commentsEditReadsBefore, +} from './comments' +import { + register as costRegister, + sessionStart as costSessionStart, + turnStart as costTurnStart, + turnComplete as costTurnComplete, + sessionEnd as costSessionEnd, + bandLine as costBandLine, + bashRewrite as costBashRewrite, + bashGate as costBashGate, + bashAfter as costBashAfter, + editAfter as costEditAfter, + readOrEditAfter as costReadOrEditAfter, + editReadsBefore as costEditReadsBefore, +} from './cost' +import { + register as healthRegister, + sessionStart as healthSessionStart, + turnStart as healthTurnStart, + turnComplete as healthTurnComplete, + sessionEnd as healthSessionEnd, + bandLine as healthBandLine, + bashRewrite as healthBashRewrite, + bashGate as healthBashGate, + bashAfter as healthBashAfter, + editAfter as healthEditAfter, + readOrEditAfter as healthReadOrEditAfter, + editReadsBefore as healthEditReadsBefore, +} from './health' +import { + register as sqlGraphRegister, + sessionStart as sqlGraphSessionStart, + turnStart as sqlGraphTurnStart, + turnComplete as sqlGraphTurnComplete, + sessionEnd as sqlGraphSessionEnd, + bandLine as sqlGraphBandLine, + bashRewrite as sqlGraphBashRewrite, + bashGate as sqlGraphBashGate, + bashAfter as sqlGraphBashAfter, + editAfter as sqlGraphEditAfter, + readOrEditAfter as sqlGraphReadOrEditAfter, + editReadsBefore as sqlGraphEditReadsBefore, +} from './sql-graph' +import { + register as docsRegister, + sessionStart as docsSessionStart, + turnStart as docsTurnStart, + turnComplete as docsTurnComplete, + sessionEnd as docsSessionEnd, + bandLine as docsBandLine, + bashRewrite as docsBashRewrite, + bashGate as docsBashGate, + bashAfter as docsBashAfter, + editAfter as docsEditAfter, + readOrEditAfter as docsReadOrEditAfter, + editReadsBefore as docsEditReadsBefore, +} from './docs' +import { + register as cteProfileRegister, + sessionStart as cteProfileSessionStart, + turnStart as cteProfileTurnStart, + turnComplete as cteProfileTurnComplete, + sessionEnd as cteProfileSessionEnd, + bandLine as cteProfileBandLine, + bashRewrite as cteProfileBashRewrite, + bashGate as cteProfileBashGate, + bashAfter as cteProfileBashAfter, + editAfter as cteProfileEditAfter, + readOrEditAfter as cteProfileReadOrEditAfter, + editReadsBefore as cteProfileEditReadsBefore, +} from './cte-profile' + +export type { FeatureId } from '../status-line' +export { FEATURE_IDS } from '../status-line' + +/** The elements a band line draws with: what `$.ui.resolve(e)` gave the band's hook. */ +export type BandUi = { Box: any; Button: any; Text: any; [element: string]: any } + +/** What a feature's `register` gets. */ +export type FeatureContext = { + /** The plugin's `userConfig` values (`.claude-plugin/plugin.json`), defaults filled in. */ + options: PluginOptions +} + +function failed($: EngineInterface, id: string, part: string, error: unknown) { + try { + $.ui.log(`${id} · ${part} failed: ${String(error)}`, { to: 'debug' }) + } catch {} +} + +/** + * Runs one feature function and logs a failure, whether it throws at once or rejects later, so a feature + * never breaks the phase it runs in. The function's value, or nothing when it failed. + */ +export async function attempt($: EngineInterface, id: string, part: string, run: () => T | Promise): Promise | void> { + try { + return await run() + } catch (error) { + failed($, id, part, error) + } +} + +/** Registers every feature's own hooks. */ +export function registerFeatures(on: On, context: FeatureContext) { + // One feature's register throwing (a duplicate command, a refused matcher) must not stop the others or the tool hook after them. + try { + runsRegister(on, context) + } catch {} + try { + deferRegister(on, context) + } catch {} + try { + toModelRegister(on, context) + } catch {} + try { + commentsRegister(on, context) + } catch {} + try { + costRegister(on, context) + } catch {} + try { + healthRegister(on, context) + } catch {} + try { + sqlGraphRegister(on, context) + } catch {} + try { + docsRegister(on, context) + } catch {} + try { + cteProfileRegister(on, context) + } catch {} +} + +export async function featuresSessionStart($: EngineInterface, e: Args<'session.start'>) { + await attempt($, 'runs', 'sessionStart', () => runsSessionStart($, e)) + await attempt($, 'defer', 'sessionStart', () => deferSessionStart($, e)) + await attempt($, 'toModel', 'sessionStart', () => toModelSessionStart($, e)) + await attempt($, 'comments', 'sessionStart', () => commentsSessionStart($, e)) + await attempt($, 'cost', 'sessionStart', () => costSessionStart($, e)) + await attempt($, 'health', 'sessionStart', () => healthSessionStart($, e)) + await attempt($, 'sqlGraph', 'sessionStart', () => sqlGraphSessionStart($, e)) + await attempt($, 'docs', 'sessionStart', () => docsSessionStart($, e)) + await attempt($, 'cteProfile', 'sessionStart', () => cteProfileSessionStart($, e)) +} + +export async function featuresTurnStart($: EngineInterface, e: Args<'turn.start'>) { + await attempt($, 'runs', 'turnStart', () => runsTurnStart($, e)) + await attempt($, 'defer', 'turnStart', () => deferTurnStart($, e)) + await attempt($, 'toModel', 'turnStart', () => toModelTurnStart($, e)) + await attempt($, 'comments', 'turnStart', () => commentsTurnStart($, e)) + await attempt($, 'cost', 'turnStart', () => costTurnStart($, e)) + await attempt($, 'health', 'turnStart', () => healthTurnStart($, e)) + await attempt($, 'sqlGraph', 'turnStart', () => sqlGraphTurnStart($, e)) + await attempt($, 'docs', 'turnStart', () => docsTurnStart($, e)) + await attempt($, 'cteProfile', 'turnStart', () => cteProfileTurnStart($, e)) +} + +export async function featuresTurnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) { + await attempt($, 'runs', 'turnComplete', () => runsTurnComplete($, e, out)) + await attempt($, 'defer', 'turnComplete', () => deferTurnComplete($, e, out)) + await attempt($, 'toModel', 'turnComplete', () => toModelTurnComplete($, e, out)) + await attempt($, 'comments', 'turnComplete', () => commentsTurnComplete($, e, out)) + await attempt($, 'cost', 'turnComplete', () => costTurnComplete($, e, out)) + await attempt($, 'health', 'turnComplete', () => healthTurnComplete($, e, out)) + await attempt($, 'sqlGraph', 'turnComplete', () => sqlGraphTurnComplete($, e, out)) + await attempt($, 'docs', 'turnComplete', () => docsTurnComplete($, e, out)) + await attempt($, 'cteProfile', 'turnComplete', () => cteProfileTurnComplete($, e, out)) +} + +export async function featuresSessionEnd($: EngineInterface, e: Args<'session.end'>) { + await attempt($, 'runs', 'sessionEnd', () => runsSessionEnd($, e)) + await attempt($, 'defer', 'sessionEnd', () => deferSessionEnd($, e)) + await attempt($, 'toModel', 'sessionEnd', () => toModelSessionEnd($, e)) + await attempt($, 'comments', 'sessionEnd', () => commentsSessionEnd($, e)) + await attempt($, 'cost', 'sessionEnd', () => costSessionEnd($, e)) + await attempt($, 'health', 'sessionEnd', () => healthSessionEnd($, e)) + await attempt($, 'sqlGraph', 'sessionEnd', () => sqlGraphSessionEnd($, e)) + await attempt($, 'docs', 'sessionEnd', () => docsSessionEnd($, e)) + await attempt($, 'cteProfile', 'sessionEnd', () => cteProfileSessionEnd($, e)) +} + +/** Each feature's band line, in order, with its id; a feature with nothing to say is left out. */ +export async function featureBandLines($: EngineInterface, ui: BandUi): Promise<{ id: string; line: RenderElement }[]> { + const lines: { id: string; line: RenderElement }[] = [] + const add = (id: string, line: RenderElement | null | void) => { + if (line) lines.push({ id, line }) + } + add('runs', await attempt($, 'runs', 'bandLine', () => runsBandLine($, ui))) + add('defer', await attempt($, 'defer', 'bandLine', () => deferBandLine($, ui))) + add('toModel', await attempt($, 'toModel', 'bandLine', () => toModelBandLine($, ui))) + add('comments', await attempt($, 'comments', 'bandLine', () => commentsBandLine($, ui))) + add('cost', await attempt($, 'cost', 'bandLine', () => costBandLine($, ui))) + add('health', await attempt($, 'health', 'bandLine', () => healthBandLine($, ui))) + add('sqlGraph', await attempt($, 'sqlGraph', 'bandLine', () => sqlGraphBandLine($, ui))) + add('docs', await attempt($, 'docs', 'bandLine', () => docsBandLine($, ui))) + add('cteProfile', await attempt($, 'cteProfile', 'bandLine', () => cteProfileBandLine($, ui))) + return lines +} + +/** The command after every feature's rewrite, each seeing the one before's. */ +export async function featuresBashRewrite($: EngineInterface, e: BashCall): Promise { + let command = e.command + const take = (next: string | null | void) => { + if (typeof next === 'string' && next.trim() !== '') command = next + } + take(await attempt($, 'runs', 'bashRewrite', () => runsBashRewrite($, { ...e, command }))) + take(await attempt($, 'defer', 'bashRewrite', () => deferBashRewrite($, { ...e, command }))) + take(await attempt($, 'toModel', 'bashRewrite', () => toModelBashRewrite($, { ...e, command }))) + take(await attempt($, 'comments', 'bashRewrite', () => commentsBashRewrite($, { ...e, command }))) + take(await attempt($, 'cost', 'bashRewrite', () => costBashRewrite($, { ...e, command }))) + take(await attempt($, 'health', 'bashRewrite', () => healthBashRewrite($, { ...e, command }))) + take(await attempt($, 'sqlGraph', 'bashRewrite', () => sqlGraphBashRewrite($, { ...e, command }))) + take(await attempt($, 'docs', 'bashRewrite', () => docsBashRewrite($, { ...e, command }))) + take(await attempt($, 'cteProfile', 'bashRewrite', () => cteProfileBashRewrite($, { ...e, command }))) + return command +} + +/** The first feature's refusal of the Bash call, or null. */ +export async function featuresBashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + let gate: { deny: string } | null = null + const take = (next: { deny: string } | null | void) => { + if (!gate && next && typeof next.deny === 'string') gate = { deny: next.deny } + } + if (!gate) take(await attempt($, 'runs', 'bashGate', () => runsBashGate($, e))) + if (!gate) take(await attempt($, 'defer', 'bashGate', () => deferBashGate($, e))) + if (!gate) take(await attempt($, 'toModel', 'bashGate', () => toModelBashGate($, e))) + if (!gate) take(await attempt($, 'comments', 'bashGate', () => commentsBashGate($, e))) + if (!gate) take(await attempt($, 'cost', 'bashGate', () => costBashGate($, e))) + if (!gate) take(await attempt($, 'health', 'bashGate', () => healthBashGate($, e))) + if (!gate) take(await attempt($, 'sqlGraph', 'bashGate', () => sqlGraphBashGate($, e))) + if (!gate) take(await attempt($, 'docs', 'bashGate', () => docsBashGate($, e))) + if (!gate) take(await attempt($, 'cteProfile', 'bashGate', () => cteProfileBashGate($, e))) + return gate +} + +/** The context lines every feature adds after a Bash call ran. */ +export async function featuresBashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise { + const lines: string[] = [] + addLines(lines, await attempt($, 'runs', 'bashAfter', () => runsBashAfter($, e, result))) + addLines(lines, await attempt($, 'defer', 'bashAfter', () => deferBashAfter($, e, result))) + addLines(lines, await attempt($, 'toModel', 'bashAfter', () => toModelBashAfter($, e, result))) + addLines(lines, await attempt($, 'comments', 'bashAfter', () => commentsBashAfter($, e, result))) + addLines(lines, await attempt($, 'cost', 'bashAfter', () => costBashAfter($, e, result))) + addLines(lines, await attempt($, 'health', 'bashAfter', () => healthBashAfter($, e, result))) + addLines(lines, await attempt($, 'sqlGraph', 'bashAfter', () => sqlGraphBashAfter($, e, result))) + addLines(lines, await attempt($, 'docs', 'bashAfter', () => docsBashAfter($, e, result))) + addLines(lines, await attempt($, 'cteProfile', 'bashAfter', () => cteProfileBashAfter($, e, result))) + return lines +} + +/** Whether any feature's `editAfter` needs the file's text from before the edit. */ +export const EDIT_READS_BEFORE: boolean = runsEditReadsBefore || deferEditReadsBefore || toModelEditReadsBefore || commentsEditReadsBefore || costEditReadsBefore || healthEditReadsBefore || sqlGraphEditReadsBefore || docsEditReadsBefore || cteProfileEditReadsBefore + +/** The context lines every feature adds after an edit landed. */ +export async function featuresEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise { + const lines: string[] = [] + addLines(lines, await attempt($, 'runs', 'editAfter', () => runsEditAfter($, e, result, runsEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'defer', 'editAfter', () => deferEditAfter($, e, result, deferEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'toModel', 'editAfter', () => toModelEditAfter($, e, result, toModelEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'comments', 'editAfter', () => commentsEditAfter($, e, result, commentsEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'cost', 'editAfter', () => costEditAfter($, e, result, costEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'health', 'editAfter', () => healthEditAfter($, e, result, healthEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'sqlGraph', 'editAfter', () => sqlGraphEditAfter($, e, result, sqlGraphEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'docs', 'editAfter', () => docsEditAfter($, e, result, docsEditReadsBefore ? file : { path: file.path, before: null }))) + addLines(lines, await attempt($, 'cteProfile', 'editAfter', () => cteProfileEditAfter($, e, result, cteProfileEditReadsBefore ? file : { path: file.path, before: null }))) + return lines +} + +/** The context lines every feature adds after a read or an edit succeeded. */ +export async function featuresReadOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise { + const lines: string[] = [] + addLines(lines, await attempt($, 'runs', 'readOrEditAfter', () => runsReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'defer', 'readOrEditAfter', () => deferReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'toModel', 'readOrEditAfter', () => toModelReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'comments', 'readOrEditAfter', () => commentsReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'cost', 'readOrEditAfter', () => costReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'health', 'readOrEditAfter', () => healthReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'sqlGraph', 'readOrEditAfter', () => sqlGraphReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'docs', 'readOrEditAfter', () => docsReadOrEditAfter($, e, result, file))) + addLines(lines, await attempt($, 'cteProfile', 'readOrEditAfter', () => cteProfileReadOrEditAfter($, e, result, file))) + return lines +} + +function addLines(lines: string[], added: readonly unknown[] | null | void) { + if (Array.isArray(added)) for (const line of added) if (typeof line === 'string' && line !== '') lines.push(line) +} diff --git a/plugins/altimate-code/hooks/features/runs.tsx b/plugins/altimate-code/hooks/features/runs.tsx new file mode 100644 index 00000000..40ad8ff0 --- /dev/null +++ b/plugins/altimate-code/hooks/features/runs.tsx @@ -0,0 +1,53 @@ +// Runs: every dbt command Claude runs, with its results, in /runs. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'runs', text)`. +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) {} + +/** After the session started: the place to register commands. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + +/** Also called for a subagent's turns, which carry `e.agentId`. */ +export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} + +/** After the turn's answer; `out` is what the turn ended with. Also called for a subagent's turns (`e.agentId`). */ +export async function turnComplete($: EngineInterface, e: Args<'turn.complete'>, out: EventResult<'turn.complete'>) {} + +export async function sessionEnd($: EngineInterface, e: Args<'session.end'>) {} + +/** This feature's line in the band, under the lineage line; null when there is nothing to say. */ +export async function bandLine($: EngineInterface, ui: BandUi): Promise { + return null +} + +/** The command to run in place of `e.command`; null keeps it. */ +export async function bashRewrite($: EngineInterface, e: BashCall): Promise { + return null +} + +/** + * `{ deny }` refuses the Bash call; null lets it run. A gate that throws is logged and the call runs: + * a gate that must hold the call when its own check fails catches that failure and returns `{ deny }`. + */ +export async function bashGate($: EngineInterface, e: BashCall): Promise<{ deny: string } | null> { + return null +} + +export async function bashAfter($: EngineInterface, e: BashCall, result: ToolCallResult): Promise {} + +/** `file.before` holds the text from before the edit only when `editReadsBefore` is true. */ +export async function editAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: EditedFile): Promise {} + +export async function readOrEditAfter($: EngineInterface, e: FileCall, result: ToolCallResult, file: { path: string }): Promise {} + +/** Whether `editAfter` needs the file's text from before the edit (one extra read per edit). */ +export const editReadsBefore = false diff --git a/plugins/altimate-code/hooks/features/sql-graph.test.tsx b/plugins/altimate-code/hooks/features/sql-graph.test.tsx new file mode 100644 index 00000000..47fe1c68 --- /dev/null +++ b/plugins/altimate-code/hooks/features/sql-graph.test.tsx @@ -0,0 +1,395 @@ +import { expect, mock, test } from 'claude-code/testing' + +import { cteCount, inputsOf, orderNodes } from './sql-graph' + +const ROOT = '/repo' +const FILE = `${ROOT}/models/fct_orders.sql` + +const PANE = { + plugin: 'altimate-code', + component: 'Pane', + requestId: 'altimate-sql-graph', + props: { title: 'SQL graph', isFocused: true, bodyColumns: 90, placement: 'dock', scroll: { offset: 0, bodyRows: 60 }, view: {} }, +} as const + +// The backend's answer for a model with two CTEs, as the tool returns it (response order is not dependency order). +const GRAPH = { + nodes: [ + { id: 'fct_orders', name: 'fct_orders', type: 'model', nodeId: 'model.shop.fct_orders', sql: 'select * from paid', columns: [{ name: 'order_id' }, { name: 'amount' }] }, + { id: 'paid', name: 'paid', type: 'cte', sql: 'select order_id, amount\nfrom orders\nwhere status = \'paid\'', columns: [{ name: 'order_id' }, { name: 'amount' }] }, + { id: 'orders', name: 'orders', type: 'model', nodeId: 'model.shop.stg_orders', sql: '', columns: [{ name: 'order_id' }, { name: 'amount' }, { name: 'status' }] }, + ], + edges: [ + ['orders', 'paid'], + ['paid', 'fct_orders'], + ], +} + +type Options = { answer?: Record; fail?: string; sql?: string; noProject?: boolean; ok?: boolean; okOutput?: string; hold?: Record>; holdFirst?: Promise; yml?: string } + +async function start($: any, on: any, options: Options = {}) { + const clock = mock.clock(on) + const cli: string[][] = [] + const reads: string[] = [] + on('command.register', () => ({ value: { command: 'sql-graph' } })) + on('turn.start', (_: unknown, e: { turnId: string }) => ({ turnId: e.turnId })) + on('session.end', () => ({ sessionId: 'test' })) + on('turn.complete', (_: unknown, e: { answer: string }) => ({ text: e.answer })) + on('session.start', (_: unknown, e: { cwd: string }) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('ui.open', () => ({ value: {} })) + on('ui.log', () => ({ value: undefined })) + on('ui.toast', () => ({ value: undefined })) + on('ui.render', ($$: any, e: any) => { + const { Box } = $$.ui.resolve(e) + return + }) + on('fs.exists', (_: unknown, e: { path: string }) => ({ value: !options.noProject && (e.path === `${ROOT}/dbt_project.yml` || e.path === `${ROOT}/dbt_packages/pkg/dbt_project.yml` || e.path === `${ROOT}/dbt_packages/vendor/pkg/dbt_project.yml` || e.path === `${ROOT}/vendor/pkg/dbt_project.yml` || e.path === `${ROOT}/vendor/pkg/nested/child/dbt_project.yml`) })) + on('fs.read', (_: unknown, e: { path: string }) => { + reads.push(e.path) + return { value: e.path === `${ROOT}/dbt_project.yml` ? (options.yml ?? "name: 'shop'\n") : (options.sql ?? 'select 1') } + }) + on('tool.list', () => ({ value: [] })) + on('mcp.connect', () => ({ value: { isConnected: false, reason: 'not_connected', message: 'off' } })) + on('process.run', async (_: unknown, e: { argv: readonly string[] }) => { + const [, command] = e.argv + // The integrations half of the plugin asks the CLI for its status at session start. + if (command !== 'tool') return { value: { exitCode: 1, stdout: '', stderr: 'not this test' } } + cli.push([...e.argv]) + const asked = JSON.parse(String(e.argv[e.argv.indexOf('--args') + 1] ?? '{}')).model as string + // A test can hold one model's answer to make it arrive after a newer ask's. + if (options.hold?.[asked]) await options.hold[asked] + // The first ask is held and answers with a graph of its own; later asks answer at once. + const nth = cli.length + if (options.holdFirst && nth === 1) { + await options.holdFirst + return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: '', metadata: { success: true, model: asked, nodes: [{ id: 'stale', name: 'stale', type: 'cte', sql: '', columns: [] }], edges: [] } }), stderr: '' } } + } + if (options.ok === false) return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: options.okOutput ?? 'Not available: this needs the dbt adapter', metadata: { success: false, reason: 'read-only', error: 'Not available: this needs the dbt adapter' } }), stderr: '' } } + if (options.fail) return { value: { exitCode: 1, stdout: JSON.stringify({ status: 'error', output: options.fail, metadata: { success: false } }), stderr: '' } } + const metadata = { success: true, model: asked, ...(options.answer ?? GRAPH) } + return { value: { exitCode: 0, stdout: JSON.stringify({ status: 'ok', output: 'SQL graph for fct_orders', metadata }), stderr: '' } } + }) + on('tool.call', () => ({ result: { ok: true } })) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await clock.settle() + return { clock, cli, reads } +} + +const composer = { origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 120 } } + +test('orderNodes puts each node after what feeds it, whatever order the backend listed them in', () => { + expect(orderNodes(GRAPH as any).map(node => node.id)).toEqual(['orders', 'paid', 'fct_orders']) + expect(inputsOf(GRAPH as any, 'fct_orders')).toEqual(['paid']) + expect(inputsOf(GRAPH as any, 'orders')).toEqual([]) +}) + +test('orderNodes keeps the listed order for nodes with no edges and survives a cycle', () => { + const alone = { nodes: [{ id: 'b' }, { id: 'a' }], edges: [] } as any + expect(orderNodes(alone).map(node => node.id)).toEqual(['b', 'a']) + const cycle = { nodes: [{ id: 'a' }, { id: 'b' }], edges: [['a', 'b'], ['b', 'a']] } as any + expect(orderNodes(cycle).map(node => node.id).sort()).toEqual(['a', 'b']) +}) + +test('a model is the .sql file in a dbt project\'s model folders: by file name, not by an ancestor folder, and never a macro, test, snapshot or build file', async ($, on) => { + const { clock } = await start($, on, { yml: "name: 'shop'\nmodel-paths: ['models', 'more_models']\n" }) + const reads = async (file: string) => { + await $.tool.call({ tool: 'Read', file_path: file }) + await clock.settle() + return (await $.command.run({ command: 'sql-graph', args: '', ...composer } as any)).text + } + expect(await reads(`${ROOT}/more_models/marts/dim_a.sql`)).toContain('dim_a') + expect(await reads(`${ROOT}/macros/cents.sql`)).toContain('dim_a') + expect(await reads(`${ROOT}/tests/t.sql`)).toContain('dim_a') + expect(await reads(`${ROOT}/target/compiled/shop/models/x.sql`)).toContain('dim_a') + expect(await reads(`${ROOT}/db/migrations/001.sql`)).toContain('dim_a') + expect(await reads(`${ROOT}/models/fct_orders.sql`)).toContain('fct_orders') + // A folder inside a model path keeps its name; a package's own models are not the project's. + expect(await reads(`${ROOT}/models/tests/in_models.sql`)).toContain('in_models') + expect(await reads(`${ROOT}/dbt_packages/pkg/models/p.sql`)).toContain('in_models') +}) + +test('a package installed deeper in the default folder, or under the project\'s packages-install-path, is not the project\'s model', async ($, on) => { + const { clock } = await start($, on, { yml: "name: 'shop'\npackages-install-path: vendor\n" }) + const reads = async (file: string) => { + await $.tool.call({ tool: 'Read', file_path: file }) + await clock.settle() + return (await $.command.run({ command: 'sql-graph', args: '', ...composer } as any)).text + } + expect(await reads(`${ROOT}/models/fct_orders.sql`)).toContain('fct_orders') + expect(await reads(`${ROOT}/vendor/pkg/models/v.sql`)).toContain('fct_orders') + expect(await reads(`${ROOT}/dbt_packages/vendor/pkg/models/d.sql`)).toContain('fct_orders') + // A project nested inside an installed package is a package's too: the outer project is still asked. + expect(await reads(`${ROOT}/vendor/pkg/nested/child/models/n.sql`)).toContain('fct_orders') +}) + +// A configured folder that is not the project's own vendor folder leaves the models in it alone. +for (const path of ['C:\\repo\\vendor', '../vendor', '/vendor', 'vendor/repo/', '/vendor/repo/', `cache${ROOT}/vendor`, `/opt${ROOT}/vendor`]) + test(`a packages-install-path of ${path} hides none of the project's own models`, async ($, on) => { + const { clock } = await start($, on, { yml: `name: 'shop'\npackages-install-path: ${path}\n` }) + await $.tool.call({ tool: 'Read', file_path: `${ROOT}/vendor/pkg/models/v.sql` }) + await clock.settle() + expect((await $.command.run({ command: 'sql-graph', args: '', ...composer } as any)).text).toMatch(/SQL graph for v\b/) + }) + +for (const path of [`${ROOT}/vendor`, 'vendor/./', './vendor', 'cache/../vendor', `${ROOT}/cache/../vendor`]) + test(`a packages-install-path written ${path.startsWith('/') ? 'as an absolute path inside the project' : `as ${path}`} is the same folder`, async ($, on) => { + const { clock } = await start($, on, { yml: `name: 'shop'\npackages-install-path: ${path}\n` }) + await $.tool.call({ tool: 'Read', file_path: `${ROOT}/models/fct_orders.sql` }) + await $.tool.call({ tool: 'Read', file_path: `${ROOT}/vendor/pkg/models/v.sql` }) + await clock.settle() + expect((await $.command.run({ command: 'sql-graph', args: '', ...composer } as any)).text).toContain('fct_orders') + }) + +test('outside a dbt project a .sql read sets no default model and an edit adds no line', async ($, on) => { + const { clock, cli } = await start($, on, { noProject: true, sql: 'with a as (select 1) select * from a' }) + const edit: any = await $.tool.call({ tool: 'Edit', file_path: '/other/models/x.sql', old_string: '1', new_string: '2' }) + await clock.settle() + expect(JSON.stringify(edit.context ?? [])).not.toContain('/sql-graph') + const reply = await $.command.run({ command: 'sql-graph', args: '', ...composer } as any) + expect(reply.text).toBe('Read or edit a dbt model, or run /sql-graph .') + expect(cli).toHaveLength(0) +}) + +test('cteCount counts the CTEs a model defines, not words in comments or strings', () => { + expect(cteCount('with a as (select 1), b as (select 2), "c" as (select 3) select * from a')).toBe(3) + expect(cteCount('with recursive r as (select 1) select * from r')).toBe(1) + expect(cteCount("-- with x as (\nselect ', y as (' as s from t")).toBe(0) + expect(cteCount('select cast(a as int), b as c from t')).toBe(0) + expect(cteCount("with a as (select '--' as marker), b as (select 1) select * from b")).toBe(2) + expect(cteCount('{# with fake as (select 1) #}\nselect 1')).toBe(0) + expect(cteCount(`select "it's" as c; with x as (select 1) select '--' from x`)).toBe(1) + expect(cteCount('with "my cte" as (select 1) select 1')).toBe(1) + expect(cteCount('with a (id) as (select 1), b(x, y) as (select 2, 3) select * from a')).toBe(2) +}) + +test('/sql-graph asks the tool once, with write permission, and the pane lists the nodes in dependency order', async ($, on) => { + const { clock, cli } = await start($, on) + const reply = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(reply.text).toBe('The SQL graph for fct_orders is open.') + expect(cli).toHaveLength(1) + expect(cli[0]).toContain('dbt_sql_graph') + expect(cli[0]).toContain('--allow-write') + expect(JSON.parse(cli[0]![cli[0]!.indexOf('--args') + 1]!)).toEqual({ model: 'fct_orders' }) + + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /SQL graph · fct_orders · 3 nodes/ })).toBeDefined() + // The backend lists fct_orders first; the pane draws each node after what feeds it. + expect((await ui.findAll({ type: 'Button' })).map(row => row.key)).toEqual(['node-orders', 'node-paid', 'node-fct_orders']) + expect(await ui.find({ type: 'Text', text: 'Press a row to see its SQL.' })).toBeDefined() + await ui.unmount() +}) + +test('pressing a row shows that node\'s SQL', async ($, on) => { + const { clock } = await start($, on) + await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'node-paid' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: 'from orders' })).toBeDefined() + expect(await ui.find({ type: 'Text', text: "where status = 'paid'" })).toBeDefined() + await ui.unmount() +}) + +test('two nodes with one name stay two rows, each with its own inputs and SQL', async ($, on) => { + const answer = { + nodes: [ + { id: 'analytics.customers_1', name: 'customers', type: 'model', nodeId: 'model.shop.customers', sql: 'analytics.customers', columns: [] }, + { id: 'raw.customers_2', name: 'customers', type: 'source', nodeId: 'source.shop.raw.customers', sql: 'raw.customers', columns: [] }, + { id: 'LEFT_JOIN_9', name: 'LEFT_JOIN_9', type: 'LEFT_JOIN', sql: 'LEFT JOIN raw.customers', columns: [] }, + ], + edges: [ + ['analytics.customers_1', 'LEFT_JOIN_9'], + ['raw.customers_2', 'LEFT_JOIN_9'], + ], + } + const { clock } = await start($, on, { answer }) + await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ key: 'node-analytics.customers_1' })).toBeDefined() + expect(await ui.find({ key: 'node-raw.customers_2' })).toBeDefined() + expect(inputsOf(answer as any, 'LEFT_JOIN_9')).toEqual(['analytics.customers_1', 'raw.customers_2']) + await ui.press({ key: 'node-raw.customers_2' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: 'raw.customers' })).toBeDefined() + await ui.unmount() +}) + +test('text from the CLI, the repo and the backend is drawn without escape or control characters, and a long statement is cut', async ($, on) => { + const esc = String.fromCharCode(27) + const bad = `bad${esc}]0;owned\u0007${esc}[31mred${esc}[0m\u2028end` + const { clock } = await start($, on, { fail: bad }) + const reply = await $.command.run({ command: 'sql-graph', args: `m${esc}]0;x\u0007odel`, ...composer } as any) + await clock.settle() + expect(reply.text).not.toMatch(/[\u0000-\u0008\u000b-\u001f\u007f-\u009f\u2028\u2029]/) + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + const drawn = JSON.stringify(await ui.find({ type: 'Text', text: /bad/ })) + expect(drawn).not.toMatch(/u001b|u0007/) + expect(drawn).not.toContain('\u2028') + await ui.unmount() +}) + +test('a graph whose names, types and SQL carry escape and control characters is drawn as plain text', async ($, on) => { + const esc = String.fromCharCode(27) + const dirty = (word: string) => `${word}${esc}[31m!${esc}]0;x\u0007\u2028end` + const answer = { + nodes: [ + { id: 'a', name: dirty('src'), type: dirty('model'), sql: '', columns: [] }, + { id: 'b', name: dirty('out'), type: 'cte', sql: `select${esc}[1m 1\u0007\nfrom${esc}]0;x\u0007 a\u2028`, columns: [] }, + ], + edges: [['a', 'b']], + } + const { clock } = await start($, on, { answer }) + await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'node-b' }) + await clock.settle() + const bad = /[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029]/ + const rows = await ui.findAll({ type: 'Button' }) + expect(rows).toHaveLength(2) + for (const row of rows) expect(String((row as any).props.label)).not.toMatch(bad) + expect(String((rows[1] as any).props.label)).toContain('from src') + const texts = await ui.findAll({ type: 'Text' }) + for (const text of texts) expect(String((text as any).text ?? '')).not.toMatch(/[\u0000-\u0009\u000b-\u001f\u007f-\u009f\u2028\u2029]/) + expect(await ui.find({ type: 'Text', text: /select.*1/s })).toBeDefined() + await ui.unmount() +}) + +test('the SQL of a selected node is cut at a limit and says how much was left out', async ($, on) => { + const answer = { + nodes: [{ id: 'big', name: 'big', type: 'cte', sql: `${'x'.repeat(20_000)}TAILMARK${'x'.repeat(4_992)}`, columns: [] }], + edges: [], + } + const { clock } = await start($, on, { answer }) + await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + await ui.press({ key: 'node-big' }) + await clock.settle() + const shown = await ui.find({ type: 'Text', text: /… 5000 more characters not shown$/ }) + expect(shown).toBeDefined() + expect(JSON.stringify(shown)).not.toContain('TAILMARK') + await ui.unmount() +}) + +test('without a name /sql-graph shows the model Claude last read; with none read it says what to do and calls nothing', async ($, on) => { + const { clock, cli } = await start($, on) + const none = await $.command.run({ command: 'sql-graph', args: '', ...composer } as any) + expect(none.text).toBe('Read or edit a dbt model, or run /sql-graph .') + expect(cli).toHaveLength(0) + + await $.tool.call({ tool: 'Read', file_path: FILE }) + await clock.settle() + await $.command.run({ command: 'sql-graph', args: '', ...composer } as any) + await clock.settle() + expect(cli).toHaveLength(1) + expect(JSON.parse(cli[0]![cli[0]!.indexOf('--args') + 1]!)).toEqual({ model: 'fct_orders' }) +}) + +test('a tool failure is the pane\'s message and the command\'s reply', async ($, on) => { + const { clock } = await start($, on, { fail: 'Not available: no dbt project here' }) + const reply = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(reply.text).toBe('Not available: no dbt project here') + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: 'Not available: no dbt project here' })).toBeDefined() + await ui.unmount() +}) + +test('an edit to a model adds one line with its CTE count and never calls the backend', async ($, on) => { + const { clock, cli } = await start($, on, { sql: 'with a as (select 1), b as (select 2) select * from a' }) + const result = await $.tool.call({ tool: 'Edit', file_path: FILE, old_string: '1', new_string: '2' }) + await clock.settle() + expect((result as any).context).toContain('2 CTEs · /sql-graph') + expect(cli).toHaveLength(0) +}) + +test('an edit to a model with no CTEs, or to a file that is no model, adds no line', async ($, on) => { + const { clock } = await start($, on, { sql: 'select 1' }) + const plain = await $.tool.call({ tool: 'Edit', file_path: FILE, old_string: '1', new_string: '2' }) + const macro = await $.tool.call({ tool: 'Edit', file_path: `${ROOT}/macros/m.sql`, old_string: '1', new_string: '2' }) + await clock.settle() + expect(JSON.stringify((plain as any).context ?? [])).not.toContain('/sql-graph') + expect(JSON.stringify((macro as any).context ?? [])).not.toContain('/sql-graph') +}) + +test('an older ask for the same model that answers after a newer one does not replace it, and says so', async ($, on) => { + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { clock } = await start($, on, { holdFirst: held }) + const older = $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.advance(3_000) + expect((await older).text).toBe('The SQL graph for fct_orders is loading; the pane shows it when it is ready.') + // The second ask answers at once; the first answers after it. + const newer = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(newer.text).toBe('The SQL graph for fct_orders is open.') + release() + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: /SQL graph · fct_orders · 3 nodes/ })).toBeDefined() + await ui.unmount() +}) + +test('an older ask that answers after a newer one, inside the wait, replies that it was replaced', async ($, on) => { + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { clock } = await start($, on, { holdFirst: held }) + const older = $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.advance(500) + const newer = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(newer.text).toBe('The SQL graph for fct_orders is open.') + release() + await clock.settle() + expect((await older).text).toBe('The SQL graph for fct_orders was replaced by a newer /sql-graph.') +}) + +test('an answer that lands after a new conversation started is dropped', async ($, on) => { + let release!: () => void + const held = new Promise(resolve => (release = resolve)) + const { clock } = await start($, on, { hold: { fct_orders: held } }) + const reply = $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.advance(3_000) + await reply + await $.session.end({ sessionId: 'test' } as any) + release() + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect(await ui.find({ type: 'Text', text: 'Run /sql-graph .' })).toBeDefined() + await ui.unmount() +}) + +test('a tool answer of status ok with success false is the failure it says, not an empty graph', async ($, on) => { + const { clock } = await start($, on, { ok: false }) + const reply = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(reply.text).toBe('Not available: this needs the dbt adapter') +}) + +test('the tool\'s own reason is shown, not the CLI\'s generic output', async ($, on) => { + const { clock } = await start($, on, { ok: false, okOutput: 'Compiled 1 model in 2.1s' }) + const reply = await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + expect(reply.text).toBe('Not available: this needs the dbt adapter') +}) + +test('a malformed node or edge from the backend is dropped, and a node without columns is drawn with none', async ($, on) => { + const answer = { + nodes: [null, { id: 'a', name: 'a', type: 'cte', sql: 123 }, { id: 5 }], + edges: [['a'], ['a', 'a']], + } + const { clock } = await start($, on, { answer }) + await $.command.run({ command: 'sql-graph', args: 'fct_orders', ...composer } as any) + await clock.settle() + const ui = await $.ui.mount({ ...PANE, surface: 'terminal' }) + expect((await ui.findAll({ type: 'Button' })).map(row => row.key)).toEqual(['node-a']) + await ui.press({ key: 'node-a' }) + await clock.settle() + expect(await ui.find({ type: 'Text', text: '(no SQL)' })).toBeDefined() + await ui.unmount() +}) diff --git a/plugins/altimate-code/hooks/features/sql-graph.tsx b/plugins/altimate-code/hooks/features/sql-graph.tsx new file mode 100644 index 00000000..155ad0ce --- /dev/null +++ b/plugins/altimate-code/hooks/features/sql-graph.tsx @@ -0,0 +1,327 @@ +// SQL graph: /sql-graph lists a model's CTEs, joins and filters. +// +// The plugin calls each function below at its moment, in the order features/index.ts fixes; one with +// nothing to do stays a no-op. This feature's own hooks (its commands and panes, each under a matcher +// no other part uses) go in `register`. The events the whole plugin shares (session start and end, +// turns, Bash and file tool calls, the band) come through the other functions, since a plugin hooks +// each of those once. The status-line part is set with `setStatusPart($, 'sqlGraph', text)`. +import { atom, read, update } from 'claude-code' +import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' + +import type { SqlGraphState, SqlGraphView } from '../../types' +import { later, runTool, within } from '../altimate-cli' +import { projectLayout } from '../lineage-graph' +import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { BandUi, FeatureContext } from './index' + +const PANE = 'altimate-sql-graph' +const PANE_TITLE = 'SQL graph' +const COMMAND = 'sql-graph' +// How long /sql-graph waits for the graph before it replies without it; the pane shows it when it lands. +const COMMAND_WAIT_MS = 2_000 +// The compile, the warehouse metadata read and the backend call, with the dbt adapter's start: its own budget. +const TOOL_BUDGET_MS = 150_000 +const PANE_SIZE = { columns: 100, rows: 30 } + +const stateAtom = atom({ plugin: 'altimate-code', key: 'sqlGraph' } as const, null, { shape: 'sql-graph-1' }) + +const EMPTY: SqlGraphState = { lastModel: null, shown: null } + +// Folders at the top of a dbt project that hold no model, and build or package folders at any depth. A folder inside a model path keeps its name: `models/tests/orders.sql` is a model. +const NOT_MODEL_TOP = /^(macros|tests|analyses|analysis|snapshots|seeds)$/i +const NOT_MODEL_ANYWHERE = /^(target|dbt_packages|dbt_modules)$/i +// The most of a node's SQL the pane draws; a larger statement is cut, and says so. +const SQL_LIMIT = 20_000 + +/** Whether a dbt project's folder sits among the installed packages of an enclosing project: a default package folder at any depth, or its `packages-install-path`. */ +async function insideInstalledPackages($: EngineInterface, root: string): Promise { + let dir = root + for (let i = 0; i < 40; i++) { + const cut = dir.lastIndexOf('/') + if (cut <= 0) return false + dir = dir.slice(0, cut) + if (!(await $.fs.exists(`${dir}/dbt_project.yml`).catch(() => false))) continue + const inside = root.slice(dir.length).replace(/^\/+/, '').split('/') + if (inside.some(part => NOT_MODEL_ANYWHERE.test(part))) return true + const yml = await $.fs.read(`${dir}/dbt_project.yml`).catch(() => '') + const custom = /^packages-install-path:\s*['"]?([^'"#\n]+?)['"]?\s*(?:#.*)?$/m.exec(String(yml))?.[1] + // The configured folder as a path from this project: an absolute one counts only when it is inside the project. + const given = (custom ?? '').replace(/\\/g, '/') + const from = `${dir.replace(/\/+$/, '')}/` + // A drive or UNC prefix is absolute too, and never inside a POSIX project path. + const absolute = given.startsWith('/') || /^[A-Za-z]:/.test(given) + const relative = absolute ? (given.startsWith(from) ? given.slice(from.length) : null) : given + const kept: string[] = [] + let outside = relative === null + for (const part of relative === null ? [] : relative.split('/')) { + if (part === '..') { + // A path that climbs above the project root is outside it. + if (kept.length === 0) outside = true + else kept.pop() + } else if (part && part !== '.') kept.push(part) + } + const own = outside ? '' : kept.join('/') + const here = inside.join('/') + // An enclosing project that does not hold this one among its packages leaves the outer ones to be asked. + if (own && (here === own || here.startsWith(`${own}/`))) return true + } + return false +} + +/** The model a SQL file holds, by its file name; null for a file outside a dbt project's model folders. */ +export async function modelOf($: EngineInterface, file: string): Promise { + if (!/\.sql$/i.test(file)) return null + const path = file.replace(/\\/g, '/') + let dir = path.slice(0, path.lastIndexOf('/')) + let root: string | null = null + for (let i = 0; i < 40 && dir; i++) { + if (await $.fs.exists(`${dir}/dbt_project.yml`).catch(() => false)) { + root = dir + break + } + const cut = dir.lastIndexOf('/') + if (cut <= 0) break + dir = dir.slice(0, cut) + } + // An installed package has a dbt_project.yml of its own: its models are not this project's. + if (!root || NOT_MODEL_ANYWHERE.test(root.split('/').slice(-2, -1)[0] ?? '')) return null + if (await insideInstalledPackages($, root)) return null + const relative = path.slice(root.length).replace(/^\/+/, '') + const folders = relative.split('/').slice(0, -1) + if (folders.some(part => NOT_MODEL_ANYWHERE.test(part)) || NOT_MODEL_TOP.test(folders[0] ?? '')) return null + const layout = projectLayout(await $.fs.read(`${root}/dbt_project.yml`).catch(() => '')) + const inside = layout.models.some(folder => { + const own = folder.replace(/^\.\/+/, '').replace(/^\.$/, '').replace(/\/+$/, '') + return own === '' || relative.startsWith(`${own}/`) + }) + return inside ? relative.slice(relative.lastIndexOf('/') + 1).replace(/\.sql$/i, '') || null : null +} + +/** How many CTEs a model's SQL defines: `with a as (…), b (c) as (…)`; comments and strings are not read. */ +export function cteCount(sql: string): number { + // One pass, so a `--` inside a string and a quote inside a comment each stay where they are. + const bare = sql.replace(/"(?:[^"]|"")*"|'(?:[^']|'')*'|--[^\n]*|\/\*[\s\S]*?\*\/|\{#[\s\S]*?#\}/g, m => (m[0] === '"' ? '"x"' : ' ')) + return [ + ...bare.matchAll( + /(?:\bwith\s+(?:recursive\s+)?|,\s*)(?:"[^"]+"|`[^`]+`|\w+)\s*(?:\([^)]*\)\s*)?as\s*(?:not\s+materialized\s+|materialized\s+)?\(/gi, + ), + ].length +} + +/** Text from the repo, the CLI or the backend drawn as one line of plain characters: escape sequences and control characters out. */ +function plain(text: string): string { + return text + .replace(/\u001b\][^\u0007\u001b]*(?:\u0007|\u001b\\)?/g, ' ') + .replace(/\u001b\[[0-?]*[ -/]*[@-~]/g, ' ') + .replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, ' ') +} + +/** A node's SQL as drawn: lines kept, escape sequences and other control characters out, and cut at SQL_LIMIT. */ +function sqlText(sql: string): string { + const kept = sql.slice(0, SQL_LIMIT).split('\n').map(plain).join('\n') + return sql.length > SQL_LIMIT ? `${kept}\n… ${sql.length - SQL_LIMIT} more characters not shown` : kept +} + +/** The graph's nodes in dependency order: a node comes after everything that feeds it; ties keep the backend's order. */ +export function orderNodes(graph: SqlGraphView): SqlGraphView['nodes'] { + const ids = new Set(graph.nodes.map(node => node.id)) + const pending = new Map() + const feeds = new Map() + for (const [from, to] of graph.edges) { + if (!ids.has(from) || !ids.has(to) || from === to) continue + pending.set(to, (pending.get(to) ?? 0) + 1) + feeds.set(from, [...(feeds.get(from) ?? []), to]) + } + const done = new Set() + const ordered: SqlGraphView['nodes'] = [] + // Repeated passes in the backend's order: a cycle (which SQL cannot have) falls out as the rest, unsorted. + while (ordered.length < graph.nodes.length) { + const ready = graph.nodes.filter(node => !done.has(node.id) && (pending.get(node.id) ?? 0) === 0) + const batch = ready.length ? ready : graph.nodes.filter(node => !done.has(node.id)) + for (const node of batch) { + done.add(node.id) + ordered.push(node) + for (const to of feeds.get(node.id) ?? []) pending.set(to, (pending.get(to) ?? 1) - 1) + } + if (!ready.length) break + } + return ordered.length === graph.nodes.length ? ordered : graph.nodes +} + +/** The inputs of a node: the ids with an edge into it. */ +export function inputsOf(graph: SqlGraphView, id: string): string[] { + return graph.edges.filter(([, to]) => to === id).map(([from]) => from) +} + +async function merge($: EngineInterface, change: (prev: SqlGraphState) => SqlGraphState) { + await update($, stateAtom, prev => change(prev ?? EMPTY)) +} + +// The ask that owns the pane. Only an answer to that ask is written, so an older ask for the same model, or one +// from before a new conversation, never replaces a newer one. +let latestRequest = 0 + +async function showing($: EngineInterface, request: number, change: Partial>) { + await merge($, prev => (prev.shown?.request === request ? { ...prev, shown: { ...prev.shown, ...change } } : prev)) +} + +/** Asks the tool for the model's graph and puts the answer, or why there is none, in the pane. */ +async function load($: EngineInterface, model: string): Promise<'shown' | 'failed' | 'replaced'> { + const request = ++latestRequest + await merge($, prev => ({ ...prev, shown: { model, request, graph: null, loading: true, message: null, selected: null } })) + let outcome: 'shown' | 'failed' = 'failed' + try { + const until = (await $.clock.now()) + TOOL_BUDGET_MS + // The tool starts the dbt adapter, so it needs write permission: it goes through the CLI. + const result = await runTool($, 'dbt_sql_graph', { model }, { write: true, until }) + const meta = result.metadata as { success?: boolean; error?: string; nodes?: SqlGraphView['nodes']; edges?: SqlGraphView['edges'] } | null + if (!result.ok || !meta?.success || !Array.isArray(meta.nodes) || !Array.isArray(meta.edges)) { + // The tool's own reason comes before the CLI's generic output. + const reason = typeof meta?.error === 'string' ? meta.error : '' + await showing($, request, { loading: false, message: plain(reason || result.text || `No SQL graph for ${model}.`) }) + } else { + // A node the render reads must be well formed: others are dropped, not thrown on. + const nodes = meta.nodes.filter( + n => n && typeof n === 'object' && typeof n.id === 'string' && typeof n.name === 'string' && typeof n.type === 'string', + ).map(n => ({ ...n, sql: typeof n.sql === 'string' ? n.sql : '', columns: Array.isArray(n.columns) ? n.columns : [] })) + const edges = meta.edges.filter(e => Array.isArray(e) && e.length === 2 && e.every(x => typeof x === 'string')) + await showing($, request, { loading: false, graph: { nodes, edges } }) + outcome = 'shown' + } + } catch (error) { + await showing($, request, { loading: false, message: plain(`No SQL graph for ${model}: ${String(error)}`) }) + } + return (await read($, stateAtom))?.shown?.request === request ? outcome : 'replaced' +} + +/** Adds this feature's own hooks. */ +export function register(on: On, context: FeatureContext) { + on('command.run', { command: COMMAND }, async ($, e) => { + const asked = e.args.trim() + const model = asked || (await read($, stateAtom))?.lastModel || '' + if (!model) return { text: 'Read or edit a dbt model, or run /sql-graph .' } + const shownModel = plain(model) + try { + await $.ui.open({ id: PANE, title: PANE_TITLE, ...PANE_SIZE, focus: true, closeOnEscape: true }) + } catch (error) { + return { text: plain(`Could not open the SQL graph: ${String(error)}`) } + } + // One backend call and one warehouse metadata read, per command, never per edit. + const landed = await within($, COMMAND_WAIT_MS, load($, model)) + if (landed === null) return { text: `The SQL graph for ${shownModel} is loading; the pane shows it when it is ready.` } + if (landed === 'replaced') return { text: `The SQL graph for ${shownModel} was replaced by a newer /sql-graph.` } + return { text: landed === 'shown' ? `The SQL graph for ${shownModel} is open.` : ((await read($, stateAtom))?.shown?.message ?? `No SQL graph for ${shownModel}.`) } + }) + + on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => { + const { Box, Button, Text } = $.ui.resolve(e) + const shown = (await read($, stateAtom))?.shown + if (!shown) { + return ( + + SQL graph + Run /sql-graph <model>. + + ) + } + if (shown.loading) { + return ( + + {`SQL graph · ${plain(shown.model)}`} + Compiling the model and asking the Altimate backend… + + ) + } + if (!shown.graph) { + return ( + + {`SQL graph · ${plain(shown.model)}`} + {plain(shown.message ?? `No SQL graph for ${shown.model}.`)} + + ) + } + const graph = shown.graph + const nodes = orderNodes(graph) + const chosen = nodes.find(node => node.id === shown.selected) + const nameOf = new Map(nodes.map(node => [node.id, node.name])) + const select = (id: string) => later($, () => showing($, shown.request, { selected: id })) + return ( + + + {`SQL graph · ${plain(shown.model)} · ${nodes.length} nodes`} + + {nodes.map(node => { + const from = inputsOf(graph, node.id).map(id => nameOf.get(id) ?? id) + const text = `${plain(node.name)} (${plain(node.type)}) · ${node.columns.length} ${node.columns.length === 1 ? 'column' : 'columns'}${from.length ? ` · from ${from.map(plain).join(', ')}` : ''}` + return