diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts new file mode 100644 index 00000000..336cde1f --- /dev/null +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -0,0 +1,411 @@ +import { expect, mock, test } from 'claude-code/testing' + +import { effective, rewriteDeferCommand, runsHere, runsInProject, statusText } from './defer' + +const on = { stateDir: '/work/prod-state' } + +test('dbt build -s x gets --defer --state right after the subcommand', () => { + expect(rewriteDeferCommand('dbt build -s x', on)).toBe('dbt build --defer --state /work/prod-state -s x') +}) + +test('each dbt invocation in cd a && dbt run is rewritten, the rest of the line is left as it is', () => { + expect(rewriteDeferCommand('cd a && dbt run', on)).toBe('cd a && dbt run --defer --state /work/prod-state') + expect(rewriteDeferCommand('dbt run && dbt test | tee log', on)).toBe('dbt run --defer --state /work/prod-state && dbt test --defer --state /work/prod-state | tee log') +}) + +test('a quoted --directory or --project option is not followed', () => { + expect(runsInProject('uv run "--directory=../b" dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject("uv run '--directory' ../b dbt run", '/repo/a', '/repo/a')).toBe(false) +}) + +test('uv run dbt test is rewritten after the subcommand, and --favor-state follows the setting', () => { + expect(rewriteDeferCommand('uv run dbt test', { ...on, favorState: true })).toBe('uv run dbt test --defer --state /work/prod-state --favor-state') +}) + +test('a command with --state, --defer or --no-defer already is not changed', () => { + expect(rewriteDeferCommand('dbt build --state ./old', on)).toBe('dbt build --state ./old') + expect(rewriteDeferCommand('dbt build --no-defer', on)).toBe('dbt build --no-defer') + expect(rewriteDeferCommand('DBT_STATE=./old dbt build', on)).toBe('DBT_STATE=./old dbt build') +}) + +test('defer off or no dbt command: no rewrite', () => { + expect(rewriteDeferCommand('dbt build', {})).toBe('dbt build') + expect(rewriteDeferCommand('dbt build', { stateDir: null })).toBe('dbt build') + expect(rewriteDeferCommand('ls -la && echo dbt', on)).toBe('ls -la && echo dbt') +}) + +test('commands that do not defer are left without --defer, and the target goes to every command that takes one', () => { + const both = { ...on, target: 'qa', defaultTarget: 'dev' } + expect(rewriteDeferCommand('dbt ls -s x', on)).toBe('dbt ls -s x') + expect(rewriteDeferCommand('dbt seed', on)).toBe('dbt seed') + expect(rewriteDeferCommand('dbt snapshot -s x', on)).toBe('dbt snapshot --defer --state /work/prod-state -s x') + expect(rewriteDeferCommand('dbt build -s x', on)).toBe('dbt build --defer --state /work/prod-state -s x') + expect(rewriteDeferCommand('dbt deps', both)).toBe('dbt deps') + expect(rewriteDeferCommand('dbt source freshness', both)).toBe('dbt source freshness') + expect(rewriteDeferCommand('dbt docs generate', both)).toBe('dbt docs generate') + expect(rewriteDeferCommand('dbt debug', both)).toBe('dbt debug --target qa') + expect(rewriteDeferCommand('dbt retry', both)).toBe('dbt retry') +}) + +test('an inline DBT_TARGET keeps the target of that command only', () => { + const options = { target: 'qa', defaultTarget: 'dev' } + expect(rewriteDeferCommand('DBT_TARGET=ci dbt run', options)).toBe('DBT_TARGET=ci dbt run') + expect(rewriteDeferCommand('DBT_TARGET=ci dbt run && dbt test', options)).toBe('DBT_TARGET=ci dbt run && dbt test --target qa') +}) + +test('a command for another project, by cd or --project-dir, is not rewritten', () => { + expect(runsInProject('dbt run', '/repo/a', '/repo/a')).toBe(true) + expect(runsInProject('cd models && dbt run', '/repo/a', '/repo/a')).toBe(true) + expect(runsInProject('cd a && dbt run', '/repo', '/repo/a')).toBe(true) + expect(runsInProject('cd ../b && dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('dbt run && cd ../b && dbt test', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('dbt run --project-dir ../b', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('DBT_PROJECT_DIR=../b dbt run', '/repo/a', '/repo/a')).toBe(false) + // A folder below the project with a dbt project of its own is not this project. + expect(runsInProject('cd nested && dbt build', '/repo/a', '/repo/a', dir => dir === '/repo/a/nested')).toBe(false) + expect(runsInProject('dbt build', '/repo/a/nested/deeper', '/repo/a', dir => dir === '/repo/a/nested')).toBe(false) + expect(runsInProject('cd models && dbt build', '/repo/a', '/repo/a', dir => dir === '/repo/a/nested')).toBe(true) + // An escaped space ends the raw match early: `./a\ b` is not the project `./a`. + expect(runsInProject('dbt run --project-dir ./a\\ b', '/repo', '/repo/a')).toBe(false) + expect(runsInProject('dbt run', '/repo', '/repo/a')).toBe(false) + expect(runsInProject('cd ~/other && dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('ls', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('{ cd ../b; dbt run; }', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('if cd ../b; then dbt run; fi', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('cd -P ../b && dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('cd ~/x && dbt run --project-dir /repo/a', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('pushd ../b && dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('uv run --directory ../b dbt run', '/repo/a', '/repo/a')).toBe(false) + // The project named with --project-dir is this one when it resolves to it. + expect(runsInProject('dbt run --project-dir a', '/repo', '/repo/a')).toBe(true) + expect(runsInProject('dbt run --project-dir b', '/repo', '/repo/a')).toBe(false) + expect(runsInProject('dbt run --project-dir nested', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('cd ../b; (cd ../a); dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('out=`cd ../b && dbt run`', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('cd a && dbt run --project-dir .', '/repo', '/repo/a')).toBe(true) + expect(runsInProject('dbt run --project-dir ./models/..', '/repo/a', '/repo/a')).toBe(true) +}) + +test('a folder change or project named outside the dbt command itself is not trusted', () => { + const run = (command: string) => runsInProject(command, '/repo/a', '/repo/a') + // A project named by another command or in a comment does not vouch for a different dbt command. + expect(run('cd ../b && dbt run --project-dir ../a && dbt test')).toBe(false) + expect(run('cd ../b; echo --project-dir ../a; dbt run')).toBe(false) + expect(run('dbt run # --project-dir ../a')).toBe(false) + // Folder changes that are not followed leave the folder unknown. + expect(run('cd && dbt run')).toBe(false) + expect(run('popd && dbt run')).toBe(false) + expect(run('command cd ../b && dbt run')).toBe(false) + expect(run('env -C ../b dbt run')).toBe(false) + expect(run('env --chdir=../b dbt run')).toBe(false) + expect(run('cd ./$SUB && dbt run')).toBe(false) + expect(run('cd `pwd`/../b && dbt run')).toBe(false) + expect(run("command 'cd' ../b && dbt run")).toBe(false) + expect(run('env "-C" ../b dbt run')).toBe(false) + expect(run('dbt run "--project-dir" ../b')).toBe(false) + expect(run('cd "\'.\'"/.. && dbt run')).toBe(false) + expect(run('cd "a"/.. && dbt run')).toBe(false) + expect(run('popd; dbt run')).toBe(false) + expect(run('cd\ndbt run')).toBe(false) + expect(run('cd ../b && dbt ls <(cd ../a; dbt ls)')).toBe(false) + expect(run('cd models && dbt run')).toBe(true) +}) + +test('DBT_STATE or DBT_TARGET exported earlier in the line is left alone, and an inner invocation keeps its place', () => { + expect(rewriteDeferCommand('export DBT_STATE=/mine && dbt build', on)).toBe('export DBT_STATE=/mine && dbt build') + expect(rewriteDeferCommand('export OTHER=x DBT_STATE=/mine DBT_TARGET=prod && dbt build', { ...on, target: 'qa', defaultTarget: 'dev' })).toBe('export OTHER=x DBT_STATE=/mine DBT_TARGET=prod && dbt build') + expect(rewriteDeferCommand('export OTHER="two words" DBT_STATE=/mine && dbt build', on)).toBe('export OTHER="two words" DBT_STATE=/mine && dbt build') + expect(rewriteDeferCommand('export OTHER="a;b" DBT_STATE=/mine DBT_TARGET=prod && dbt build', { ...on, target: 'qa', defaultTarget: 'dev' })).toBe('export OTHER="a;b" DBT_STATE=/mine DBT_TARGET=prod && dbt build') + expect(rewriteDeferCommand('export DBT_TARGET=prod && dbt build', { target: 'qa', defaultTarget: 'dev' })).toBe('export DBT_TARGET=prod && dbt build') + // The outer one holds a process substitution, which the parser cannot read, so it is left as written; the inner keeps its place. + expect(rewriteDeferCommand('dbt build <(dbt build)', on)).toBe('dbt build <(dbt build --defer --state /work/prod-state)') +}) + +test('a Windows session folder, with either slash, is the project it names', () => { + expect(runsInProject('dbt run', 'C:\\repo', 'C:/repo')).toBe(true) + expect(runsInProject('cd models && dbt run', 'C:/repo', 'C:\\repo')).toBe(true) + expect(runsInProject('cd C:\\other && dbt run', 'C:/repo', 'C:/repo')).toBe(false) + expect(runsInProject('cd a && dbt run', 'C:\\repo', 'C:/repo/a')).toBe(true) +}) + +test('a path with spaces is quoted', () => { + expect(rewriteDeferCommand('dbt run', { stateDir: "/my state/o'k" })).toBe(`dbt run --defer --state '/my state/o'\\''k'`) +}) + +test('the session target is added when the command names none, even when it is the default, since the environment may name another', () => { + const options = { target: 'prod', defaultTarget: 'dev' } + expect(rewriteDeferCommand('dbt run -s x', options)).toBe('dbt run --target prod -s x') + expect(rewriteDeferCommand('dbt run -t qa', options)).toBe('dbt run -t qa') + expect(rewriteDeferCommand('dbt run', { target: 'dev', defaultTarget: 'dev' })).toBe('dbt run --target dev') + expect(rewriteDeferCommand('dbt run', { ...on, ...options })).toBe('dbt run --defer --state /work/prod-state --target prod') +}) + +test('a favor-state option the command already has is not given a second one', () => { + const options = { ...on, favorState: true } + expect(rewriteDeferCommand('dbt --favor-state run', options)).toBe('dbt --favor-state run --defer --state /work/prod-state') + expect(rewriteDeferCommand('dbt run --no-favor-state', options)).toBe('dbt run --defer --state /work/prod-state --no-favor-state') + expect(rewriteDeferCommand('dbt run', options)).toBe('dbt run --defer --state /work/prod-state --favor-state') +}) + +test('a tab after --project-dir, an escaped folder word and a cd that may not run are not trusted', () => { + const run = (command: string) => runsInProject(command, '/repo/a', '/repo/a') + expect(run('dbt run --project-dir\t../b')).toBe(false) + expect(run('dbt run --project-dir\t../a')).toBe(true) + expect(run('cd nested\\ project && dbt run')).toBe(false) + expect(run('cd ../b; if false; then cd ../a; fi; dbt run')).toBe(false) + expect(run('false && cd ../a; dbt run')).toBe(false) + expect(run('cd ../b || cd ../a; dbt run')).toBe(false) + expect(run('cd models && cd .. && dbt run')).toBe(true) +}) + +test('DBT_FAVOR_STATE keeps its own choice and does not stop the deferral', () => { + const options = { ...on, favorState: true } + expect(rewriteDeferCommand('DBT_FAVOR_STATE=false dbt run', options)).toBe('DBT_FAVOR_STATE=false dbt run --defer --state /work/prod-state') + expect(rewriteDeferCommand('export DBT_FAVOR_STATE=true; dbt run', options)).toBe('export DBT_FAVOR_STATE=true; dbt run --defer --state /work/prod-state') +}) + +test('a cd that control flow, a pipeline, a background job or a glob may skip or redirect is not trusted', () => { + const run = (command: string) => runsInProject(command, '/repo/a', '/repo/a') + expect(run('cd ../b\nif false; then\n cd ../a\nfi\ndbt run')).toBe(false) + expect(run('if false; then echo skip; cd ../a; fi; dbt run')).toBe(false) + expect(run('for i in; do cd ../a; done; dbt run')).toBe(false) + expect(run('cd ../b; cd ../a | cat; dbt run')).toBe(false) + expect(run('cd ../b; cd ../a & dbt run')).toBe(false) + expect(run('cd nested* && dbt run')).toBe(false) + expect(run('cd models && dbt run')).toBe(true) +}) + +test('a cd with a redirection before a pipe or &, a cd inside quotes and a short directory option are not trusted', () => { + const run = (command: string) => runsInProject(command, '/repo/a', '/repo/a') + expect(run('cd ../b; cd ../a >/dev/null | cat; dbt run')).toBe(false) + expect(run('cd ../b; cd ../a 2>/dev/null & wait; dbt run')).toBe(false) + expect(run("cd ../b; echo 'example; cd ../a '; dbt run")).toBe(false) + expect(run('poetry run -C ../b dbt run')).toBe(false) + expect(run('cd models && dbt run | tee out')).toBe(true) +}) + +test('a cd is trusted only as the leading `cd a && cd b &&` chain, and option text inside quotes is no option', () => { + const run = (command: string) => runsInProject(command, '/repo/a', '/repo/a') + expect(run('cd ../b; false &&\ncd ../a; dbt run')).toBe(false) + expect(run('cd ../b; # example; cd ../a\ndbt run')).toBe(false) + expect(run('cd nonexistent; cd ..; dbt run')).toBe(false) + expect(run('cd ../b && dbt run --vars \'{"example": "--project-dir /repo/a "}\'')).toBe(false) + expect(run('cd models && cd .. && dbt run')).toBe(true) +}) + +test('a background cd chain, a pushd stack word, an option value that looks like --project-dir and a project at the root are handled', () => { + const run = (command: string) => runsInProject(command, '/repo/b', '/repo/a') + expect(run('cd ../a && dbt run & dbt test')).toBe(false) + expect(runsInProject('pushd ../b && pushd ../a && pushd +1 && dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(run('dbt run --exclude=--project-dir=/repo/a')).toBe(false) + expect(runsInProject('cd models && dbt run', '/', '/', () => false)).toBe(true) + expect(runsInProject('cd models && dbt run', '/', '/', dir => dir === '/models')).toBe(false) +}) + +test('a chain that may have stopped half way, a hidden cd and an option value shaped like --project-dir are not trusted', () => { + const run = (command: string) => runsInProject(command, '/repo/b', '/repo/a') + expect(runsInProject('cd ../b && cd missing && cd ../../a && dbt run; dbt test', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('cd ../b && cd ../missing/../a && dbt run || dbt test', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject("$'cd' ../b && dbt run", '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('dbt run --project\\\n-dir ../b', '/repo/a', '/repo/a')).toBe(false) + expect(run('dbt run --exclude --project-dir=/repo/a')).toBe(false) + expect(runsInProject('cd models && dbt run -s x && dbt test', '/repo/a', '/repo/a')).toBe(true) +}) + +test('the override decides, and the status text shows target and defer', () => { + const state: any = { projectDir: '/p', enabled: true, favorState: false, mode: 'local', stateDir: '/work/prod', reason: null, override: null, defaultTarget: 'dev', targets: ['dev', 'prod'], target: null, failedAt: null } + expect(statusText(state)).toBe('dbt dev · defer prod') + expect(effective(state).stateDir).toBe('/work/prod') + expect(effective({ ...state, override: false }).stateDir).toBeNull() + expect(statusText({ ...state, override: false, target: 'prod' })).toBe('dbt prod') + expect(statusText({ ...state, projectDir: null })).toBeNull() +}) + +const ROOT = '/repo' + +/** A dbt project at /repo whose defer setting the CLI reports as `answer`; Bash commands are recorded. */ +function start($: any, on: any, answer: Record, fail: { times: number } = { times: 0 }, projects: string[] = [ROOT]) { + const bash: string[] = [] + const statuses: (string | undefined)[] = [] + const reads: string[] = [] + const clock = mock.clock(on) + on('command.register', (_: unknown, e: any) => ({ value: { command: e.name } })) + on('session.start', (_: unknown, e: { cwd: string }) => ({ cwd: e.cwd })) + on('session.root', () => ({ value: ROOT })) + on('fs.exists', (_: unknown, e: { path: string }) => ({ value: projects.some(dir => e.path === `${dir}/dbt_project.yml`) })) + on('process.run', (_: unknown, e: { readonly argv: readonly string[] }) => { + if (!e.argv.includes('dbt_defer_state')) return { value: { exitCode: 0, stdout: '{}', stderr: '' } } + reads.push(e.argv.join(' ')) + if (fail.times-- > 0) return { value: { exitCode: 1, stdout: '', stderr: 'not ready' } } + return { + value: { exitCode: 0, stdout: JSON.stringify({ status: 'success', output: '', metadata: { success: true, ...answer } }), stderr: '' }, + } + }) + on('ui.status', (_: unknown, e: any) => { + statuses.push(e.text) + return { value: undefined } + }) + on('tool.call', (_: unknown, e: any) => { + bash.push(e.command) + return { result: { ok: true } } + }) + return { bash, statuses, reads, clock } +} + +const DEFER = { enabled: true, favorState: true, mode: 'local', stateDir: '/work/prod-state', defaultTarget: 'dev', targets: ['dev', 'prod'] } + +test('through the plugin, Claude’s dbt commands run with --defer --state when the project setting is on', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'dbt build -s x' }) + await $.tool.call({ tool: 'Bash', command: 'dbt build --state ./mine' }) + expect(seen.bash).toEqual(['dbt build --defer --state /work/prod-state --favor-state -s x', 'dbt build --state ./mine']) + expect(seen.statuses.at(-1)).toContain('dbt dev · defer prod-state') +}) + +test('a dbt project below the project, even under dbt_packages, keeps its own settings; the shell folder from an earlier cd counts', async ($, on) => { + const seen = start($, on, DEFER, { times: 0 }, [ROOT, `${ROOT}/dbt_packages/pkg`, `${ROOT}/nested`]) + let cwd = ROOT + on('session.cwd', () => ({ value: cwd })) + on('fs.list', (_: unknown, e: { path: string }) => ({ value: e.path === ROOT ? [{ name: 'nested', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }, { name: 'dbt_packages', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }] : e.path === `${ROOT}/dbt_packages` ? [{ name: 'pkg', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }] : [] })) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'cd nested && dbt build' }) + cwd = `${ROOT}/dbt_packages/pkg` + await $.tool.call({ tool: 'Bash', command: 'dbt build' }) + cwd = `${ROOT}/models` + await $.tool.call({ tool: 'Bash', command: 'dbt build' }) + expect(seen.bash).toEqual(['cd nested && dbt build', 'dbt build', 'dbt build --defer --state /work/prod-state --favor-state']) +}) + +test('/defer off stops the rewrite for the session, /defer on brings it back, /target adds --target', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + const run = (command: string, args: string) => $.command.run({ command, args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 120 } }) + + expect((await run('defer', 'off')).text).toContain('Defer off') + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + expect((await run('defer', 'on')).text).toContain('Defer on') + expect((await run('target', 'prod')).text).toContain('--target prod') + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + expect((await run('target', 'nope')).text).toContain('No target "nope"') + expect((await run('defer', 'status')).text).toContain('state: /work/prod-state (favor state)') + expect(seen.bash).toEqual(['dbt run', 'dbt run --defer --state /work/prod-state --favor-state --target prod']) +}) + +test('with defer off in the project nothing is rewritten and /defer on says why it cannot', async ($, on) => { + const seen = start($, on, { enabled: false, mode: 'none', defaultTarget: 'dev', targets: ['dev'] }) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + const reply = await $.command.run({ command: 'defer', args: 'on', origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 120 } }) + expect(reply.text).toContain('cannot be turned on') + expect(seen.bash).toEqual(['dbt run']) +}) + +test('a configured but switched-off setting can be turned on for the session', async ($, on) => { + const seen = start($, on, { ...DEFER, enabled: false }) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + const run = (command: string, args: string) => $.command.run({ command, args, origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 120 } }) + expect((await run('defer', 'on')).text).toContain('Defer on') + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + expect(seen.bash).toEqual(['dbt run', 'dbt run --defer --state /work/prod-state --favor-state']) +}) + +test('a dbt command for another project is left as it is', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'cd ../other && dbt run' }) + await $.tool.call({ tool: 'Bash', command: 'dbt run --project-dir ../other' }) + await $.tool.call({ tool: 'Bash', command: 'cd models && dbt run' }) + expect(seen.bash).toEqual(['cd ../other && dbt run', 'dbt run --project-dir ../other', 'cd models && dbt run --defer --state /work/prod-state --favor-state']) +}) + +test('the setting is read once, on the first dbt command, and a command without dbt reads nothing', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'ls' }) + expect(seen.reads).toEqual([]) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + await $.tool.call({ tool: 'Bash', command: 'dbt test' }) + expect(seen.reads.length).toBe(1) +}) + +test('a read that failed is tried again after a minute, not for the rest of the session', async ($, on) => { + const seen = start($, on, DEFER, { times: 1 }) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + await seen.clock.advance(61_000) + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + expect(seen.bash).toEqual(['dbt run', 'dbt run', 'dbt run --defer --state /work/prod-state --favor-state']) + expect(seen.reads.length).toBe(2) +}) + +test('a new session clears the status line and the overrides of the one before', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.command.run({ command: 'target', args: 'prod', origin: { kind: 'composer' }, presentation: { isFullscreen: false, columns: 120 } }) + expect(seen.statuses.at(-1)).toContain('dbt prod') + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + expect(String(seen.statuses.at(-1))).not.toContain('dbt prod') + await $.tool.call({ tool: 'Bash', command: 'dbt run' }) + expect(seen.bash.at(-1)).toBe('dbt run --defer --state /work/prod-state --favor-state') +}) + +test('a command that only mentions dbt does not read the setting', async ($, on) => { + const seen = start($, on, DEFER) + await $.session.start({ cwd: ROOT, surface: 'terminal', isInteractive: true }) + await $.tool.call({ tool: 'Bash', command: 'cat dbt_project.yml' }) + await $.tool.call({ tool: 'Bash', command: 'git commit -m "dbt"' }) + expect(seen.reads).toEqual([]) + expect(seen.bash).toEqual(['cat dbt_project.yml', 'git commit -m "dbt"']) +}) + +test('an invocation with a word the parser cannot read is left as it is, however the word is written', () => { + const both = { ...on, target: 'qa', defaultTarget: 'dev' } + for (const command of ['dbt --target "$T" run', 'dbt run --target "$T"', 'dbt run "--target" "$T"', 'dbt run $FLAGS', 'dbt run "${FLAGS[@]}"', 'dbt run `printf -- --no-defer`', 'dbt run -t $T', 'dbt run --profiles-dir ~/.dbt']) { + expect(rewriteDeferCommand(command, both)).toBe(command) + } +}) + +test('a project word that goes on after its quotes is not one the settings are judged for', () => { + expect(runsInProject('dbt run --project-dir "."/../b', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('DBT_PROJECT_DIR="."/../b dbt run', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('dbt run --project-dir "."', '/repo/a', '/repo/a')).toBe(true) +}) + +/** An engine whose dbt projects are the given folders (a link counts: exists follows it). */ +const withProjects = (...dirs: string[]): any => ({ fs: { exists: async (file: string) => dirs.some(dir => file === `${dir}/dbt_project.yml`) } }) + +test('a dbt project of its own below the project keeps its own settings, at any depth and through a link', async () => { + const $ = withProjects('/repo', '/repo/examples/tutorials/dbt/shop', '/repo/linked') + expect(await runsHere($, 'cd examples/tutorials/dbt/shop && dbt build', '/repo', '/repo')).toBe(false) + expect(await runsHere($, 'cd linked && dbt build', '/repo', '/repo')).toBe(false) + expect(await runsHere($, 'dbt build', '/repo/examples/tutorials/dbt/shop', '/repo')).toBe(false) + expect(await runsHere($, 'cd models && dbt build', '/repo', '/repo')).toBe(true) + expect(await runsHere($, 'dbt build', '/repo', '/repo')).toBe(true) +}) + +test('on a Windows project path a nested dbt project is found in the form the command is compared in', async () => { + const $ = withProjects('C:/repo/nested') + expect(await runsHere($, 'cd nested && dbt build', 'C:\\repo', 'C:\\repo')).toBe(false) + expect(await runsHere($, 'cd models && dbt build', 'C:\\repo', 'C:\\repo')).toBe(true) +}) + +test('a Windows --project-dir with backslashes names the project; an escaped space still does not', () => { + expect(runsInProject('dbt run --project-dir ".\\repo"', 'C:/repo', 'C:/repo/repo')).toBe(true) + // Unquoted, the shell eats the backslash: `.\repo` is `.repo`. + expect(runsInProject('dbt run --project-dir .\\repo', 'C:/repo', 'C:/repo/repo')).toBe(false) + expect(runsInProject('dbt run --project-dir "C:\\other"', 'C:/repo', 'C:/repo')).toBe(false) + expect(runsInProject('dbt run --project-dir ./a\\ b', '/repo', '/repo/a')).toBe(false) +}) + +test('a flag that takes no value before --project-dir leaves it a real option, and a wrapper keeps the assignment before it', () => { + expect(runsInProject('dbt run --full-refresh --project-dir /repo/a', '/repo/b', '/repo/a')).toBe(true) + expect(runsInProject('dbt run --full-refresh --project-dir ../b', '/repo/a', '/repo/a')).toBe(false) + expect(runsInProject('dbt run --exclude --project-dir=/repo/a', '/repo/b', '/repo/a')).toBe(false) + const options = { stateDir: '/work/prod-state', favorState: true } + expect(rewriteDeferCommand('DBT_FAVOR_STATE=false command dbt run', options)).toBe('DBT_FAVOR_STATE=false command dbt run --defer --state /work/prod-state') + expect(rewriteDeferCommand('DBT_FAVOR_STATE=false env dbt run', options)).toBe('DBT_FAVOR_STATE=false env dbt run --defer --state /work/prod-state') + expect(rewriteDeferCommand('echo hi; dbt run', options)).toBe('echo hi; dbt run --defer --state /work/prod-state --favor-state') +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index c37aa855..f913afb1 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -5,16 +5,416 @@ // 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 { atom, read, update } from 'claude-code' import type { Args, EngineInterface, EventResult, On, RenderElement, ToolCallResult } from 'claude-code' +import { runTool } from '../altimate-cli' +import { parseDbtCommand } from '../dbt-command' +import { setStatusPart } from '../status-line' import type { BashCall, ContextLines, EditedFile, FileCall } from '../tool-chain' +import type { DeferState } from '../../types' import type { BandUi, FeatureContext } from './index' +const deferAtom = atom({ plugin: 'altimate-code', key: 'defer' } as const, null as DeferState | null) + +// The commands that take `--defer` in every dbt version this reads state for (older dbt refuses the option on +// `ls`, `parse`, `seed`, `run-operation` and others, and `retry` reads the previous run's results from `--state`). +const DEFERS = new Set(['build', 'run', 'test', 'compile', 'show', 'snapshot']) +// Commands that take no target, or take it after a second word (`source freshness`, `docs generate`) this does not read. +const NO_TARGET = new Set(['deps', 'clean', 'init', 'retry', 'docs', 'source']) + +// dbt options that take no value: one of these before `--project-dir` leaves it a real option of the command. +const FLAG_ONLY = new Set(['full-refresh', 'fail-fast', 'x', 'debug', 'quiet', 'q', 'warn-error', 'version-check', 'no-version-check', 'partial-parse', 'no-partial-parse', 'static-parser', 'no-static-parser', 'use-colors', 'no-use-colors', 'defer', 'no-defer', 'favor-state', 'no-favor-state', 'store-failures', 'empty', 'no-print', 'print', 'log-cache-events', 'introspect', 'no-introspect', 'write-json', 'no-write-json']) +// The command's own text from the start of its simple command (after `;`, `&`, `|`, a newline or a bracket), so an assignment or a wrapper before `dbt` counts. +const segmentStart = (command: string, index: number) => Math.max(command.slice(0, index).search(/[^;&|(){}\n]*$/), 0) + +const quote = (text: string) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`) + +export type RewriteOptions = { + /** The directory to defer to; null or undefined means defer is off. */ + stateDir?: string | null + favorState?: boolean + /** The session's target, chosen with /target; added to a command without one, even when it is the profile's default, since the environment may say another. */ + target?: string | null + defaultTarget?: string | null +} + +/** + * The shell command with `--defer --state ` (and `--favor-state`) and `--target ` inserted + * right after the subcommand of each dbt invocation that does not already set them; the command itself + * when nothing needs to change. An invocation with a word the parser cannot read (`$FLAGS`, `~/x`, a glob) is left as written. + */ +export function rewriteDeferCommand(command: string, options: RewriteOptions): string { + const { stateDir, favorState = false, target } = options + if (!stateDir && !target) return command + let out = command + // DBT_STATE or DBT_TARGET exported in the line is the user's own choice: none of its dbt commands gets the flag + // (a line with an `export` and the variable anywhere in it counts, whatever the quoting). + const exportedState = /\bexport\b/.test(command) && /\bDBT_(?:STATE|DEFER|DEFER_STATE)=/.test(command) + const exportedTarget = /\bexport\b/.test(command) && /\bDBT_TARGET=/.test(command) + // From the last invocation to the first, so the offsets of those before stay right. + for (const one of [...parseDbtCommand(command)].sort((a, b) => b.subcommandEnd - a.subcommandEnd)) { + if (!one.subcommand) continue + // The parser cannot say what the shell passes to dbt for a word that holds an expansion, a glob or a `~`, and a flag + // may be among them: such an invocation is left as the user wrote it, as the parser's contract asks. + if (one.dynamic) continue + const flags: string[] = [] + const ownText = command.slice(segmentStart(command, one.start), one.end) + if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE)=/.test(ownText)) { + // The command's own favor-state choice, in a flag or the environment, stands. + const own = /--(?:no-)?favor-state\b|\bDBT_FAVOR_STATE=/.test(ownText) || (/\bexport\b/.test(command) && /\bDBT_FAVOR_STATE=/.test(command)) + flags.push('--defer', '--state', quote(stateDir), ...(favorState && !own ? ['--favor-state'] : [])) + } + if (target && !NO_TARGET.has(one.subcommand) && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(ownText)) flags.push('--target', quote(target)) + if (flags.length === 0) continue + out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` + } + return out +} + +type DeferAnswer = { + success?: boolean + enabled?: boolean + favorState?: boolean + mode?: 'local' | 'remote' | 'none' + stateDir?: string + reason?: string + defaultTarget?: string + targets?: string[] +} + +const dirname = (path: string) => path.replace(/[\\/]+[^\\/]*$/, '') || '/' + +/** The dbt project the session works in: the folder or one above it with a dbt_project.yml, else the only one a level below. */ +async function findProject($: EngineInterface): Promise { + // A call that throws at once (an engine without a session) is no project either. + const root = await Promise.resolve().then(() => $.session.root()).catch(() => null) + if (!root) return null + for (let dir = root, i = 0; i < 40; i++) { + if (await $.fs.exists(`${dir}/dbt_project.yml`).catch(() => false)) return dir + const parent = dirname(dir) + if (parent === dir) break + dir = parent + } + const below: string[] = [] + for (const entry of await $.fs.list(root).catch(() => [])) { + if (entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules') continue + if (await $.fs.exists(`${root}/${entry.name}/dbt_project.yml`).catch(() => false)) below.push(`${root}/${entry.name}`) + } + return below.length === 1 ? below[0]! : null +} + +/** Whether the word before is an option that takes a value, which this word would then be: not one of dbt's flags that take none. */ +const valueOfPrevious = (before: string) => { + const prev = /(?:^|\s)-{1,2}([\w-]+)\s+$/.exec(before) + return !!prev && !FLAG_ONLY.has(prev[1]!) +} + +/** + * Whether the command's dbt runs in the project: `runsInProject`, with the folders it asks about checked + * for a dbt_project.yml of their own. A folder below the project that holds one has its own settings, at any + * depth and through a link; no folder tree is scanned. + */ +export async function runsHere($: EngineInterface, command: string, root: string, projectDir: string): Promise { + const asked = new Set() + // A first pass with no nested project: a nested one only narrows the answer, so a no here is final. + if (!runsInProject(command, root, projectDir, dir => (asked.add(dir), false))) return false + if (asked.size === 0) return true + const owned = new Set() + for (const dir of asked) if (await $.fs.exists(`${dir}/dbt_project.yml`).catch(() => false)) owned.add(dir) + return runsInProject(command, root, projectDir, dir => owned.has(dir)) +} + +/** Whether the character at `index` is inside single or double quotes. */ +function quoted(text: string, index: number): boolean { + let open: string | null = null + for (let i = 0; i < index; i++) { + const c = text[i]! + if (open === null && c === '\\') i++ + else if (open === null && (c === "'" || c === '"')) open = c + else if (open === '"' && c === '\\') i++ + else if (c === open) open = null + } + return open !== null +} + +// Where a command runs from: the session folder, moved by each `cd` or `pushd` in the command. +const CD = /(?:^|[;&|(\n{!]\s*|\b(?:if|elif|while|until|then|do|else|time)\s+)(?:cd|pushd)[ \t]+("[^"]+"|'[^']+'|[^\s;&|)]+)/gm +const PROJECT_DIR = /(?:--project-dir[\s=]|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g +const UNQUOTE = /^['"]|['"]$/g + +/** `target` seen from `base`, as an absolute path with forward slashes (a drive letter kept); null when it cannot be known. */ +function resolvePath(base: string, target: string): string | null { + if (/^~|[$`]/.test(target)) return null + const from = base.replace(/\\/g, '/') + const to = target.replace(/\\/g, '/') + const drive = /^[A-Za-z]:/.exec(to)?.[0] ?? /^[A-Za-z]:/.exec(from)?.[0] ?? '' + const path = /^[A-Za-z]:\//.test(to) ? to.slice(2) : to.startsWith('/') ? to : `${from.slice(drive.length)}/${to}` + const out: string[] = [] + for (const part of path.split('/')) { + if (part === '' || part === '.') continue + if (part === '..') out.pop() + else out.push(part) + } + return `${drive}/${out.join('/')}` +} + +/** + * Whether the command's dbt runs in the project the settings were read for: not when it moves to another + * folder (`cd`, `pushd`, `--project-dir`, `DBT_PROJECT_DIR`, uv's `--directory`) or one it cannot work out. + * The check reads the command's text, not the filesystem: a link that leads into another project's folders, and a + * `DBT_PROJECT_DIR` inherited from the session's own environment, are not seen. That is the known limit of this check. + */ +export function runsInProject(command: string, root: string, projectDir: string, isProject: (dir: string) => boolean = () => false): boolean { + // A folder change this does not follow (`popd`, `env -C`, `command cd`, a `cd` with no folder) leaves the folder unknown. + // Quotes and backslashes are dropped for this check: `command 'cd' ../b` and `env "-C" ../b` change folder like their plain forms. + const plain = command.replace(/["'\\]/g, '') + if (/\s--(?:directory|project)[\s=]|\s-C/.test(plain)) return false + if (/(?:^|[\s;&|(){}!])(?:popd|chdir)(?=[\s;&|)]|$)|\benv\s+(?:\S+\s+)*(?:-C|--chdir)\b/.test(plain)) return false + // Control flow (`if`, a loop, `case`) can skip a `cd`: the folder is unknown once a `cd` is among it. + // Quoting forms that hide a word from the checks below (`$'cd'`, a line continuation inside an option). + if (/\$['"]|\\\n/.test(command)) return false + const control = /(?:^|[\s;&|(){}!])(?:if|then|else|elif|fi|while|until|do|done|for|case|esac|select)(?=[\s;&|)]|$)/.test(plain) + const cdWords = plain.match(/(?:^|[\s;&|(){}!`])(?:cd|pushd)(?=[\s;&|)]|$)/g)?.length ?? 0 + if (cdWords !== [...command.matchAll(CD)].length) return false + if (cdWords > 0 && control) return false + // A `&` (not `&&` or a redirection) sends the commands before it to a background shell: the folder the rest runs in is unknown. + if (cdWords > 0 && /&/.test(command.replace(/&&|>&|&>|\d*[<>]&\d*/g, ''))) return false + // A folder change is trusted only as the leading `cd a && cd b && dbt ...` chain: after it, only a command that runs because every `cd` worked. + // A `cd` after a `;`, a newline, a comment, `||`, a pipe or anywhere later may be skipped, fail or run elsewhere. + if (cdWords > 0) { + const rest = command.replace(/^\s*(?:(?:cd|pushd)[ \t]+(?:"[^"]*"|'[^']*'|[^\s;&|()<>`$\\*?[\]{}'"]+)[ \t]*&&[ \t]*)*/, '') + if (/(?:^|[\s;&|(){}!`])(?:cd|pushd|popd|chdir)(?=[\s;&|)]|$)/.test(rest.replace(/["'\\]/g, ''))) return false + // After a chain that may have stopped half way, only commands that run because it all worked: no `;`, `||` or new line. + if (rest !== command && /;|\|\||\n/.test(rest)) return false + } + // A folder change inside a subshell or command substitution leaves the parent's folder unchanged or unknown. + if (cdWords > 0 && /[(`]/.test(plain)) return false + const invocations = parseDbtCommand(command) + // The outermost command that starts first, not an invocation inside a `<(...)` that ends up first in the list. + const first = [...invocations].sort((a, b) => a.start - b.start)[0] + const project = resolvePath(projectDir, '.') + if (!first || !project) return false + const base = project.replace(/\/+$/, '') + // A folder below the project that holds a dbt project of its own has its own settings. + const ownsProject = (dir: string) => { + for (let d = dir; d.startsWith(`${base}/`); ) { + if (isProject(d)) return true + const up = dirname(d) + if (up === d) break + d = up + } + return false + } + const inside = (dir: string | null) => !!dir && (dir === project || (dir.startsWith(`${base}/`) && !ownsProject(dir))) + const windows = /^[A-Za-z]:/.test(projectDir) + let dir = resolvePath(root, '.') + let before = dir + for (const match of command.matchAll(CD)) { + if (!dir) return false + // A folder word with an escape (`nested\ project`) is cut short by the pattern: not a folder this can work out. + if (/\\/.test(match[1]!) && !(windows && /^['"]/.test(match[1]!))) return false + // A glob in the folder word may name a folder this does not see. + if (/[*?[\]{}]/.test(match[1]!)) return false + // A `cd` that may not run (after `||`, after another command in an `&&` list, inside `if`, `then` or a loop) leaves the folder unknown. + const at = match.index + match[0].search(/(?:cd|pushd)[ \t]+/) + const lead = command.slice(0, at) + if (!/^\s*(?:(?:cd|pushd)[ \t]+\S+\s*&&\s*)*$/.test(lead.slice(Math.max(lead.lastIndexOf(';'), lead.lastIndexOf('\n')) + 1))) return false + // A `cd` in a pipeline or a background job (a redirection may come first) runs in a subshell and leaves this folder as it was. + const rest = command.slice(match.index + match[0].length).split(/&&|\|\||;|\n/)[0]!.replace(/\d*>&\d*-?|&>>?|\d*[<>]+/g, ' ') + if (/[|&]/.test(rest)) return false + // A `cd` inside quotes is text another command prints, not a folder change. + if (quoted(command, at)) return false + // A folder word that goes on after its quotes (`"."/..`) is not one this can work out. + if (!/^(?:[\s;&|)]|$)/.test(command.slice(match.index + match[0].length))) return false + const word = match[1]!.replace(UNQUOTE, '') + // `cd -P dir`, `cd -`: not a folder this can work out. + dir = /^[-+]/.test(word) ? null : resolvePath(dir, word) + if (match.index < first.start) before = dir + else if (!inside(dir)) return false + } + // A project named outright is the one to judge; otherwise the folder the command runs from. + // An option word starts after whitespace: `--exclude=--project-dir=x` is another option's value. + const named = [...command.matchAll(PROJECT_DIR)].filter(match => !quoted(command, match.index) && (match.index === 0 || /\s/.test(command[match.index - 1]!)) && !valueOfPrevious(command.slice(0, match.index))) + // A project option written with quotes (`"--project-dir" ../b`) is only seen in the plain copy: unknown. + if (named.length !== (plain.match(/--project-dir[\s=]|\bDBT_PROJECT_DIR=/g)?.length ?? 0)) return false + // A path word that goes on after its quotes (`--project-dir "."/../b`) is not one this can work out. + // An escaped word (`./a\ b`) is cut short by this pattern at the escaped space: not a path this can work out. + // On a Windows project path a backslash separates folders; elsewhere any backslash may be an escape. + // In an unquoted word the shell eats a backslash as an escape, so only a quoted word keeps it as a separator. + if (named.some(match => (windows && /^['"]/.test(match[1]!) ? /\\$/.test(match[1]!) : match[1]!.includes('\\')))) return false + if (named.some(match => !/^(?:[\s;&|)]|$)/.test(command.slice(match.index + match[0].length)))) return false + if (named.length === 0) return inside(before) + // Only a single dbt invocation, with the project named inside it, is judged: elsewhere in the line it is another command's. + if (invocations.length !== 1 || !before) return false + if (named.some(match => match.index < first.start || match.index >= first.end)) return false + // Exactly the project: a folder below it may be a separate dbt project with its own settings. + return named.every(match => resolvePath(before!, match[1]!.replace(UNQUOTE, '')) === project) +} + +/** The flags the state's override and answer lead to: the state dir only while defer is on. */ +export function effective(state: DeferState | null): RewriteOptions { + if (!state) return {} + const on = state.override ?? state.enabled + return { + stateDir: on ? state.stateDir : null, + favorState: state.favorState, + target: state.target, + defaultTarget: state.defaultTarget, + } +} + +/** The status line's part: "dbt dev · defer prod" (target, then defer). */ +export function statusText(state: DeferState | null): string | null { + if (!state?.projectDir) return null + const target = state.target ?? state.defaultTarget + const on = state.override ?? state.enabled + const parts: string[] = [] + if (target) parts.push(`dbt ${target}`) + if (on && state.stateDir) parts.push(`defer ${state.stateDir.split(/[\\/]/).filter(Boolean).pop() ?? 'on'}`) + return parts.length ? parts.join(' · ') : null +} + +async function load($: EngineInterface, previous: DeferState | null): Promise { + const projectDir = await findProject($) + const state: DeferState = { + projectDir, + enabled: false, + favorState: false, + mode: 'none', + stateDir: null, + reason: null, + override: previous?.override ?? null, + defaultTarget: null, + targets: [], + target: previous?.target ?? null, + failedAt: null, + } + if (!projectDir) return state + const answer = await runTool($, 'dbt_defer_state', { project_dir: projectDir }, { cliOnly: true }).catch(() => null) + const data = answer?.ok && (answer.metadata as DeferAnswer | null)?.success !== false ? (answer.metadata as DeferAnswer | null) : null + if (!data) return { ...state, reason: answer?.text || 'altimate-code did not answer', failedAt: await $.clock.now() } + return { + ...state, + enabled: data.enabled === true && typeof data.stateDir === 'string', + favorState: data.favorState === true, + mode: data.mode ?? 'none', + stateDir: data.stateDir ?? null, + reason: data.reason ?? null, + defaultTarget: data.defaultTarget ?? null, + targets: data.targets ?? [], + } +} + +// The read in flight, shared by whoever needs the answer first. +let loading: Promise | null = null +// Counts the sessions: an answer read for an earlier one is dropped. +let generation = 0 +// A read that failed (the CLI timed out or was not ready) is tried again after this long. +const RETRY_MS = 60_000 + +/** The state the project's setting gives, read on first need and kept for the session (a failed read is tried again after a minute); /defer reset reads it again. */ +async function ensure($: EngineInterface): Promise { + const have = await read($, deferAtom) + if (have && (have.failedAt === null || (await $.clock.now()) - have.failedAt < RETRY_MS)) return have + const mine = generation + const started = (loading ??= load($, have).then(async state => { + if (mine === generation) await publish($, state) + return state + })) + let state: DeferState + try { + state = await started + } finally { + // Another session's read must not be dropped by a caller that was waiting on this one; a read that rejected is not kept. + if (loading === started) loading = null + } + return mine === generation ? state : await ensure($) +} + +async function publish($: EngineInterface, state: DeferState) { + await update($, deferAtom, () => state) + await setStatusPart($, 'defer', statusText(state)).catch(() => {}) +} + +function describe(state: DeferState | null): string { + if (!state?.projectDir) return 'defer: no dbt project found in this folder.' + const on = state.override ?? state.enabled + const lines = [ + `defer: ${on && state.stateDir ? 'on' : 'off'}${state.override !== null ? ` (set with /defer ${state.override ? 'on' : 'off'} for this session)` : ''}`, + `project: ${state.projectDir}`, + `mode: ${state.mode}`, + ] + if (state.stateDir) lines.push(`state: ${state.stateDir}${state.favorState ? ' (favor state)' : ''}`) + if (state.reason) lines.push(`note: ${state.reason}`) + lines.push(`target: ${state.target ?? state.defaultTarget ?? 'profile default'}${state.target ? ' (session)' : ''}`) + if (state.targets.length) lines.push(`targets: ${state.targets.join(', ')}`) + return lines.join('\n') +} + /** Adds this feature's own hooks. */ -export function register(on: On, context: FeatureContext) {} +export function register(on: On, context: FeatureContext) { + on('command.run', { command: 'defer' }, async ($, e) => { + const word = e.args.trim().toLowerCase() + const started = generation + let state = await ensure($) + if (word === 'on' || word === 'off') { + if (word === 'on' && !state.stateDir) { + if (started === generation) await publish($, state) + return { text: `Defer cannot be turned on: ${state.reason ?? 'no state directory is configured for this project (dbt.deferConfigPerProject).'}` } + } + state = { ...state, override: word === 'on' } + // A session that started while the setting was read has its own state. + if (started === generation) await publish($, state) + return { text: `Defer ${word} for this session.\n${describe(state)}` } + } + if (word === 'reset') { + state = await load($, null) + // A session that started before this command's reads finished has its own state. + if (started === generation) await publish($, state) + return { text: `Defer and target back to the project's settings.\n${describe(state)}` } + } + if (word === '' || word === 'status') { + return { text: describe(state) } + } + return { text: 'Usage: /defer [status|on|off|reset]' } + }) -/** After the session started: the place to register commands. */ -export async function sessionStart($: EngineInterface, e: Args<'session.start'>) {} + on('command.run', { command: 'target' }, async ($, e) => { + const name = e.args.trim() + const started = generation + let state = await ensure($) + if (name === '') { + return { text: `target: ${state.target ?? state.defaultTarget ?? 'profile default'}${state.target ? ' (session)' : ''}${state.targets.length ? `\ntargets: ${state.targets.join(', ')}` : ''}` } + } + if (name === 'reset') { + state = { ...state, target: null } + // A session that started while the setting was read has its own state. + if (started === generation) await publish($, state) + return { text: `Target back to the profile default${state.defaultTarget ? ` (${state.defaultTarget})` : ''}.` } + } + if (!/^[\w.-]+$/.test(name)) return { text: `Not a target name: ${name}` } + if (state.targets.length && !state.targets.includes(name)) { + return { text: `No target "${name}" in the profile. Targets: ${state.targets.join(', ')}` } + } + if (!state.projectDir) return { text: 'No dbt project found in this folder, so there is no target to set.' } + state = { ...state, target: name } + if (started === generation) await publish($, state) + return { text: `dbt commands now run with --target ${name} (this session).` } + }) +} + +/** After the session started: registers the commands. The project's setting is read when first needed. */ +export async function sessionStart($: EngineInterface, e: Args<'session.start'>) { + await $.command.register({ name: 'defer', description: "Show or set whether dbt commands defer to the production manifest", argumentHint: '[status|on|off|reset]' }) + await $.command.register({ name: 'target', description: "Set the dbt target for this session's dbt commands", argumentHint: '[|reset]' }) + // A new session starts from the project's own settings, not from the last one's overrides. + generation++ + loading = null + await update($, deferAtom, () => null) + // Clearing the line is cosmetic: an engine that cannot draw it does not stop the session. + await setStatusPart($, 'defer', null).catch(() => {}) +} /** Also called for a subagent's turns, which carry `e.agentId`. */ export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} @@ -31,7 +431,16 @@ export async function bandLine($: EngineInterface, ui: BandUi): Promise { - return null + // Most commands name no dbt: they never cost the settings read. + if (!/\bdbt\b/.test(e.command) || parseDbtCommand(e.command).length === 0) return null + const state = await ensure($) + if (!state.projectDir) return null + // The folder the session's shell is in now: an earlier `cd` in the session moves it, which the project root does not. + const root = (await $.session.cwd().catch(() => null)) ?? (await $.session.root().catch(() => null)) + if (!root) return null + if (!(await runsHere($, e.command, root, state.projectDir))) return null + const command = rewriteDeferCommand(e.command, effective(state)) + return command === e.command ? null : command } /** diff --git a/plugins/altimate-code/types/index.d.ts b/plugins/altimate-code/types/index.d.ts index 554d4010..3c6926b0 100644 --- a/plugins/altimate-code/types/index.d.ts +++ b/plugins/altimate-code/types/index.d.ts @@ -223,7 +223,27 @@ export interface RunsState {} // Defer and target: the target and defer state dbt commands run with. // Filled in by that feature alone (hooks/features/); the other features never read or write it. // --------------------------------------------------------------------------------------------------- -export interface DeferState {} +export interface DeferState { + /** The dbt project the session works in; null when there is none (nothing is rewritten). */ + projectDir: string | null + /** The project's Power User setting turns defer on and gives a usable state directory. */ + enabled: boolean + favorState: boolean + mode: 'local' | 'remote' | 'none' + /** The directory passed as `--state`; null when there is none to use. */ + stateDir: string | null + /** Why defer is configured but cannot be applied. */ + reason: string | null + /** /defer on or off for this session; null follows the project's setting. */ + override: boolean | null + /** The profile's default target and its output names. */ + defaultTarget: string | null + targets: string[] + /** /target for this session; null leaves the command's own or the profile's default. */ + target: string | null + /** When reading the setting failed (engine clock, ms); null when it was read. */ + failedAt: number | null +} // --------------------------------------------------------------------------------------------------- // Raw SQL to model: the SQL being turned into a dbt model.