From ec4a19cae378eb7ee34987085107923195e34af3 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:03:12 +0530 Subject: [PATCH 01/27] =?UTF-8?q?feat:=20defer=20and=20target=20=E2=80=94?= =?UTF-8?q?=20dbt=20commands=20run=20with=20--defer=20--state,=20/defer=20?= =?UTF-8?q?and=20/target?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Claude's dbt commands get --defer --state (and --favor-state) right after the subcommand when the project's Power User defer setting is on, unless the command already sets them. /defer status|on|off|reset and /target change this for the session; the status line shows the target and defer state. Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 112 +++++++++ .../altimate-code/hooks/features/defer.tsx | 223 +++++++++++++++++- plugins/altimate-code/types/index.d.ts | 20 +- 3 files changed, 350 insertions(+), 5 deletions(-) create mode 100644 plugins/altimate-code/hooks/features/defer.test.ts 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..83be0731 --- /dev/null +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -0,0 +1,112 @@ +import { expect, mock, test } from 'claude-code/testing' + +import { effective, rewriteDeferCommand, 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('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') + expect(rewriteDeferCommand('dbt deps', on)).toBe('dbt deps') +}) + +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 it differs from the default and the command names none', () => { + 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') + expect(rewriteDeferCommand('dbt run', { ...on, ...options })).toBe('dbt run --defer --state /work/prod-state --target prod') +}) + +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 } + 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) { + const bash: string[] = [] + const statuses: (string | undefined)[] = [] + 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: e.path === `${ROOT}/dbt_project.yml` })) + on('process.run', (_: unknown, e: { readonly argv: readonly string[] }) => ({ + 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 } +} + +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('/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']) +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index f0959592..04035df2 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -5,16 +5,226 @@ // 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) + +/** dbt commands that read no project graph: they get neither the defer flags nor a target. */ +const NO_FLAGS = new Set(['deps', 'clean', 'debug', 'init', 'retry', 'docs', 'source']) + +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; added to a command without one when it differs from the profile's default. */ + 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. + */ +export function rewriteDeferCommand(command: string, options: RewriteOptions): string { + const { stateDir, favorState = false, target, defaultTarget } = options + if (!stateDir && !target) return command + let out = command + // From the last invocation to the first, so the offsets of those before stay right. + for (const one of parseDbtCommand(command).reverse()) { + if (!one.subcommand || NO_FLAGS.has(one.subcommand)) continue + const flags: string[] = [] + if (stateDir && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) + if (target && target !== defaultTarget && one.target === null) 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 = { + 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 { + const root = await $.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 +} + +/** 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, + } + 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) : null + if (!data) return { ...state, reason: answer?.text ?? 'altimate-code did not answer' } + 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 first answer of the session, shared by whoever needs it first. +let loading: Promise | null = null + +/** The state the project's setting gives, read once per session on first need; /defer reset reads it again. */ +async function ensure($: EngineInterface): Promise { + const have = await read($, deferAtom) + if (have) return have + loading ??= load($, null).then(async state => { + await publish($, state) + return state + }) + const state = await loading + // A session that ended and began again while this read ran must not keep its answer. + return (await read($, deferAtom)) ?? state +} + +async function publish($: EngineInterface, state: DeferState) { + await update($, deferAtom, () => state) + await setStatusPart($, 'defer', statusText(state)) +} + +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() + let state = await ensure($) + if (word === 'on' || word === 'off') { + if (word === 'on' && !state.stateDir) { + 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' } + await publish($, state) + return { text: `Defer ${word} for this session.\n${describe(state)}` } + } + if (word === 'reset') { + state = await load($, null) + 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() + 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 } + 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(', ')}` } + } + state = { ...state, target: name } + 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. + loading = null + await update($, deferAtom, () => null) +} export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} @@ -30,7 +240,12 @@ 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)) return null + const state = await ensure($) + if (!state.projectDir) return null + const command = rewriteDeferCommand(e.command, effective(state)) + return command === e.command ? null : command } /** `{ deny }` refuses the Bash call; null lets it run. */ diff --git a/plugins/altimate-code/types/index.d.ts b/plugins/altimate-code/types/index.d.ts index 93c272e6..aac18424 100644 --- a/plugins/altimate-code/types/index.d.ts +++ b/plugins/altimate-code/types/index.d.ts @@ -186,7 +186,25 @@ 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 +} // --------------------------------------------------------------------------------------------------- // Raw SQL to model: the SQL being turned into a dbt model. From 542621402624579ef90c4d1deb73a4873a1b3eca Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 17:29:28 +0530 Subject: [PATCH 02/27] fix: defer rewrite only touches commands that run in the project, keeps old dbt's skip list, and survives a new session The rewrite checks where the command runs (cd, pushd, --project-dir, DBT_PROJECT_DIR, Windows paths); deps, clean, debug, init, docs, source and retry get no --defer; a new session clears the status part; a failed read is tried again after a minute; the read in flight is owned by its own session. Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 118 ++++++++++++++++-- .../altimate-code/hooks/features/defer.tsx | 94 +++++++++++--- plugins/altimate-code/types/index.d.ts | 2 + 3 files changed, 190 insertions(+), 24 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 83be0731..63b892b3 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -1,6 +1,6 @@ import { expect, mock, test } from 'claude-code/testing' -import { effective, rewriteDeferCommand, statusText } from './defer' +import { effective, rewriteDeferCommand, runsInProject, statusText } from './defer' const on = { stateDir: '/work/prod-state' } @@ -27,7 +27,52 @@ 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') - expect(rewriteDeferCommand('dbt deps', on)).toBe('dbt deps') +}) + +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 --defer --state /work/prod-state -s x') + expect(rewriteDeferCommand('dbt deps', both)).toBe('dbt deps') + expect(rewriteDeferCommand('dbt source freshness', both)).toBe('dbt source --target qa freshness') + 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) + 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('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 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', () => { @@ -43,7 +88,7 @@ test('the session target is added when it differs from the default and the comma }) 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 } + 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() @@ -54,17 +99,23 @@ test('the override decides, and the status text shows target and defer', () => { 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) { +function start($: any, on: any, answer: Record, fail: { times: number } = { times: 0 }) { const bash: string[] = [] const statuses: (string | undefined)[] = [] - mock.clock(on) + 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: e.path === `${ROOT}/dbt_project.yml` })) - on('process.run', (_: unknown, e: { readonly argv: readonly string[] }) => ({ + 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 } @@ -73,7 +124,7 @@ function start($: any, on: any, answer: Record) { bash.push(e.command) return { result: { ok: true } } }) - return { bash, statuses } + return { bash, statuses, reads, clock } } const DEFER = { enabled: true, favorState: true, mode: 'local', stateDir: '/work/prod-state', defaultTarget: 'dev', targets: ['dev', 'prod'] } @@ -110,3 +161,54 @@ test('with defer off in the project nothing is rewritten and /defer on says why 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') +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 04035df2..996ee7c9 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -17,8 +17,10 @@ import type { BandUi, FeatureContext } from './index' const deferAtom = atom({ plugin: 'altimate-code', key: 'defer' } as const, null as DeferState | null) -/** dbt commands that read no project graph: they get neither the defer flags nor a target. */ -const NO_FLAGS = new Set(['deps', 'clean', 'debug', 'init', 'retry', 'docs', 'source']) +// Commands that do not defer (dbt before 1.8 refuses the option on some of them, and `retry` reads the +// previous run's results from `--state`, which would point at the wrong ones) and commands that take no target. +const NO_DEFER = new Set(['deps', 'clean', 'debug', 'init', 'retry', 'docs', 'source']) +const NO_TARGET = new Set(['deps', 'clean', 'init', 'retry']) const quote = (text: string) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`) @@ -42,10 +44,10 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s let out = command // From the last invocation to the first, so the offsets of those before stay right. for (const one of parseDbtCommand(command).reverse()) { - if (!one.subcommand || NO_FLAGS.has(one.subcommand)) continue + if (!one.subcommand) continue const flags: string[] = [] - if (stateDir && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) - if (target && target !== defaultTarget && one.target === null) flags.push('--target', quote(target)) + if (stateDir && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) + if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` } @@ -53,6 +55,7 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s } type DeferAnswer = { + success?: boolean enabled?: boolean favorState?: boolean mode?: 'local' | 'remote' | 'none' @@ -82,6 +85,54 @@ async function findProject($: EngineInterface): Promise { return below.length === 1 ? below[0]! : 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)\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/gm +const PROJECT_DIR = /(?:--project-dir[ =]|\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. + */ +export function runsInProject(command: string, root: string, projectDir: string): boolean { + if (/\s--(?:directory|project)[\s=]/.test(command)) return false + const first = parseDbtCommand(command)[0] + const project = resolvePath(projectDir, '.') + if (!first || !project) return false + const inside = (dir: string | null) => !!dir && (dir === project || dir.startsWith(`${project.replace(/\/+$/, '')}/`)) + let dir = resolvePath(root, '.') + let before = dir + for (const match of command.matchAll(CD)) { + if (!dir) return false + const word = match[1]!.replace(UNQUOTE, '') + // `cd -P dir`, `cd -`: not a folder this can work out. + dir = word.startsWith('-') ? 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. + const named = [...command.matchAll(PROJECT_DIR)] + if (named.length === 0) return inside(before) + if (!before) return false + return named.every(match => inside(resolvePath(before!, match[1]!.replace(UNQUOTE, '')))) +} + /** 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 {} @@ -118,11 +169,12 @@ async function load($: EngineInterface, previous: DeferState | null): Promise null) - const data = answer?.ok ? (answer.metadata as DeferAnswer | null) : null - if (!data) return { ...state, reason: answer?.text ?? 'altimate-code did not answer' } + 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', @@ -135,20 +187,26 @@ async function load($: EngineInterface, previous: DeferState | null): 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 once per session on first need; /defer reset reads it again. */ +/** 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) return have - loading ??= load($, null).then(async state => { - await publish($, state) + 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 - }) - const state = await loading - // A session that ended and began again while this read ran must not keep its answer. - return (await read($, deferAtom)) ?? state + })) + const state = await started + // Another session's read must not be dropped by a caller that was waiting on this one. + if (loading === started) loading = null + return mine === generation ? state : await ensure($) } async function publish($: EngineInterface, state: DeferState) { @@ -222,8 +280,10 @@ 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) + await setStatusPart($, 'defer', null) } export async function turnStart($: EngineInterface, e: Args<'turn.start'>) {} @@ -244,6 +304,8 @@ export async function bashRewrite($: EngineInterface, e: BashCall): Promise null) + if (!root || !runsInProject(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 aac18424..4bcd7bd4 100644 --- a/plugins/altimate-code/types/index.d.ts +++ b/plugins/altimate-code/types/index.d.ts @@ -204,6 +204,8 @@ export interface DeferState { 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 } // --------------------------------------------------------------------------------------------------- From ce3f002e30bc3f4d57e56bc776c519df1bc0b233 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Fri, 13 Nov 2026 21:54:17 +0530 Subject: [PATCH 03/27] fix: defer rewrite judges the project per invocation, skips folder changes and exports it cannot follow, and keeps /defer reset from overwriting a newer session Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 34 +++++++++++++++++ .../altimate-code/hooks/features/defer.tsx | 37 +++++++++++++++---- 2 files changed, 63 insertions(+), 8 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 63b892b3..582de5cb 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -68,6 +68,40 @@ test('a command for another project, by cd or --project-dir, is not rewritten', 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') + expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls --defer --state /work/prod-state <(dbt ls --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) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 127908ee..1ee4eb7d 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -42,12 +42,16 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s const { stateDir, favorState = false, target, defaultTarget } = 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=/.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).reverse()) { + for (const one of [...parseDbtCommand(command)].sort((a, b) => b.subcommandEnd - a.subcommandEnd)) { if (!one.subcommand) continue const flags: string[] = [] - if (stateDir && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) - if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) + if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) + if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` } @@ -86,13 +90,13 @@ async function findProject($: EngineInterface): Promise { } // 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)\s+("[^"]+"|'[^']+'|[^\s;&|)]+)/gm +const CD = /(?:^|[;&|(\n{!]\s*|\b(?:if|elif|while|until|then|do|else|time)\s+)(?:cd|pushd)[ \t]+("[^"]+"|'[^']+'|[^\s;&|)]+)/gm const PROJECT_DIR = /(?:--project-dir[ =]|\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 + 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] ?? '' @@ -112,7 +116,15 @@ function resolvePath(base: string, target: string): string | null { */ export function runsInProject(command: string, root: string, projectDir: string): boolean { if (/\s--(?:directory|project)[\s=]/.test(command)) return false - const first = parseDbtCommand(command)[0] + // 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;&|(){}!])(?:popd|chdir)(?=[\s;&|)]|$)|\benv\s+(?:\S+\s+)*(?:-C|--chdir)\b/.test(plain)) return false + const cdWords = plain.match(/(?:^|[\s;&|(){}!])(?:cd|pushd)(?=[\s;&|)]|$)/g)?.length ?? 0 + if (cdWords !== [...command.matchAll(CD)].length) 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 inside = (dir: string | null) => !!dir && (dir === project || dir.startsWith(`${project.replace(/\/+$/, '')}/`)) @@ -120,6 +132,8 @@ export function runsInProject(command: string, root: string, projectDir: string) let before = dir for (const match of command.matchAll(CD)) { if (!dir) 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 = word.startsWith('-') ? null : resolvePath(dir, word) @@ -128,8 +142,12 @@ export function runsInProject(command: string, root: string, projectDir: string) } // A project named outright is the one to judge; otherwise the folder the command runs from. const named = [...command.matchAll(PROJECT_DIR)] + // A project option written with quotes (`"--project-dir" ../b`) is only seen in the plain copy: unknown. + if (named.length !== (plain.match(/--project-dir[ =]|\bDBT_PROJECT_DIR=/g)?.length ?? 0)) return false if (named.length === 0) return inside(before) - if (!before) return false + // 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 return named.every(match => inside(resolvePath(before!, match[1]!.replace(UNQUOTE, '')))) } @@ -244,8 +262,10 @@ export function register(on: On, context: FeatureContext) { return { text: `Defer ${word} for this session.\n${describe(state)}` } } if (word === 'reset') { + const mine = generation state = await load($, null) - await publish($, state) + // A session that started while this read ran has its own state. + if (mine === generation) await publish($, state) return { text: `Defer and target back to the project's settings.\n${describe(state)}` } } if (word === '' || word === 'status') { @@ -269,6 +289,7 @@ export function register(on: On, context: FeatureContext) { 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 } await publish($, state) return { text: `dbt commands now run with --target ${name} (this session).` } From a74e10cf5121552f2b8c5c870f8e661661ad8520 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sat, 14 Nov 2026 07:57:24 +0530 Subject: [PATCH 04/27] fix(defer): skip the rewrite for a cd in a subshell, a project below this one, and DBT_DEFER settings of the user Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 3 +++ plugins/altimate-code/hooks/features/defer.tsx | 9 ++++++--- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 582de5cb..0b20888d 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -64,6 +64,9 @@ test('a command for another project, by cd or --project-dir, is not rewritten', // 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) }) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 1ee4eb7d..22c5eaad 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -44,13 +44,13 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s 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=/.test(command) + const exportedState = /\bexport\b/.test(command) && /\bDBT_(?:STATE|DEFER|DEFER_STATE|FAVOR_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 const flags: string[] = [] - if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) + if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` @@ -122,6 +122,8 @@ export function runsInProject(command: string, root: string, projectDir: string) if (/(?:^|[\s;&|(){}!])(?:popd|chdir)(?=[\s;&|)]|$)|\benv\s+(?:\S+\s+)*(?:-C|--chdir)\b/.test(plain)) return false const cdWords = plain.match(/(?:^|[\s;&|(){}!])(?:cd|pushd)(?=[\s;&|)]|$)/g)?.length ?? 0 if (cdWords !== [...command.matchAll(CD)].length) 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] @@ -148,7 +150,8 @@ export function runsInProject(command: string, root: string, projectDir: string) // 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 - return named.every(match => inside(resolvePath(before!, match[1]!.replace(UNQUOTE, '')))) + // 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. */ From 970e6485c6fc42ceddc9ff914690b851e43244bb Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Sun, 15 Nov 2026 22:19:15 +0530 Subject: [PATCH 05/27] fix(defer): a rejected read is not kept, quoted --directory is not followed, only real dbt invocations read the setting, /defer and /target skip a restarted session, stale status refresh is dropped Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 14 +++++++++++++ .../altimate-code/hooks/features/defer.tsx | 21 ++++++++++++------- plugins/altimate-code/hooks/integrations.tsx | 1 + 3 files changed, 29 insertions(+), 7 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 0b20888d..9243b929 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -13,6 +13,11 @@ test('each dbt invocation in cd a && dbt run is rewritten, the rest of the line 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') }) @@ -249,3 +254,12 @@ test('a new session clears the status line and the overrides of the one before', 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"']) +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 22c5eaad..a26fd513 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -115,10 +115,10 @@ function resolvePath(base: string, target: string): string | null { * folder (`cd`, `pushd`, `--project-dir`, `DBT_PROJECT_DIR`, uv's `--directory`) or one it cannot work out. */ export function runsInProject(command: string, root: string, projectDir: string): boolean { - if (/\s--(?:directory|project)[\s=]/.test(command)) return false // 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=]/.test(command) || /\s--(?:directory|project)[\s=]/.test(plain)) return false if (/(?:^|[\s;&|(){}!])(?:popd|chdir)(?=[\s;&|)]|$)|\benv\s+(?:\S+\s+)*(?:-C|--chdir)\b/.test(plain)) return false const cdWords = plain.match(/(?:^|[\s;&|(){}!])(?:cd|pushd)(?=[\s;&|)]|$)/g)?.length ?? 0 if (cdWords !== [...command.matchAll(CD)].length) return false @@ -224,9 +224,13 @@ async function ensure($: EngineInterface): Promise { if (mine === generation) await publish($, state) return state })) - const state = await started - // Another session's read must not be dropped by a caller that was waiting on this one. - if (loading === started) loading = null + 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($) } @@ -254,6 +258,7 @@ function describe(state: DeferState | null): string { 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) { @@ -261,7 +266,8 @@ export function register(on: On, context: FeatureContext) { return { text: `Defer cannot be turned on: ${state.reason ?? 'no state directory is configured for this project (dbt.deferConfigPerProject).'}` } } state = { ...state, override: word === 'on' } - await publish($, state) + // 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') { @@ -279,6 +285,7 @@ export function register(on: On, context: FeatureContext) { 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(', ')}` : ''}` } @@ -294,7 +301,7 @@ export function register(on: On, context: FeatureContext) { } if (!state.projectDir) return { text: 'No dbt project found in this folder, so there is no target to set.' } state = { ...state, target: name } - await publish($, state) + if (started === generation) await publish($, state) return { text: `dbt commands now run with --target ${name} (this session).` } }) } @@ -326,7 +333,7 @@ export async function bandLine($: EngineInterface, ui: BandUi): Promise { // Most commands name no dbt: they never cost the settings read. - if (!/\bdbt\b/.test(e.command)) return null + if (!/\bdbt\b/.test(e.command) || parseDbtCommand(e.command).length === 0) return null const state = await ensure($) if (!state.projectDir) return null const root = await $.session.root().catch(() => null) diff --git a/plugins/altimate-code/hooks/integrations.tsx b/plugins/altimate-code/hooks/integrations.tsx index 8f14ff1e..36b71bec 100644 --- a/plugins/altimate-code/hooks/integrations.tsx +++ b/plugins/altimate-code/hooks/integrations.tsx @@ -105,6 +105,7 @@ async function refresh($: EngineInterface, subcommand: 'status' | 'detect' = 'st const next = parseStatus(result.stdout) if (next) { await update($, status, () => next) + if (mine !== latestRefresh) return await showStatusLine($, next) } else { const failure = parseJson<{ message?: string }>(result.stdout)?.message ?? firstLine(result.stderr.replace(ANSI, '')) From f4ebfb1f05e3e1fd3599cb5aba2d942ba1936d35 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 06:20:58 +0530 Subject: [PATCH 06/27] refactor(defer): test only the plain form for a directory flag Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.tsx | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index a26fd513..3376fc70 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -118,7 +118,7 @@ export function runsInProject(command: string, root: string, projectDir: string) // 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=]/.test(command) || /\s--(?:directory|project)[\s=]/.test(plain)) return false + if (/\s--(?:directory|project)[\s=]/.test(plain)) return false if (/(?:^|[\s;&|(){}!])(?:popd|chdir)(?=[\s;&|)]|$)|\benv\s+(?:\S+\s+)*(?:-C|--chdir)\b/.test(plain)) return false const cdWords = plain.match(/(?:^|[\s;&|(){}!])(?:cd|pushd)(?=[\s;&|)]|$)/g)?.length ?? 0 if (cdWords !== [...command.matchAll(CD)].length) return false From bb6f094d05ef3afc7429a4e28c469a0847905159 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:43:40 +0530 Subject: [PATCH 07/27] test(features): give the all-stubs phase test the state surface the defer feature reads Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/index.test.ts | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/plugins/altimate-code/hooks/features/index.test.ts b/plugins/altimate-code/hooks/features/index.test.ts index 7c1e206d..53ee5cdb 100644 --- a/plugins/altimate-code/hooks/features/index.test.ts +++ b/plugins/altimate-code/hooks/features/index.test.ts @@ -16,7 +16,19 @@ import { const engine = () => { const logs: string[] = [] - return { logs, $: { ui: { log: (text: string) => void logs.push(text) } } as any } + // The state and command surface is the defer feature's, which is real: its settings are not read for a stub run. + const kept = new Map() + const state = { get: async (key: string) => ({ value: kept.get(key), version: 0 }), set: async (key: string, value: unknown) => (kept.set(key, value), { isSet: true, version: 1 }) } + return { + logs, + $: { + ui: { log: (text: string) => void logs.push(text), status: () => {} }, + command: { register: async () => {} }, + state, + session: { root: async () => null }, + clock: { now: async () => 0 }, + } as any, + } } test('attempt logs a feature function that throws at once, one that rejects, and passes a value on', async () => { From d8085a43167623059fda70b8f3dd056658d5e715 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:46:05 +0530 Subject: [PATCH 08/27] fix(task-impact): pass the file flag to projectRoot, import altimate-cli once Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/task-impact.tsx | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/plugins/altimate-code/hooks/task-impact.tsx b/plugins/altimate-code/hooks/task-impact.tsx index 6f5a8aee..dd48ca29 100644 --- a/plugins/altimate-code/hooks/task-impact.tsx +++ b/plugins/altimate-code/hooks/task-impact.tsx @@ -5,7 +5,7 @@ import { atom, read, update } from 'claude-code' import type { EngineInterface, On, RenderElement } from 'claude-code' import type { PlanImpactView, TaskSummaryView } from '../types' -import { later, runAltimate } from './altimate-cli' +import { later, runAltimate, runTool, within } from './altimate-cli' import { answerOf, changedColumns, @@ -25,7 +25,6 @@ import { WINDOWS_EXPLORER, } from './impact-report' import { projectLayout } from './lineage-graph' -import { runTool, within } from './altimate-cli' import { modelsNamed, openPane, projectRoot } from './lineage' export const REPORT_COMMAND = 'lineage-report' @@ -636,7 +635,7 @@ export async function taskBeforeTool($: EngineInterface, e: any) { if (!file || !/\.sql$/i.test(file)) return const t = (task ??= newTask()) if (t.originals.has(file)) return - const root = await projectRoot($, file, { cliOnly: true }).catch(() => null) + const root = await projectRoot($, file, true).catch(() => null) if (!root) return // A project first touched mid-task has its manifest copied now, before the edit. await within($, 20_000, prepareRoot($, t, root)) From 675d9210cf91ba18e5c1713b425ad4b41b0571bb Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:54:22 +0530 Subject: [PATCH 09/27] fix(defer): leave unreadable invocations and partial project words alone Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 15 ++++++++++++++- plugins/altimate-code/hooks/features/defer.tsx | 5 ++++- 2 files changed, 18 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 9243b929..d3c99afc 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -107,7 +107,8 @@ test('DBT_STATE or DBT_TARGET exported earlier in the line is left alone, and an 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') - expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls --defer --state /work/prod-state <(dbt ls --defer --state /work/prod-state)') + // The outer one holds a redirection word the parser cannot read, so it is left as written; the inner one keeps its place. + expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls <(dbt ls --defer --state /work/prod-state)') }) test('a Windows session folder, with either slash, is the project it names', () => { @@ -263,3 +264,15 @@ test('a command that only mentions dbt does not read the setting', async ($, on) 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', () => { + const both = { ...on, target: 'qa', defaultTarget: 'dev' } + expect(rewriteDeferCommand('dbt --target "$T" run', both)).toBe('dbt --target "$T" run') + expect(rewriteDeferCommand('dbt run $FLAGS', both)).toBe('dbt run $FLAGS') +}) + +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) +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 3376fc70..3bf0a24b 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -48,7 +48,8 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s 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 + // An invocation with a word the parser cannot read (`$FLAGS`, `--target "$T"`) is left as the user wrote it. + if (!one.subcommand || one.dynamic) continue const flags: string[] = [] if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) @@ -146,6 +147,8 @@ export function runsInProject(command: string, root: string, projectDir: string) const named = [...command.matchAll(PROJECT_DIR)] // A project option written with quotes (`"--project-dir" ../b`) is only seen in the plain copy: unknown. if (named.length !== (plain.match(/--project-dir[ =]|\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. + 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 From b95c776ed00e5663f3c1000577b5b448d8f2eed9 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 07:58:31 +0530 Subject: [PATCH 10/27] fix(defer): skip only invocations whose flags may come from an expansion Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 10 +++++++--- plugins/altimate-code/hooks/features/defer.tsx | 10 +++++++--- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index d3c99afc..0f3adaa2 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -107,8 +107,7 @@ test('DBT_STATE or DBT_TARGET exported earlier in the line is left alone, and an 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 redirection word the parser cannot read, so it is left as written; the inner one keeps its place. - expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls <(dbt ls --defer --state /work/prod-state)') + expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls --defer --state /work/prod-state <(dbt ls --defer --state /work/prod-state)') }) test('a Windows session folder, with either slash, is the project it names', () => { @@ -265,10 +264,15 @@ test('a command that only mentions dbt does not read the setting', async ($, on) 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', () => { +test('an invocation whose flags may come from an expansion is left as it is', () => { const both = { ...on, target: 'qa', defaultTarget: 'dev' } expect(rewriteDeferCommand('dbt --target "$T" run', both)).toBe('dbt --target "$T" run') expect(rewriteDeferCommand('dbt run $FLAGS', both)).toBe('dbt run $FLAGS') + expect(rewriteDeferCommand('dbt run -t $T', both)).toBe('dbt run -t $T') + // An unreadable word that cannot carry a flag does not stop the rewrite. + expect(rewriteDeferCommand('dbt run --profiles-dir ~/.dbt', on)).toBe('dbt run --defer --state /work/prod-state --profiles-dir ~/.dbt') + expect(rewriteDeferCommand('dbt build -s "$MODEL"', on)).toBe('dbt build --defer --state /work/prod-state -s "$MODEL"') + expect(rewriteDeferCommand('dbt run -s staging.*', on)).toBe('dbt run --defer --state /work/prod-state -s staging.*') }) test('a project word that goes on after its quotes is not one the settings are judged for', () => { diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 3bf0a24b..8e85a3cd 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -36,7 +36,7 @@ export type RewriteOptions = { /** * 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. + * when nothing needs to change. An invocation whose flags may come from an expansion is left as written. */ export function rewriteDeferCommand(command: string, options: RewriteOptions): string { const { stateDir, favorState = false, target, defaultTarget } = options @@ -48,8 +48,12 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s 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)) { - // An invocation with a word the parser cannot read (`$FLAGS`, `--target "$T"`) is left as the user wrote it. - if (!one.subcommand || one.dynamic) continue + if (!one.subcommand) continue + // A word that is itself an expansion (`$FLAGS`) may carry --state, --defer or --target, and a --target whose value + // is an expansion names a target this cannot read: such an invocation is left as the user wrote it. + // Other unreadable words (`~`, a glob, `-s "$MODEL"`) cannot change what the flags mean. + const text = command.slice(one.start, one.end) + if (one.dynamic && (/(?:^|\s)\$[{(\w@*]/.test(text) || /(?:--target[ =]|\s-t\s*|\bDBT_TARGET=)\S*[$`]/.test(text))) continue const flags: string[] = [] if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) From 41bd5427b4b8019eb97290faace099db2587397d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 08:01:36 +0530 Subject: [PATCH 11/27] fix(defer): leave every invocation the parser cannot read as written Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 15 ++++++--------- plugins/altimate-code/hooks/features/defer.tsx | 10 ++++------ 2 files changed, 10 insertions(+), 15 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 0f3adaa2..7dd3ccb8 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -107,7 +107,8 @@ test('DBT_STATE or DBT_TARGET exported earlier in the line is left alone, and an 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') - expect(rewriteDeferCommand('dbt ls <(dbt ls)', on)).toBe('dbt ls --defer --state /work/prod-state <(dbt ls --defer --state /work/prod-state)') + // 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 ls <(dbt ls)', on)).toBe('dbt ls <(dbt ls --defer --state /work/prod-state)') }) test('a Windows session folder, with either slash, is the project it names', () => { @@ -264,15 +265,11 @@ test('a command that only mentions dbt does not read the setting', async ($, on) expect(seen.bash).toEqual(['cat dbt_project.yml', 'git commit -m "dbt"']) }) -test('an invocation whose flags may come from an expansion is left as it is', () => { +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' } - expect(rewriteDeferCommand('dbt --target "$T" run', both)).toBe('dbt --target "$T" run') - expect(rewriteDeferCommand('dbt run $FLAGS', both)).toBe('dbt run $FLAGS') - expect(rewriteDeferCommand('dbt run -t $T', both)).toBe('dbt run -t $T') - // An unreadable word that cannot carry a flag does not stop the rewrite. - expect(rewriteDeferCommand('dbt run --profiles-dir ~/.dbt', on)).toBe('dbt run --defer --state /work/prod-state --profiles-dir ~/.dbt') - expect(rewriteDeferCommand('dbt build -s "$MODEL"', on)).toBe('dbt build --defer --state /work/prod-state -s "$MODEL"') - expect(rewriteDeferCommand('dbt run -s staging.*', on)).toBe('dbt run --defer --state /work/prod-state -s staging.*') + 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', () => { diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 8e85a3cd..92e69ee4 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -36,7 +36,7 @@ export type RewriteOptions = { /** * 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 whose flags may come from an expansion is left as written. + * 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, defaultTarget } = options @@ -49,11 +49,9 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s // 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 - // A word that is itself an expansion (`$FLAGS`) may carry --state, --defer or --target, and a --target whose value - // is an expansion names a target this cannot read: such an invocation is left as the user wrote it. - // Other unreadable words (`~`, a glob, `-s "$MODEL"`) cannot change what the flags mean. - const text = command.slice(one.start, one.end) - if (one.dynamic && (/(?:^|\s)\$[{(\w@*]/.test(text) || /(?:--target[ =]|\s-t\s*|\bDBT_TARGET=)\S*[$`]/.test(text))) 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[] = [] if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) From 9fffbde2f6b7f41ce14ecb048638f119b3663e90 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 11:35:59 +0530 Subject: [PATCH 12/27] fix(defer): leave an escaped --project-dir word alone; reuse the command keyword set Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/dbt-command.ts | 4 ++-- plugins/altimate-code/hooks/features/defer.test.ts | 2 ++ plugins/altimate-code/hooks/features/defer.tsx | 2 ++ 3 files changed, 6 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/dbt-command.ts b/plugins/altimate-code/hooks/dbt-command.ts index 15002323..95c8ed13 100644 --- a/plugins/altimate-code/hooks/dbt-command.ts +++ b/plugins/altimate-code/hooks/dbt-command.ts @@ -462,8 +462,8 @@ export function parseDbtCommand(line: string): DbtInvocation[] { 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']) +// Words after which a command still starts, so a `(` there opens a subshell (the same words as KEYWORDS). +const COMMAND_KEYWORDS = KEYWORDS const NAME = /^[A-Za-z_][A-Za-z0-9_-]*$/ /** diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 7dd3ccb8..d6f3e032 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -57,6 +57,8 @@ test('a command for another project, by cd or --project-dir, is not rewritten', 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) + // 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) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 92e69ee4..6204500d 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -150,6 +150,8 @@ export function runsInProject(command: string, root: string, projectDir: string) // A project option written with quotes (`"--project-dir" ../b`) is only seen in the plain copy: unknown. if (named.length !== (plain.match(/--project-dir[ =]|\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. + if (named.some(match => 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. From 1975de69cf2027358a531c081e6623a7fd5eb2a4 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 11:51:24 +0530 Subject: [PATCH 13/27] fix(defer): judge the project from the shell's current folder, skip nested dbt projects, defer only on commands that take it Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 13 +++-- .../altimate-code/hooks/features/defer.tsx | 48 +++++++++++++++---- 2 files changed, 49 insertions(+), 12 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index d6f3e032..9dce4e89 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -36,9 +36,12 @@ test('defer off or no dbt command: no rewrite', () => { 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 --defer --state /work/prod-state -s x') + expect(rewriteDeferCommand('dbt ls -s x', on)).toBe('dbt ls -s x') + expect(rewriteDeferCommand('dbt seed', on)).toBe('dbt seed') + 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 --target qa freshness') + 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') }) @@ -57,6 +60,10 @@ test('a command for another project, by cd or --project-dir, is not rewritten', 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) @@ -110,7 +117,7 @@ test('DBT_STATE or DBT_TARGET exported earlier in the line is left alone, and an 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 ls <(dbt ls)', on)).toBe('dbt ls <(dbt ls --defer --state /work/prod-state)') + 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', () => { diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 6204500d..4ac00f56 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -17,10 +17,11 @@ import type { BandUi, FeatureContext } from './index' const deferAtom = atom({ plugin: 'altimate-code', key: 'defer' } as const, null as DeferState | null) -// Commands that do not defer (dbt before 1.8 refuses the option on some of them, and `retry` reads the -// previous run's results from `--state`, which would point at the wrong ones) and commands that take no target. -const NO_DEFER = new Set(['deps', 'clean', 'debug', 'init', 'retry', 'docs', 'source']) -const NO_TARGET = new Set(['deps', 'clean', 'init', 'retry']) +// The commands that take `--defer` in every dbt version this reads state for (dbt before 1.8 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']) +// 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']) const quote = (text: string) => (/^[\w@%+=:,./-]+$/.test(text) ? text : `'${text.replace(/'/g, `'\\''`)}'`) @@ -53,7 +54,7 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s // 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[] = [] - if (stateDir && !exportedState && !NO_DEFER.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) + if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` @@ -92,6 +93,25 @@ async function findProject($: EngineInterface): Promise { return below.length === 1 ? below[0]! : null } +/** The folders below the project (down to three levels) that hold a dbt_project.yml of their own. */ +async function nestedProjects($: EngineInterface, projectDir: string): Promise> { + const found = new Set() + let level = [projectDir] + for (let depth = 0; depth < 3 && level.length > 0; depth++) { + const next: string[] = [] + for (const dir of level) { + for (const entry of await $.fs.list(dir).catch(() => [])) { + if (entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dbt_packages' || entry.name === 'target') continue + const child = `${dir}/${entry.name}` + if (await $.fs.exists(`${child}/dbt_project.yml`).catch(() => false)) found.add(child) + else next.push(child) + } + } + level = next + } + return found +} + // 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[ =]|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g @@ -117,7 +137,7 @@ function resolvePath(base: string, target: string): string | null { * 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. */ -export function runsInProject(command: string, root: string, projectDir: string): boolean { +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, '') @@ -132,7 +152,13 @@ export function runsInProject(command: string, root: string, projectDir: string) const first = [...invocations].sort((a, b) => a.start - b.start)[0] const project = resolvePath(projectDir, '.') if (!first || !project) return false - const inside = (dir: string | null) => !!dir && (dir === project || dir.startsWith(`${project.replace(/\/+$/, '')}/`)) + 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}/`); d = dirname(d)) if (isProject(d)) return true + return false + } + const inside = (dir: string | null) => !!dir && (dir === project || (dir.startsWith(`${base}/`) && !ownsProject(dir))) let dir = resolvePath(root, '.') let before = dir for (const match of command.matchAll(CD)) { @@ -343,8 +369,12 @@ export async function bashRewrite($: EngineInterface, e: BashCall): Promise null) - if (!root || !runsInProject(e.command, root, 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 + // Only a command that starts or moves below the project can end up in a dbt project of its own. + const nested = root !== state.projectDir || /\b(?:cd|pushd)\b/.test(e.command) ? await nestedProjects($, state.projectDir) : new Set() + if (!runsInProject(e.command, root, state.projectDir, dir => nested.has(dir))) return null const command = rewriteDeferCommand(e.command, effective(state)) return command === e.command ? null : command } From ef26dcd6eead9fe2b78405916d2bfb22146194d7 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 11:57:38 +0530 Subject: [PATCH 14/27] fix(defer): compare nested projects in the normalized form; look under dbt_packages too Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 18 ++++++++++++++++-- plugins/altimate-code/hooks/features/defer.tsx | 6 +++--- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 9dce4e89..54ac758b 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -151,7 +151,7 @@ test('the override decides, and the status text shows target and defer', () => { 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 }) { +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[] = [] @@ -159,7 +159,7 @@ function start($: any, on: any, answer: Record, fail: { times: 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: e.path === `${ROOT}/dbt_project.yml` })) + 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(' ')) @@ -190,6 +190,20 @@ test('through the plugin, Claude’s dbt commands run with --defer --state when 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' }, { name: 'dbt_packages', kind: 'dir' }] : e.path === `${ROOT}/dbt_packages` ? [{ name: 'pkg', kind: 'dir' }] : [] })) + 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 }) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 4ac00f56..27bbc5f8 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -93,7 +93,7 @@ async function findProject($: EngineInterface): Promise { return below.length === 1 ? below[0]! : null } -/** The folders below the project (down to three levels) that hold a dbt_project.yml of their own. */ +/** The folders below the project (down to three levels, `dbt_packages` included) that hold a dbt_project.yml of their own, in the form `runsInProject` compares. */ async function nestedProjects($: EngineInterface, projectDir: string): Promise> { const found = new Set() let level = [projectDir] @@ -101,9 +101,9 @@ async function nestedProjects($: EngineInterface, projectDir: string): Promise [])) { - if (entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'dbt_packages' || entry.name === 'target') continue + if (entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'target') continue const child = `${dir}/${entry.name}` - if (await $.fs.exists(`${child}/dbt_project.yml`).catch(() => false)) found.add(child) + if (await $.fs.exists(`${child}/dbt_project.yml`).catch(() => false)) found.add(resolvePath(child, '.') ?? child) else next.push(child) } } From 0ff6cae3baa0e9a8377c198728208935e33989ba Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 13:47:05 +0530 Subject: [PATCH 15/27] fix(defer): Windows project paths with backslashes, and scan for nested projects only when the shell can reach one Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 22 ++++++++++++++++++- .../altimate-code/hooks/features/defer.tsx | 13 ++++++++--- 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 54ac758b..f08159a6 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -1,6 +1,6 @@ import { expect, mock, test } from 'claude-code/testing' -import { effective, rewriteDeferCommand, runsInProject, statusText } from './defer' +import { effective, nestedProjects, rewriteDeferCommand, runsInProject, statusText } from './defer' const on = { stateDir: '/work/prod-state' } @@ -300,3 +300,23 @@ test('a project word that goes on after its quotes is not one the settings are j 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) }) + +test('on a Windows project path a nested dbt project is found in the form the command is compared in', async () => { + const dirs: Record = { 'C:\\repo': ['nested', 'models'] } + const $: any = { + fs: { + list: async (dir: string) => (dirs[dir] ?? []).map(name => ({ name, kind: 'dir' })), + exists: async (file: string) => file === 'C:\\repo/nested/dbt_project.yml', + }, + } + const nested = await nestedProjects($, 'C:\\repo') + expect([...nested]).toEqual(['C:/repo/nested']) + expect(runsInProject('cd nested && dbt build', 'C:\\repo', 'C:\\repo', dir => nested.has(dir))).toBe(false) + expect(runsInProject('cd models && dbt build', 'C:\\repo', 'C:\\repo', dir => nested.has(dir))).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) + 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) +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 27bbc5f8..b481ef4b 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -94,7 +94,7 @@ async function findProject($: EngineInterface): Promise { } /** The folders below the project (down to three levels, `dbt_packages` included) that hold a dbt_project.yml of their own, in the form `runsInProject` compares. */ -async function nestedProjects($: EngineInterface, projectDir: string): Promise> { +export async function nestedProjects($: EngineInterface, projectDir: string): Promise> { const found = new Set() let level = [projectDir] for (let depth = 0; depth < 3 && level.length > 0; depth++) { @@ -177,7 +177,9 @@ export function runsInProject(command: string, root: string, projectDir: string, if (named.length !== (plain.match(/--project-dir[ =]|\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. - if (named.some(match => match[1]!.includes('\\'))) return false + // On a Windows project path a backslash separates folders; elsewhere any backslash may be an escape. + const windows = /^[A-Za-z]:/.test(projectDir) + if (named.some(match => (windows ? /\\$/.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. @@ -373,7 +375,12 @@ export async function bashRewrite($: EngineInterface, e: BashCall): Promise null)) ?? (await $.session.root().catch(() => null)) if (!root) return null // Only a command that starts or moves below the project can end up in a dbt project of its own. - const nested = root !== state.projectDir || /\b(?:cd|pushd)\b/.test(e.command) ? await nestedProjects($, state.projectDir) : new Set() + // A shell above or outside the project reaches one only by a `cd`, `pushd` or project option. + const project = resolvePath(state.projectDir, '.')?.replace(/\/+$/, '') + const here = resolvePath(root, '.') + const below = !!project && !!here && (here === project || here.startsWith(`${project}/`)) + const moves = /\b(?:cd|pushd)\b|--project-dir|DBT_PROJECT_DIR/.test(e.command) + const nested = (below && here !== project) || moves ? await nestedProjects($, state.projectDir) : new Set() if (!runsInProject(e.command, root, state.projectDir, dir => nested.has(dir))) return null const command = rewriteDeferCommand(e.command, effective(state)) return command === e.command ? null : command From 1edd331fd4bfe9c41169216e192d805905519e12 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 14:07:08 +0530 Subject: [PATCH 16/27] fix(defer): a symbolic link to another dbt project keeps that project's own settings Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 12 ++++++++++++ plugins/altimate-code/hooks/features/defer.tsx | 3 ++- 2 files changed, 14 insertions(+), 1 deletion(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index f08159a6..b519c6cc 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -320,3 +320,15 @@ test('a Windows --project-dir with backslashes names the project; an escaped spa 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 symbolic link to another dbt project counts as a nested project', async () => { + const $: any = { + fs: { + list: async (dir: string) => (dir === '/repo/a' ? [{ name: 'linked', kind: 'other', isLink: true }, { name: 'notes.txt', kind: 'file', isLink: false }] : []), + exists: async (file: string) => file === '/repo/a/linked/dbt_project.yml', + }, + } + const nested = await nestedProjects($, '/repo/a') + expect([...nested]).toEqual(['/repo/a/linked']) + expect(runsInProject('cd linked && dbt build', '/repo/a', '/repo/a', dir => nested.has(dir))).toBe(false) +}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index b481ef4b..e6a28ca3 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -101,7 +101,8 @@ export async function nestedProjects($: EngineInterface, projectDir: string): Pr const next: string[] = [] for (const dir of level) { for (const entry of await $.fs.list(dir).catch(() => [])) { - if (entry.kind !== 'dir' || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'target') continue + // A link may lead to a dbt project of its own: the engine lists it as another kind than 'dir'. + if ((entry.kind !== 'dir' && !entry.isLink) || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'target') continue const child = `${dir}/${entry.name}` if (await $.fs.exists(`${child}/dbt_project.yml`).catch(() => false)) found.add(resolvePath(child, '.') ?? child) else next.push(child) From 0192b7a092d14a5a6b9c79f5c4cc83722d86a9ad Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 14:17:43 +0530 Subject: [PATCH 17/27] fix(defer): check the folders a command reaches for a dbt project of its own, at any depth Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 40 ++++++++----------- .../altimate-code/hooks/features/defer.tsx | 39 ++++++------------ 2 files changed, 29 insertions(+), 50 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index b519c6cc..920344d7 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -1,6 +1,6 @@ import { expect, mock, test } from 'claude-code/testing' -import { effective, nestedProjects, rewriteDeferCommand, runsInProject, statusText } from './defer' +import { effective, rewriteDeferCommand, runsHere, runsInProject, statusText } from './defer' const on = { stateDir: '/work/prod-state' } @@ -301,18 +301,22 @@ test('a project word that goes on after its quotes is not one the settings are j 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 dirs: Record = { 'C:\\repo': ['nested', 'models'] } - const $: any = { - fs: { - list: async (dir: string) => (dirs[dir] ?? []).map(name => ({ name, kind: 'dir' })), - exists: async (file: string) => file === 'C:\\repo/nested/dbt_project.yml', - }, - } - const nested = await nestedProjects($, 'C:\\repo') - expect([...nested]).toEqual(['C:/repo/nested']) - expect(runsInProject('cd nested && dbt build', 'C:\\repo', 'C:\\repo', dir => nested.has(dir))).toBe(false) - expect(runsInProject('cd models && dbt build', 'C:\\repo', 'C:\\repo', dir => nested.has(dir))).toBe(true) + 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', () => { @@ -320,15 +324,3 @@ test('a Windows --project-dir with backslashes names the project; an escaped spa 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 symbolic link to another dbt project counts as a nested project', async () => { - const $: any = { - fs: { - list: async (dir: string) => (dir === '/repo/a' ? [{ name: 'linked', kind: 'other', isLink: true }, { name: 'notes.txt', kind: 'file', isLink: false }] : []), - exists: async (file: string) => file === '/repo/a/linked/dbt_project.yml', - }, - } - const nested = await nestedProjects($, '/repo/a') - expect([...nested]).toEqual(['/repo/a/linked']) - expect(runsInProject('cd linked && dbt build', '/repo/a', '/repo/a', dir => nested.has(dir))).toBe(false) -}) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index e6a28ca3..7b45000d 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -93,24 +93,18 @@ async function findProject($: EngineInterface): Promise { return below.length === 1 ? below[0]! : null } -/** The folders below the project (down to three levels, `dbt_packages` included) that hold a dbt_project.yml of their own, in the form `runsInProject` compares. */ -export async function nestedProjects($: EngineInterface, projectDir: string): Promise> { - const found = new Set() - let level = [projectDir] - for (let depth = 0; depth < 3 && level.length > 0; depth++) { - const next: string[] = [] - for (const dir of level) { - for (const entry of await $.fs.list(dir).catch(() => [])) { - // A link may lead to a dbt project of its own: the engine lists it as another kind than 'dir'. - if ((entry.kind !== 'dir' && !entry.isLink) || entry.name.startsWith('.') || entry.name === 'node_modules' || entry.name === 'target') continue - const child = `${dir}/${entry.name}` - if (await $.fs.exists(`${child}/dbt_project.yml`).catch(() => false)) found.add(resolvePath(child, '.') ?? child) - else next.push(child) - } - } - level = next - } - return found +/** + * 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 + 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)) } // Where a command runs from: the session folder, moved by each `cd` or `pushd` in the command. @@ -375,14 +369,7 @@ export async function bashRewrite($: EngineInterface, e: BashCall): Promise null)) ?? (await $.session.root().catch(() => null)) if (!root) return null - // Only a command that starts or moves below the project can end up in a dbt project of its own. - // A shell above or outside the project reaches one only by a `cd`, `pushd` or project option. - const project = resolvePath(state.projectDir, '.')?.replace(/\/+$/, '') - const here = resolvePath(root, '.') - const below = !!project && !!here && (here === project || here.startsWith(`${project}/`)) - const moves = /\b(?:cd|pushd)\b|--project-dir|DBT_PROJECT_DIR/.test(e.command) - const nested = (below && here !== project) || moves ? await nestedProjects($, state.projectDir) : new Set() - if (!runsInProject(e.command, root, state.projectDir, dir => nested.has(dir))) 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 } From 4464607afbf5a0b3b763b11fef6228f45b943f2d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 14:28:57 +0530 Subject: [PATCH 18/27] fix(defer): dbt snapshot takes --defer --state like build and run Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 1 + plugins/altimate-code/hooks/features/defer.tsx | 4 ++-- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 920344d7..9027d332 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -38,6 +38,7 @@ test('commands that do not defer are left without --defer, and the target goes t 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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 7b45000d..bf6a7108 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -17,9 +17,9 @@ 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 (dbt before 1.8 refuses the option on +// 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']) +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']) From 2eb09ef073afdfbf4e20e5c133955bcb703f6609 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 16:19:29 +0530 Subject: [PATCH 19/27] fix: unrelated assignment expansions keep defer, launcher short clusters are read, an unquoted backslash is no separator Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/dbt-command.test.ts | 6 ++++++ plugins/altimate-code/hooks/dbt-command.ts | 11 ++++++----- plugins/altimate-code/hooks/features/defer.test.ts | 4 +++- plugins/altimate-code/hooks/features/defer.tsx | 4 +++- 4 files changed, 18 insertions(+), 7 deletions(-) diff --git a/plugins/altimate-code/hooks/dbt-command.test.ts b/plugins/altimate-code/hooks/dbt-command.test.ts index 97e54639..e32f44dc 100644 --- a/plugins/altimate-code/hooks/dbt-command.test.ts +++ b/plugins/altimate-code/hooks/dbt-command.test.ts @@ -267,6 +267,12 @@ test('an expansion is part of its word, and the invocation is dynamic; its value 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' }]) + // An expansion in an unrelated assignment cannot add a flag to dbt. + expect(shape('START=$SECONDS time dbt run')).toEqual([run]) + expect(shape('LOG_DIR=$LOG nohup dbt run')).toEqual([run]) + // A combined short cluster of the launcher's flags is read. + expect(shape('uv run -qq dbt run')).toEqual([{ ...run, binary: 'uv run -qq dbt' }]) + expect(shape('uv run -qv dbt run')).toEqual([{ ...run, binary: 'uv run -qv dbt' }]) // 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'] }]) diff --git a/plugins/altimate-code/hooks/dbt-command.ts b/plugins/altimate-code/hooks/dbt-command.ts index ef463d2e..fcab0c71 100644 --- a/plugins/altimate-code/hooks/dbt-command.ts +++ b/plugins/altimate-code/hooks/dbt-command.ts @@ -638,7 +638,7 @@ function readSimple(tokens: Token[]): DbtInvocation | null { 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. + // Whether a target 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. @@ -657,7 +657,8 @@ function readSimple(tokens: Token[]): DbtInvocation | null { 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 + // Only the target variables decide a `--target` insertion; another expansion cannot add a flag to dbt. + if (word.dynamic && (name === 'DBT_TARGET' || name === 'DBT_TARGET_PATH')) assignmentDynamic = true firstAssignment ??= i optionsOpen = false continue @@ -716,10 +717,10 @@ function readSimple(tokens: Token[]): DbtInvocation | null { 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) + // A combined short cluster (`-qv`) is read when each letter is a flag of the launcher. + const cluster = /^-[a-zA-Z]{2,}$/.test(flag) && [...flag.slice(1)].every(c => options.flags.has(`-${c}`)) 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 if (!flag.includes('=') && (options.flags.has(flag) || cluster)) i++ else return null } if (i >= words.length || !isDbt(words[i]!.text)) return null diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 9027d332..f6b23ad5 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -321,7 +321,9 @@ test('on a Windows project path a nested dbt project is found in the form the co }) 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) + 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) }) diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index bf6a7108..0038897f 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -102,6 +102,7 @@ export async function runsHere($: EngineInterface, command: string, root: string 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)) @@ -174,7 +175,8 @@ export function runsInProject(command: string, root: string, projectDir: string, // 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. const windows = /^[A-Za-z]:/.test(projectDir) - if (named.some(match => (windows ? /\\$/.test(match[1]!) : match[1]!.includes('\\')))) return false + // 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. From 12f12169962d6d507601c459ed4081424c8e0f6c Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 21:27:33 +0530 Subject: [PATCH 20/27] fix: an explicit session target always applies; a command's own favor-state, a tab after --project-dir, an escaped cd word and a cd that may not run are handled Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 22 +++++++++++++++++-- .../altimate-code/hooks/features/defer.tsx | 20 +++++++++++------ 2 files changed, 33 insertions(+), 9 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index f6b23ad5..f0a998f7 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -132,14 +132,32 @@ 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 it differs from the default and the command names none', () => { +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') + 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('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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index a5c2308c..936fc1a6 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -29,7 +29,7 @@ export type RewriteOptions = { /** The directory to defer to; null or undefined means defer is off. */ stateDir?: string | null favorState?: boolean - /** The session's target; added to a command without one when it differs from the profile's default. */ + /** 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 } @@ -40,7 +40,7 @@ export type RewriteOptions = { * 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, defaultTarget } = options + 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 @@ -54,8 +54,8 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s // 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[] = [] - if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState ? ['--favor-state'] : [])) - if (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) + if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState && !/--(?:no-)?favor-state\b/.test(command.slice(one.start, one.end)) ? ['--favor-state'] : [])) + if (target && !NO_TARGET.has(one.subcommand) && one.target === null && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` } @@ -111,7 +111,7 @@ export async function runsHere($: EngineInterface, command: string, root: string // 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[ =]|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g +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. */ @@ -156,10 +156,17 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 `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 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, '') @@ -171,11 +178,10 @@ export function runsInProject(command: string, root: string, projectDir: string, // A project named outright is the one to judge; otherwise the folder the command runs from. const named = [...command.matchAll(PROJECT_DIR)] // A project option written with quotes (`"--project-dir" ../b`) is only seen in the plain copy: unknown. - if (named.length !== (plain.match(/--project-dir[ =]|\bDBT_PROJECT_DIR=/g)?.length ?? 0)) return false + 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. - const windows = /^[A-Za-z]:/.test(projectDir) // 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 From 61ee9b45aebd3444f45f5e8c4bd716ab1b9b592d Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 21:49:29 +0530 Subject: [PATCH 21/27] fix: control flow, a pipeline, a background job or a glob around a cd leaves the folder unknown; DBT_FAVOR_STATE no longer stops the deferral Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 17 +++++++++++++++++ plugins/altimate-code/hooks/features/defer.tsx | 15 +++++++++++++-- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index f0a998f7..d4b73daf 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -158,6 +158,23 @@ test('a tab after --project-dir, an escaped folder word and a cd that may not ru 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('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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 936fc1a6..7f1b52d8 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -45,7 +45,7 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s 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|FAVOR_STATE)=/.test(command) + 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)) { @@ -54,7 +54,11 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s // 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[] = [] - if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE|FAVOR_STATE)=/.test(command.slice(one.start, one.end))) flags.push('--defer', '--state', quote(stateDir), ...(favorState && !/--(?:no-)?favor-state\b/.test(command.slice(one.start, one.end)) ? ['--favor-state'] : [])) + if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE)=/.test(command.slice(one.start, one.end))) { + // The command's own favor-state choice, in a flag or the environment, stands. + const own = /--(?:no-)?favor-state\b|\bDBT_FAVOR_STATE=/.test(command.slice(one.start, one.end)) || (/\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(command.slice(one.start, one.end))) flags.push('--target', quote(target)) if (flags.length === 0) continue out = `${out.slice(0, one.subcommandEnd)} ${flags.join(' ')}${out.slice(one.subcommandEnd)}` @@ -140,8 +144,11 @@ export function runsInProject(command: string, root: string, projectDir: string, const plain = command.replace(/["'\\]/g, '') if (/\s--(?:directory|project)[\s=]/.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. + 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 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) @@ -163,10 +170,14 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 runs in a subshell and leaves this folder as it was. + if (/^\s*(?:\|(?!\|)|&(?!&))/.test(command.slice(match.index + match[0].length))) 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, '') From 985b610a0a9de0d5459c1421b3440e5e3eca7b90 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 22:14:06 +0530 Subject: [PATCH 22/27] fix: a cd in a redirected pipeline, in quotes or behind a short directory option leaves the folder unknown; a stale /target reset does not publish Co-Authored-By: Claude Sonnet 5.5 --- .../hooks/features/defer.test.ts | 9 +++++++ .../altimate-code/hooks/features/defer.tsx | 25 ++++++++++++++++--- 2 files changed, 30 insertions(+), 4 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index d4b73daf..0762454b 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -175,6 +175,15 @@ test('a cd that control flow, a pipeline, a background job or a glob may skip or 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 2>&1 && dbt run | tee out')).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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 7f1b52d8..be2377dc 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -113,6 +113,19 @@ export async function runsHere($: EngineInterface, command: string, root: string 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 @@ -142,7 +155,7 @@ export function runsInProject(command: string, root: string, projectDir: string, // 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=]/.test(plain)) return false + 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. const control = /(?:^|[\s;&|(){}!])(?:if|then|else|elif|fi|while|until|do|done|for|case|esac|select)(?=[\s;&|)]|$)/.test(plain) @@ -176,8 +189,11 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 runs in a subshell and leaves this folder as it was. - if (/^\s*(?:\|(?!\|)|&(?!&))/.test(command.slice(match.index + match[0].length))) 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, '') @@ -342,7 +358,8 @@ export function register(on: On, context: FeatureContext) { } if (name === 'reset') { state = { ...state, target: null } - await publish($, state) + // 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}` } From bd87e34159880a6b9e788224f3ded044eb0adcba Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 22:25:53 +0530 Subject: [PATCH 23/27] fix: a folder change is trusted only as a leading && chain; option text in quotes is no option; a stale /defer reset does not publish Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 11 ++++++++++- plugins/altimate-code/hooks/features/defer.tsx | 15 ++++++++++----- 2 files changed, 20 insertions(+), 6 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 0762454b..8dd19b60 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -181,7 +181,16 @@ test('a cd with a redirection before a pipe or &, a cd inside quotes and a short 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 2>&1 && dbt run | tee out')).toBe(true) + 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('the override decides, and the status text shows target and defer', () => { diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index be2377dc..5f0497aa 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -162,6 +162,12 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 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 + } // 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) @@ -203,7 +209,7 @@ export function runsInProject(command: string, root: string, projectDir: string, else if (!inside(dir)) return false } // A project named outright is the one to judge; otherwise the folder the command runs from. - const named = [...command.matchAll(PROJECT_DIR)] + const named = [...command.matchAll(PROJECT_DIR)].filter(match => !quoted(command, 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. @@ -328,7 +334,7 @@ export function register(on: On, context: FeatureContext) { let state = await ensure($) if (word === 'on' || word === 'off') { if (word === 'on' && !state.stateDir) { - await publish($, state) + 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' } @@ -337,10 +343,9 @@ export function register(on: On, context: FeatureContext) { return { text: `Defer ${word} for this session.\n${describe(state)}` } } if (word === 'reset') { - const mine = generation state = await load($, null) - // A session that started while this read ran has its own state. - if (mine === generation) await publish($, state) + // 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') { From ab07f32e8bf75884f78be7326c75dc64bfbbe6dd Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 22:34:50 +0530 Subject: [PATCH 24/27] fix: a background cd chain, a pushd stack word, an option value shaped like --project-dir and a project at the root Co-Authored-By: Claude Sonnet 5.5 --- .../altimate-code/hooks/features/defer.test.ts | 9 +++++++++ plugins/altimate-code/hooks/features/defer.tsx | 16 +++++++++++++--- 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 8dd19b60..2daba60e 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -193,6 +193,15 @@ test('a cd is trusted only as the leading `cd a && cd b &&` chain, and option te 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('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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 5f0497aa..455136fa 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -150,6 +150,8 @@ function resolvePath(base: string, target: string): string | null { /** * 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. @@ -162,6 +164,8 @@ export function runsInProject(command: string, root: string, projectDir: string, 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) { @@ -178,7 +182,12 @@ export function runsInProject(command: string, root: string, projectDir: string, 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}/`); d = dirname(d)) if (isProject(d)) return true + 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))) @@ -204,12 +213,13 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 = word.startsWith('-') ? null : resolvePath(dir, word) + 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. - const named = [...command.matchAll(PROJECT_DIR)].filter(match => !quoted(command, match.index)) + // 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]!))) // 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. From 96c49fba1b1f0cd853fb97e1ea53101f5078c228 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Tue, 17 Nov 2026 22:45:58 +0530 Subject: [PATCH 25/27] fix: a cd chain that may have stopped half way, a hidden cd and an option value shaped like --project-dir are not trusted Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 10 ++++++++++ plugins/altimate-code/hooks/features/defer.tsx | 6 +++++- 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 2daba60e..46a18914 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -202,6 +202,16 @@ test('a background cd chain, a pushd stack word, an option value that looks like 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') diff --git a/plugins/altimate-code/hooks/features/defer.tsx b/plugins/altimate-code/hooks/features/defer.tsx index 455136fa..4c842d52 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -160,6 +160,8 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 @@ -171,6 +173,8 @@ export function runsInProject(command: string, root: string, projectDir: string, 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 @@ -219,7 +223,7 @@ export function runsInProject(command: string, root: string, projectDir: string, } // 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]!))) + const named = [...command.matchAll(PROJECT_DIR)].filter(match => !quoted(command, match.index) && (match.index === 0 || /\s/.test(command[match.index - 1]!)) && !/(?:^|\s)-{1,2}[\w-]+\s+$/.test(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. From 010db648c3b8d054b157d5b563716a730ec93558 Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 09:45:10 +0530 Subject: [PATCH 26/27] test: complete the fake fs.list entries in the defer test Co-Authored-By: Claude Sonnet 5.5 --- plugins/altimate-code/hooks/features/defer.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index 46a18914..bc641370 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -267,7 +267,7 @@ test('a dbt project below the project, even under dbt_packages, keeps its own se 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' }, { name: 'dbt_packages', kind: 'dir' }] : e.path === `${ROOT}/dbt_packages` ? [{ name: 'pkg', kind: 'dir' }] : [] })) + 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` From 7eef6d903e5a80a04870205728adbaaa12cb0f1c Mon Sep 17 00:00:00 2001 From: Harish Kumar Date: Wed, 18 Nov 2026 09:58:11 +0530 Subject: [PATCH 27/27] fix: a flag that takes no value before --project-dir is no option's value, and an assignment before a wrapper counts as the command's own Co-Authored-By: Claude Opus 5.5 --- .../hooks/features/defer.test.ts | 10 ++++++++++ .../altimate-code/hooks/features/defer.tsx | 20 +++++++++++++++---- 2 files changed, 26 insertions(+), 4 deletions(-) diff --git a/plugins/altimate-code/hooks/features/defer.test.ts b/plugins/altimate-code/hooks/features/defer.test.ts index bc641370..336cde1f 100644 --- a/plugins/altimate-code/hooks/features/defer.test.ts +++ b/plugins/altimate-code/hooks/features/defer.test.ts @@ -399,3 +399,13 @@ test('a Windows --project-dir with backslashes names the project; an escaped spa 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 4c842d52..f913afb1 100644 --- a/plugins/altimate-code/hooks/features/defer.tsx +++ b/plugins/altimate-code/hooks/features/defer.tsx @@ -23,6 +23,11 @@ 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 = { @@ -54,12 +59,13 @@ export function rewriteDeferCommand(command: string, options: RewriteOptions): s // 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[] = [] - if (stateDir && !exportedState && DEFERS.has(one.subcommand) && !one.hasDefer && !one.hasState && !/\bDBT_(?:DEFER|DEFER_STATE)=/.test(command.slice(one.start, one.end))) { + 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(command.slice(one.start, one.end)) || (/\bexport\b/.test(command) && /\bDBT_FAVOR_STATE=/.test(command)) + 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(command.slice(one.start, one.end))) flags.push('--target', quote(target)) + 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)}` } @@ -98,6 +104,12 @@ async function findProject($: EngineInterface): Promise { 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 @@ -223,7 +235,7 @@ export function runsInProject(command: string, root: string, projectDir: string, } // 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]!)) && !/(?:^|\s)-{1,2}[\w-]+\s+$/.test(command.slice(0, match.index))) + 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.