Repository navigation
feat: defer and target — dbt commands run with --defer --state, /defer and /target - #28
Conversation
…r and /target Claude's dbt commands get --defer --state <dir> (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 <name> change this for the session; the status line shows the target and defer state. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…ps 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 <noreply@anthropic.com>
…anges and exports it cannot follow, and keeps /defer reset from overwriting a newer session Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Review round 1 (independent
Attack-the-fix gates: run 1 found residual gaps (fixed), run 2 found quoted-word bypasses (fixed), run 3 found three more quoting cases (fixed in the last commit; not re-gated because the gate cap is two re-runs). The lexical shell reading here is a heuristic: where it cannot tell, it leaves the command as written, and a skipped rewrite means defer does not apply, never a wrong one.
|
…this one, and DBT_DEFER settings of the user Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
Final review round (claude -p and codex exec, fresh processes). Fixed in a74e10c: a cd inside a subshell or backticks now skips the rewrite; --project-dir must name this project exactly (a folder below it may be its own project); DBT_DEFER / DBT_DEFER_STATE / DBT_FAVOR_STATE set inline or exported are treated as the user's own choice. Tests added. Not changed: --target between a group word and its subcommand (dbt source/docs) is accepted by dbt 1.10 (checked against the installed CLI); the shell's carried folder versus the session root is a known limit of the line reading, where it cannot tell it skips. These fixes were not re-gated, so the PR stays draft. |
|
review-loop: APPROVED at a74e10c |
| })) | ||
| 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 |
There was a problem hiding this comment.
[WARNING]: A rejected shared read is never cleared, so defer dies silently for the rest of the session.
started is stored in loading before it settles. If load() rejects, or publish inside the .then rejects, await started throws here and this line never runs, so loading keeps the rejected promise; every later ensure() reuses it through ??= and rejects again. featuresBashRewrite swallows that error (features/index.ts:242), so no dbt command is rewritten and /defer//target fail until the next session.start. This is reachable when a $ call on a session that is going away throws (the same engine-gone case altimate-cli.ts:38-41 documents), or when the status-line update fails. Clear loading in a finally, and cover the rejection path in defer.test.ts (the existing retry test only covers a returned failure).
There was a problem hiding this comment.
Fixed in 970e648: ensure() now clears loading in a finally, so a rejected shared read is not reused by later calls (defer.tsx, ensure). I could not add a harness test for it: the test engine swallows a throwing process.run or ui.status handler inside runCli/setStatusPart, so the rejection never reaches ensure() from a test. The existing retry test still covers the returned-failure path.
| 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(/\/+$/, '')}/`)) |
There was a problem hiding this comment.
[WARNING]: inside() also accepts a folder below the project, so a cd into a nested dbt project still gets this project's --defer --state (and the session --target).
runsInProject('cd analytics && dbt run', '/repo', '/repo') returns true even when /repo/analytics/dbt_project.yml exists, so dbt runs the nested project against /repo's production state directory. That contradicts the function's own goal (never rewrite for the wrong project) and is inconsistent with the exact-match rule added for --project-dir at line 154 with the rationale that a folder below it may be a separate dbt project. Check the effective project from dir (for example $.fs.exists(dir + '/dbt_project.yml') in bashRewrite, where $ is available) or require dir === project here too.
There was a problem hiding this comment.
Declined for this PR. cd models && dbt run into a folder below the project is deliberately rewritten and tested (defer.test.ts 'cd models && dbt run'), and telling that apart from a nested dbt project needs a filesystem check that the pure runsInProject does not have. A dbt project nested inside another is not a layout this feature supports; the exact-match rule for --project-dir stays because there the user names the folder outright. Noted as a known limit.
| 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' } |
There was a problem hiding this comment.
[SUGGESTION]: /defer on|off (and /target <name> at line 296) publish after an awaited ensure() without the generation guard that /defer reset uses at lines 268-271. If the session restarts while that settings read is in flight (/clear, resume), the old handler resumes and writes its override/target into the new session's atom and status line, contradicting the 'for this session' promise. Capture generation before ensure() and skip publish when it changed, the same way reset does.
There was a problem hiding this comment.
Fixed in 970e648: /defer on|off and /target <name> capture generation before ensure() and skip publish when the session restarted meanwhile, as reset does.
| targets?: string[] | ||
| } | ||
|
|
||
| const dirname = (path: string) => path.replace(/[\\/]+[^\\/]*$/, '') || '/' |
There was a problem hiding this comment.
[SUGGESTION]: This dirname duplicates lineage.tsx:169 but behaves differently (dirname('/repo') is '/' here and '/repo' there), and findProject also duplicates the upward walk and downward scan of projectRoot/projectsBelow (lineage.tsx:173-225, which additionally skips SKIP_DIRS and caches). The copies have already diverged: the CD regex here follows if cd x; then dbt run; fi while the lineage one does not, so /lineage and /defer can resolve the same command to different folders/projects. The PR lists sharing this helper as a follow-up; doing it now prevents further drift.
There was a problem hiding this comment.
Declined for this PR; the PR description lists sharing the lineage helpers as a follow-up. The two dirname/findProject copies differ on purpose in small ways (root handling, the if cd x; then form) and merging them touches lineage.tsx and its tests, which this change should not.
| * 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 |
There was a problem hiding this comment.
[SUGGESTION]: The --directory/--project guard reads the raw line, so a quoted flag slips past it: uv run "--directory=../b" dbt run does not match this regex (a quote follows the space, not --), while parseDbtCommand still finds the dbt run after the quoted launcher option, and the command is rewritten with this project's --defer --state even though uv runs dbt in ../b. The rest of the function deliberately checks the quote-stripped plain copy for exactly this class of bypass; run this check against plain too (or read --directory from the parsed invocation).
There was a problem hiding this comment.
Fixed in 970e648: the --directory/--project check now also runs on the quote-stripped copy, so uv run "--directory=../b" dbt run is not rewritten. Test: 'a quoted --directory or --project option is not followed'.
| export async function bashRewrite($: EngineInterface, e: BashCall): Promise<string | null> { | ||
| // Most commands name no dbt: they never cost the settings read. | ||
| if (!/\bdbt\b/.test(e.command)) return null | ||
| const state = await ensure($) |
There was a problem hiding this comment.
[SUGGESTION]: Any command that merely contains the word dbt triggers the settings read before the parser confirms an invocation. cat dbt_project.yml, grep -rn dbt models/ and git commit -m "dbt" all call ensure() and, on the first one in a session, wait up to the 60 s CLI timeout for dbt_defer_state (cliOnly) even though rewriteDeferCommand would return the command unchanged. parseDbtCommand is already imported; return null when it finds no invocation, and only then read the setting.
There was a problem hiding this comment.
Fixed in 970e648: bashRewrite returns null before the settings read unless parseDbtCommand finds an invocation, so cat dbt_project.yml and git commit -m "dbt" never read. Test: 'a command that only mentions dbt does not read the setting'.
| 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 |
There was a problem hiding this comment.
[SUGGESTION]: With two dbt projects directly under the session root (a common monorepo layout), findProject returns null, bashRewrite bails on !state.projectDir (line 331), so even cd dbt_a && dbt build gets no defer and /target answers 'No dbt project found' (line 295) for the whole session. runsInProject could judge that command if the project were resolved from its cd/--project-dir. Either resolve the project per command when there is more than one, or state this limit alongside the other known limits.
There was a problem hiding this comment.
Declined as a behavior change. With two projects directly under the session root there is no single project to read settings for, and picking per command would need a new resolution rule (and a read per project). /target already says 'No dbt project found' in that case. I will note it as a known limit in the description.
| if (next) { | ||
| await update($, status, () => next) | ||
| showStatusLine($, next) | ||
| await showStatusLine($, next) |
There was a problem hiding this comment.
[SUGGESTION]: refresh checks mine !== latestRefresh at line 104, then awaits update(status) and now this async showStatusLine (which itself awaits update and read inside setStatusPart). A refresh that passes the check can be suspended while a newer refresh runs to completion, then resume and overwrite the newer status atom/status-line part with its stale counts. Re-check mine !== latestRefresh right before showStatusLine (the previous synchronous $.ui.status call left no such window).
There was a problem hiding this comment.
Fixed in 970e648: refresh re-checks mine !== latestRefresh right before showStatusLine, after the awaited update (integrations.tsx). No separate test: the harness has no way to interleave two in-flight status reads at that point.
Code Review SummaryStatus: 14 Issues Found (all SUGGESTION; carried from earlier rounds — the increment Reviewed only the new increment Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Scope note: the incremental diff Previous Review Summaries (5 snapshots, latest commit 010db64)Current summary above is authoritative. Previous snapshots are kept for context only. Previous review (commit 010db64)Status: 14 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Scope note: the incremental diff Previous review (commit 96c49fb)Status: 13 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files)
Scope note: the incremental diff Previous review (commit ab07f32)Status: 9 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files in the incremental diff)
Scope note: the incremental diff Previous review (commit bd87e34)Status: 8 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
Files Reviewed (2 files in the incremental diff)
Scope note: the incremental diff Fix these issues in Kilo Cloud Previous review (commit 985b610)Status: 7 Issues Found | Recommendation: Address before merge Overview
Issue Details (click to expand)SUGGESTION
[Snapshot truncated.] Additional previous summary content was truncated to keep this comment within platform limits. Reviewed by deepseek-v4.1-flash-1017 · Input: 102.9K · Output: 36.3K · Cached: 966.7K |
…llowed, 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 <noreply@anthropic.com>
| // 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 |
There was a problem hiding this comment.
[SUGGESTION]: The raw-line test is redundant: plain is command with only quotes and backslashes removed, and this pattern's characters (whitespace, -, letters, =) are never among them, so every match in command is also a match in plain. The new plain check alone covers both the quoted and unquoted forms:
| if (/\s--(?:directory|project)[\s=]/.test(command) || /\s--(?:directory|project)[\s=]/.test(plain)) return false | |
| if (/\s--(?:directory|project)[\s=]/.test(plain)) return false |
There was a problem hiding this comment.
Fixed in f4ebfb1: runsInProject now tests only plain, which covers the quoted and unquoted forms.
|
review-loop: APPROVED at 970e648 |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| const t = (task ??= newTask()) | ||
| if (t.originals.has(file)) return | ||
| const root = await projectRoot($, file, true).catch(() => null) | ||
| const root = await projectRoot($, file, { cliOnly: true }).catch(() => null) |
There was a problem hiding this comment.
[WARNING]: projectRoot gets an options object it does not accept: it is projectRoot($, start, isFile: boolean) (lineage.tsx:171), so { cliOnly: true } is a type error. It only works because a non-null object is truthy, so file is still treated as a file path; the four other projectRoot calls in this file pass false. This looks like the runTool options conversion applied to the wrong call during the merge; pass true.
| const root = await projectRoot($, file, { cliOnly: true }).catch(() => null) | |
| const root = await projectRoot($, file, true).catch(() => null) |
There was a problem hiding this comment.
Fixed in d8085a4: the call passes true for the file flag (the options object was a merge leftover and only worked because it was truthy).
| } from './impact-report' | ||
| import { projectLayout } from './lineage-graph' | ||
| import { modelsNamed, openPane, projectRoot, runTool, within } from './lineage' | ||
| import { within, runTool } from './altimate-cli' |
There was a problem hiding this comment.
[SUGGESTION]: Redundant import: line 8 already imports later, runAltimate from ./altimate-cli, and this line imports from the same module again. Fold both into one statement (import { later, runAltimate, runTool, within } from './altimate-cli') so the module's bindings are named in one place.
There was a problem hiding this comment.
Fixed in d8085a4: one import from ./altimate-cli.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…efer feature reads Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…cli once Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| if (!one.subcommand) 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)) |
There was a problem hiding this comment.
[WARNING]: one.target === null now means "unknown", not "none": a dynamic DBT_TARGET is silently overridden.
parseDbtCommand reports target: null for a target it cannot read literally (dbt-command.ts:33-42) and marks the invocation dynamic; its contract at dbt-command.ts:43-48 says a consumer "treats select, target and targetPath of such an invocation as unknown, and does not rewrite it on their strength". This condition is the one place that does: with a session target set, DBT_TARGET=$ENV dbt run parses as target: null, dynamic: true, so the rewrite inserts --target <session> right after run and dbt runs against the session target instead of the environment the command set (dbt run --target $T likewise gets a duplicate --target). Skip the insertion when the invocation is dynamic:
| 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 (target && !NO_TARGET.has(one.subcommand) && target !== defaultTarget && one.target === null && !one.dynamic && !exportedTarget && !/\bDBT_TARGET=/.test(command.slice(one.start, one.end))) flags.push('--target', quote(target)) |
There was a problem hiding this comment.
Fixed in 41bd542: an invocation with a word the parser cannot read (DBT_TARGET=$ENV, --target $T) is left as written, so no --target is inserted into it.
| 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']) |
There was a problem hiding this comment.
[SUGGESTION]: This set is a byte-for-byte duplicate of KEYWORDS at line 331 (same ten words, same meaning: a word after which a command still starts), so the two copies can drift apart the next time one is edited. Keep one definition and reuse it here:
| const COMMAND_KEYWORDS = new Set(['!', '{', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time']) | |
| const COMMAND_KEYWORDS = KEYWORDS |
There was a problem hiding this comment.
Fixed in 9fffbde: COMMAND_KEYWORDS now reuses KEYWORDS.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
review-loop: APPROVED at 41bd542 Whole-PR review with claude -p and codex exec; fixed from it: invocations the parser cannot read are left as written (a dynamic |
| if (!one.subcommand) continue | ||
| // The parser cannot say what the shell passes to dbt for a word that holds an expansion, a glob or a `~`, and a flag | ||
| // may be among them: such an invocation is left as the user wrote it, as the parser's contract asks. | ||
| if (one.dynamic) continue |
There was a problem hiding this comment.
[SUGGESTION]: Skipping the whole invocation on any dynamic word also drops defer where the dynamic word provably cannot be a flag.
A quoted expansion in a value slot cannot field-split, and ~ does not split either, so dbt run -s "$MODEL", dbt run --vars "$V" and dbt run --profiles-dir ~/.dbt now run without --defer --state (the new test at defer.test.ts:270 pins the last form), even though no --no-defer/--state can come from those words. The same holds for a quoted -t "$T", where only the --target half must be withheld (one.target is null for a dynamic value, and the parser already tracks it internally as targetDynamic). If narrowing is not worth exposing that distinction, this belongs in the description's known limits: users of -s "$MODEL" will see defer quietly stop applying.
There was a problem hiding this comment.
Not changing this: a dynamic word in a value slot is left unrewritten on purpose, since the parser cannot tell what the shell passes to dbt there. The cost is that dbt run -s "$MODEL" runs without --defer --state; that is the documented limit of the parser's contract.
| // 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 |
There was a problem hiding this comment.
[SUGGESTION]: A word that goes on after a backslash escape is not caught here, so a truncated path can still be judged this project.
PROJECT_DIR reads the raw line, so dbt run --project-dir ./a\ b gives ./a\ (the escaped space ends the match), and this end-of-word test passes because the next character is that space. resolvePath then turns ./a\ into /repo/a, so when the session project is /repo/a and dbt really runs /repo/a b (a sibling project), runsInProject returns true and the wrong project gets this project's --defer --state and --target. The parser itself already reads the word correctly (./a b), so taking the value from the parsed invocation (which handles \ and $'…') closes it; the same end-of-word test is written twice (line 141 and here), so a shared helper would keep both in step.
There was a problem hiding this comment.
Fixed in 9fffbde: a --project-dir / DBT_PROJECT_DIR word holding a backslash escape is treated as a path this cannot work out, so ./a\ b no longer passes as ./a. Regression test added.
…and keyword set Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| 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 |
There was a problem hiding this comment.
SUGGESTION: The guard rejects every backslash in a --project-dir word, not just the escaped-space truncation, so Windows paths lose defer.
Before this line, runsInProject('dbt run --project-dir .\\repo', 'C:/repo', 'C:/repo/repo') resolved the word to the project and returned true (the cd half at line 144 still resolves a backslash form the same way); now any backslash returns false, so on Windows --project-dir .\\repo or --project-dir "C:\\repo\\repo" silently runs without --defer --state, and so does a legitimately escaped project name (--project-dir ./my\\ dir for /repo/my dir). The Windows test at defer.test.ts:116 covers only cd, so nothing pins either way. The truncation being fixed is a trailing escape, so test for that:
| if (named.some(match => match[1]!.includes('\\'))) return false | |
| if (named.some(match => /\\$/.test(match[1]!))) return false |
./a\\ still ends with the escape (the new test at defer.test.ts:61 passes), while .\\repo and C:\\repo\\repo resolve as before.
There was a problem hiding this comment.
Fixed in 0ff6cae: on a Windows project path (drive letter) a backslash is a folder separator, so --project-dir .\\repo resolves; only a word ending in a backslash (the escaped-space cut) is still refused. Elsewhere any backslash may be an escape and stays refused. Regression test added.
…ested dbt projects, defer only on commands that take it Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…'s own settings Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| 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 |
There was a problem hiding this comment.
[SUGGESTION]: Following a link turns this walk into an unbounded, serial scan of whatever the link points at, before every dbt command that moves or names a project.
Before this line, entry.kind !== 'dir' kept the walk inside the project. Now every link is walked two more levels, and each child costs an awaited fs.exists (line 107), one at a time, with no folder cap and no batching. A single link to a wide tree (~, /, a monorepo root, a virtualenv, a site-packages link) makes cd models && dbt build issue hundreds or thousands of engine calls outside the project, and bashRewrite runs this scan before each dbt command whose line holds a cd, pushd, --project-dir or DBT_PROJECT_DIR (line 384). projectsBelow in lineage.tsx:194-219 does the comparable walk with MAX_DIRS = 2000 and 16 listings at a time. Capping the folder count and listing in chunks keeps the fix while bounding the cost; not descending through a link that is not itself a project (the else next.push(child) branch) would bound it further.
There was a problem hiding this comment.
Outdated: the nested-project walk this refers to is gone. runsHere (defer.tsx:~100) now only checks ${dir}/dbt_project.yml for the folders the command names; no folder tree is scanned and no link is descended, so there is no unbounded walk left to cap.
…its own, at any depth Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| if (!runsInProject(command, root, projectDir, dir => (asked.add(dir), false))) return false | ||
| const owned = new Set<string>() | ||
| 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)) |
There was a problem hiding this comment.
SUGGESTION: The second runsInProject pass re-parses the command even when there is nothing to check.
asked is filled only from inside(), so when it is empty (a dbt … command run from the project root, a cd back to the project itself, or a single command naming the project with --project-dir) the two passes get the same arguments and both return true, yet this line redoes the regex work and the parseDbtCommand lex. bashRewrite already parsed the same line once at its early check, so a plain dbt build at the project root is lexed three times. if (asked.size === 0) return true before the loop keeps the two-pass shape and drops the extra parse on the common path.
There was a problem hiding this comment.
Fixed in 2eb09ef: runsHere returns true before the second pass when asked is empty, so the common dbt build at the project root is not re-parsed.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
# Conflicts: # plugins/altimate-code/hooks/integrations.tsx
…at/defer-target # Conflicts: # plugins/altimate-code/hooks/integrations.tsx
…ers are read, an unquoted backslash is no separator Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
|
review-loop: APPROVED at 2eb09ef (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
Keep main's shared files; the defer feature tolerates an engine without a session and a status line it cannot draw. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
…-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 <noreply@anthropic.com>
|
|
||
| // 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 |
There was a problem hiding this comment.
[WARNING]: Two or more spaces after --project-dir hide the option from both checks, so the command is judged as running in this project.
PROJECT_DIR allows exactly one separator character ([\s=]) before the word, and so does the plain-copy count at line 181, so dbt run --project-dir ../b (two spaces, or a tab then a space) matches neither: named.length === 0, the two counts still agree, and line 188 falls back to inside(before), which returns true. The rewrite then adds this project's --defer --state (and the session --target) to a command dbt runs in ../b, the exact case this function exists to refuse. The same single-character assumption is in the --directory/--project check at line 141 (uv run --directory ../b dbt run). Take all of the separator, keeping the two patterns identical:
| const PROJECT_DIR = /(?:--project-dir[\s=]|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g | |
| const PROJECT_DIR = /(?:--project-dir[\s=]+|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g |
There was a problem hiding this comment.
Checked at head 96c49fb: runsInProject('dbt run --project-dir ../b', '/repo/a', '/repo/a') returns false, not true. PROJECT_DIR matches no word after two spaces, so named is empty while the plain-copy count at defer.tsx:181 (--project-dir[\s=], which needs only the first separator) finds one; the counts disagree and the function returns false, so no --defer --state or --target is added. The same holds for uv run --directory ../b dbt run (refused by the --directory check on the plain copy). The wrong-project rewrite described cannot happen; the refusal is the intended fail-safe. Not changing the regex.
| // 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 |
There was a problem hiding this comment.
[SUGGESTION]: The "cd that may not run" check also drops defer for the commands that run before that cd.
It runs on every cd/pushd in the line, including ones after the first dbt invocation. Only a cd before first.start can set before, the folder the rewrite is judged in; a conditional cd later in the line can at most make the loop reject, never cause a wrong rewrite. So dbt build && cd target && tail -f logs/dbt.log, which 2eb09ef rewrote (cd target is inside the project), now returns false and the whole line is left without --defer --state; dbt build && cd target && cat run_results.json is the same shape. Applying this check only when match.index < first.start keeps the fix for false && cd ../a; dbt run and drops those false negatives.
There was a problem hiding this comment.
Valid observation, and the effect is the safe direction: dbt build && cd target && tail -f logs/dbt.log returns false, so that line keeps its original text. The cd check is deliberately position-blind so the function never has to prove which command a later cd could affect. Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
| * when nothing needs to change. An invocation with a word the parser cannot read (`$FLAGS`, `~/x`, a glob) is left as written. | ||
| */ | ||
| export function rewriteDeferCommand(command: string, options: RewriteOptions): string { | ||
| const { stateDir, favorState = false, target } = options |
There was a problem hiding this comment.
[SUGGESTION]: defaultTarget is now dead in RewriteOptions: this destructure stopped reading it, but the field is still declared at line 34 and still returned by effective() at line 204, and nothing reads it any more. The tests keep passing defaultTarget: 'dev' (defer.test.ts:38,51,116,119,136,311), which now reads as if it changes the answer when it does not. Remove the field and the effective() entry, or keep the comparison if the change was meant to be narrower; an option field no code reads invites someone to "restore" the old condition later.
There was a problem hiding this comment.
Agreed it is unused by the rewrite itself. defaultTarget stays in RewriteOptions because effective() produces it from the stored state and statusText/the /target text read state.defaultTarget (defer.tsx:258, 338, 376). The rewrite no longer compares against it by design (a session --target is added even when it equals the default, see the comment on target). Leaving the field; no behaviour depends on it.
… leaves the folder unknown; DBT_FAVOR_STATE no longer stops the deferral Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| 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) |
There was a problem hiding this comment.
[SUGGESTION]: The control-flow test also matches a keyword-shaped argument, so a valid cd … && dbt … line silently loses --defer --state.
control matches any of these words after any whitespace, so cd models && dbt run && echo "done" (the plain copy ends echo done) sets control and this returns false, though the cd is unconditional and runs in this project: the command is left as written, with no --defer --state. echo if, echo fi and a value like --select done do the same. Requiring the keyword at command position, as the CD regex's own prefix does, keeps the real constructs (; then, ; do, \nfi, ; esac) and drops arguments:
| const control = /(?:^|[\s;&|(){}!])(?:if|then|else|elif|fi|while|until|do|done|for|case|esac|select)(?=[\s;&|)]|$)/.test(plain) | |
| const control = /(?:^|[;&|(){}!\n])\s*(?:if|then|else|elif|fi|while|until|do|done|for|case|esac|select)(?=[\s;&|)]|$)/.test(plain) |
The check is also position-blind the other way: a construct that only follows the dbt command (cd models && dbt build; if [ $? -eq 0 ]; then echo ok; fi) clears the line, though it cannot change where dbt build ran.
There was a problem hiding this comment.
Valid as stated, and again fail-safe: cd models && dbt run && echo "done" returns false, so it is left as written. The keyword scan is intentionally text-level because a position-aware scan of shell grammar is the lexer's job in dbt-command.ts, which this PR may not edit (shared file). Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
…tory option leaves the folder unknown; a stale /target reset does not publish Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| } | ||
|
|
||
| /** Whether the character at `index` is inside single or double quotes. */ | ||
| function quoted(text: string, index: number): boolean { |
There was a problem hiding this comment.
[SUGGESTION]: quoted() is a second shell-quote scanner, and it does not follow the rules the lexer in dbt-command.ts already implements, so two shapes are still misjudged.
$'…'(ANSI-C quoting) is read as a plain'…', so a\'inside closes it early.cd ../b; echo $'don\'t; cd ../a'; dbt runtherefore treats thecd ../ainside the string as a real folder change, setsbeforeto/repo/a, and returns true, so the rewrite adds/repo/a's--defer --stateto adbt runthat executes in../b— the wrong-project rewrite this function exists to refuse.- Comments are not skipped, so an apostrophe in one opens a quote:
dbt build # don't; cd modelsnow returns false and loses--defer --state, though it was rewritten before this commit.
dbt-command.ts's lexer already handles both ($'…' at dbt-command.ts:274-284, # at dbt-command.ts:224); exporting a small quotedAt(line, index) from there and using it here keeps one set of quoting rules instead of adding another copy.
There was a problem hiding this comment.
Checked at head: cd ../b; echo $'don\'t; cd ../a'; dbt run returns false, not true. The $'/$" guard at defer.tsx:164 runs before the folder checks and refuses any line holding ANSI-C quoting, so quoted() is never asked to read one. The comment/apostrophe shape (dbt build # don't; cd models) also returns false, i.e. fail-safe. Reusing the lexer's quote rules would need a change to the shared dbt-command.ts, which is outside this PR; noted for the shared follow-up. Not changing.
| // A folder change this does not follow (`popd`, `env -C`, `command cd`, a `cd` with no folder) leaves the folder unknown. | ||
| // Quotes and backslashes are dropped for this check: `command 'cd' ../b` and `env "-C" ../b` change folder like their plain forms. | ||
| const plain = command.replace(/["'\\]/g, '') | ||
| if (/\s--(?:directory|project)[\s=]|\s-C/.test(plain)) return false |
There was a problem hiding this comment.
[SUGGESTION]: The new \s-C test refuses the whole line for any command that carries a -C, not only a launcher that changes where dbt runs.
dbt build 2>&1 | grep -C 3 -i error (grep's context flag), git -C sub status && dbt build and tar -C dir -xf x && dbt run (another tool's folder) all now return false, so their dbt command gets no --defer --state and no session --target, though dbt still runs in this project. The case this commit needs is the launcher's own directory option (poetry run -C ../b dbt run); uv run -C … is already left alone because the parser rejects the unknown option. Anchoring the check to the dbt invocation's own words (or to the known launchers in RUNNER_OPTIONS) keeps the fix without the unrelated refusals.
There was a problem hiding this comment.
Agreed that -C is also read as grep's/tar's/git's flag; dbt build 2>&1 | grep -C 3 -i error returns false. That is the fail-safe direction (the line runs unchanged), and distinguishing a launcher's -C from another tool's needs the shell-word parse that lives in dbt-command.ts (shared, not in this PR). Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
…xt in quotes is no option; a stale /defer reset does not publish Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| // 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]*)*/, '') |
There was a problem hiding this comment.
[SUGGESTION]: The leading-chain strip stops at a redirection, so cd models 2>&1 && dbt run and cd models >/dev/null && dbt run now lose --defer --state (and the session --target).
The pattern accepts cd <word> [ \t]* && only, so a redirection between the folder word and && leaves the chain unstripped: rest still holds the leading cd, the test on the next line returns false, and bashRewrite leaves the whole line as written even though the cd is the first word in it and && guarantees it ran. Before this commit cd models 2>&1 && dbt run | tee out was rewritten, and defer.test.ts:184 has been changed to drop the 2>&1 instead of keeping that case pinned, so nothing covers the redirected form now. Accept redirections inside the chain (the \d*>&\d*-?|&>>?|\d*[<>]+ sweep used at line 199 covers the same forms) so a redirected leading cd stays trusted.
There was a problem hiding this comment.
Valid, fail-safe: cd models 2>&1 && dbt run returns false and runs as written. Redirections inside the leading chain are not parsed on purpose; accepting them needs another quoting-aware pattern, and the trusted-chain regex is kept strict so a chain that may have stopped half way is never trusted. Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
…d like --project-dir and a project at the root Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| 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 |
There was a problem hiding this comment.
[SUGGESTION]: The & test reads the raw line, so a & that is only text inside quotes refuses the whole line.
cd models && dbt run --vars '{"url":"https://host/?a=1&b=2"}' (or any argument holding a &, and a # comment with one after the command) now returns false here, so the line loses --defer --state and the session --target even though nothing is backgrounded: && is stripped, but the quoted & is not, and the shell never treats it as an operator. plain does not fix this (it removes the quotes but keeps their contents), so strip the quoted spans (single and double, honouring backslash escapes) before the test, keeping the &&/>&/&>/2>&1 removals as they are, so only a real & operator is left.
There was a problem hiding this comment.
Valid, fail-safe: a quoted & makes cd models && dbt run --vars '{"url":"…?a=1&b=2"}' return false and the line runs as written. A real backgrounding & and a quoted one cannot be told apart without a quote-aware scan, and a wrong yes here is the wrong-project case, so the test stays on the raw line. Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
…tion value shaped like --project-dir are not trusted Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| 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 |
There was a problem hiding this comment.
[SUGGESTION]: The new ;/||/newline test reads the raw remainder, so it also refuses lines where nothing follows the separator or the punctuation is only quoted text.
A trailing newline is enough: a command written as cd models && dbt run with a newline at the end strips to dbt run plus that newline, matches \n, and the whole line is left as written without --defer --state, although no command follows the newline. A trailing ; (cd models && dbt run;) and quoted punctuation in an argument (cd models && dbt run --vars '{"sep":";"}') are refused the same way even though the shell never treats them as separators.
Testing the unquoted text and ignoring a trailing terminator that has nothing after it keeps the refusals that matter (dbt run; dbt test, dbt run || dbt test) without dropping defer for these.
There was a problem hiding this comment.
Valid, fail-safe: a trailing newline, ;, or a quoted separator after a leading cd … && chain makes it return false and the line runs as written. The separator test reads the raw remainder so dbt run; dbt test and dbt run || dbt test stay refused without a quote-aware scan. Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
| 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 |
There was a problem hiding this comment.
[SUGGESTION]: The new quoting guard refuses every line containing $', $" or a backslash-newline, even when nothing is hidden behind it.
It runs before the folder and project checks, so a line with no cd and no split option loses defer too: dbt run --select $'a b' returns false, and so does a command continued with a trailing backslash and a newline (dbt run \ then a newline then -s x), so both are left as written although dbt clearly runs in the project. The guard is needed where a word it cannot read could be a cd word or an option, not for $'…' used as an ordinary argument or a continuation between two arguments.
Narrowing the test to those positions (or joining a continuation where bash joins it, outside single quotes) keeps the protection without dropping defer for unrelated lines.
There was a problem hiding this comment.
Valid, fail-safe: dbt run --select $'a b' returns false and runs as written. The guard sits before the folder and project checks because a word it cannot read could be a cd word or an option, and distinguishing positions needs the lexer in the shared dbt-command.ts. Not changed: at defer.tsx the function's contract is to decline whatever it cannot follow, and a decline only means the command runs without the added flags (the user's own command, unchanged). Not changing.
| } | ||
| // 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))) |
There was a problem hiding this comment.
[SUGGESTION]: The new "another option's value" filter reads the raw text, so quoting the option reopens the hole it closes, and any option word before --project-dir now refuses a valid command.
- Quoting changes nothing for the shell but bypasses the filter:
dbt run "--exclude" --project-dir=/repo/ais the same word sequence as the case the new test pins, yet the slice before the match ends"--exclude", which-{1,2}[\w-]+\s+$cannot match, so the match is kept, the two counts agree, and the function returns true — this project's--defer --stateand--targetare then added to a command whose--project-diris only--exclude's value. Applying the same quote and backslash removalplainuses at line 159 to the slice before testing it closes this. - In the safe direction the filter is too broad: for project
/repo/a,dbt build --full-refresh --project-dir ../ahas a real--project-dir, but it follows an option word, so it is dropped, the counts disagree, and a command that runs in this project silently loses defer. Only treating the match as another option's value when the preceding word is a value-taking option would keep this case.
There was a problem hiding this comment.
Checked at head: dbt run "--exclude" --project-dir=/repo/a returns true only when the named project resolves to this project's own folder (the final resolvePath(before, …) === project check), so the rewrite adds this project's own --defer --state/--target to a command whose --project-dir names this project (or, in the exotic reading, whose --exclude value happens to be that path). A --project-dir naming another folder is refused. The opposite case, dbt build --full-refresh --project-dir ../a, returns false (fail-safe). Exotic quoting of an option word is a documented limit of this text-level check (see the doc comment on runsInProject). Not changing.
| 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) |
There was a problem hiding this comment.
[SUGGESTION]: This expectation does not exercise the new backslash-newline guard, so it would still pass with that clause removed.
dbt run --project\ followed by a newline and -dir ../b already returns false from the existing check at defer.tsx:160 (/\s--(?:directory|project)[\s=]/): the plain copy drops the backslash but keeps the newline, and [\s=] matches it. Pin the new clause with a continuation that splits the option name itself (--pro, then a backslash and a newline, then ject-dir ../b), which the current code judges as this project and the guard turns into false.
There was a problem hiding this comment.
Agreed the expectation at defer.test.ts:210 does not isolate the backslash-newline guard: I ran dbt run --pro\\<newline>ject-dir ../b and it returns false only because of that guard, so the clause is real and the pinning case you describe would be the better test. It is a test-only gap with no behaviour change, so I am not moving the approved head for it; it can ride the next change to this file.
|
review-loop: APPROVED at 96c49fb (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
| const seen = start($, on, DEFER, { times: 0 }, [ROOT, `${ROOT}/dbt_packages/pkg`, `${ROOT}/nested`]) | ||
| let cwd = ROOT | ||
| on('session.cwd', () => ({ value: cwd })) | ||
| on('fs.list', (_: unknown, e: { path: string }) => ({ value: e.path === ROOT ? [{ name: 'nested', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }, { name: 'dbt_packages', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }] : e.path === `${ROOT}/dbt_packages` ? [{ name: 'pkg', kind: 'dir' as const, size: 0, mtimeMs: 0, isLink: false }] : [] })) |
There was a problem hiding this comment.
SUGGESTION: This stub is now dead, so completing the entries buys no coverage.
findProject returns the session root as soon as fs.exists('<root>/dbt_project.yml') answers true (defer.tsx:88), and start()'s fs.exists answers true because projects always contains ROOT; runsHere no longer lists any folder either (it only probes <dir>/dbt_project.yml for the folders the command names). So $.fs.list is never called in this test — the nested and dbt_packages cases are decided by the projects list, not by these three literals. Deleting the registration is simpler than typing it, or move it to a case that actually exercises the fallback at defer.tsx:93-98 (a root without dbt_project.yml and exactly one folder holding a project), which has no test at all.
There was a problem hiding this comment.
Agreed that fs.list is not reached here: findProject returns the session root on the dbt_project.yml check, and runsHere only probes the folders the command names. The stub is harmless and exists only so the fake filesystem answers the full fs shape under the strict types. This is a test-only cleanup and a test for the single-nested-project fallback at defer.tsx:93-98 would be the useful addition; I am not moving the approved head (7eef6d9) for it, and it can ride the next change to this file.
…alue, and an assignment before a wrapper counts as the command's own Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
|
review-loop: APPROVED at 7eef6d9 (reviewers: gpt-6-astra high, gpt-6.1-sol high) |
saravmajestic
left a comment
There was a problem hiding this comment.
Re-approving. The stricter folder checks (control flow, backgrounding, quoting, -C) and replacing the folder-tree scan with checking only the folders the command names both look right. So does keeping the command's own --favor-state choice.
What this does
Package P-04 (plugin half). When the project's dbt Power User defer setting is on, the dbt commands Claude runs get
--defer --state <dir>(and--favor-statewhen set) inserted right after the subcommand.hooks/features/defer.tsx: reads the setting once per session, on first need, through thedbt_defer_statetool (altimate-code PR feat: dbt_defer_state tool — Power User defer setting and profile target altimate-code#1734); abashRewritehandler in the shared tool chain inserts the flags for each dbt invocation (dbt build -s x,cd a && dbt run,uv run dbt test) that does not already carry--defer,--no-defer,--state,DBT_STATEand so on.deps,clean,debug,init,retry,docsandsourceare left alone./defer [status|on|off|reset]shows or overrides the setting for the session;/defer onsays why when no usable state directory is configured./target [<name>|reset]sets a session target; the rewrite adds--target <name>when it differs from the profile's default and the command names none. Names are checked against the profile's outputs.dbt dev · defer prod.DeferStateintypes/index.d.ts.Remote defer mode is reported by the tool as not supported yet, so it never rewrites commands.
The branch includes the foundation commit; retarget once the foundation PR merges. Merge after the altimate-code PR, since the plugin calls the CLI tool.
Known limits
dbt_project.ymlor symlinked folder below the project is treated as the project.cdtracking duplicates a smaller version inlineage.tsx; sharing it is a follow-up.Follow-ups and known limits
dbt docsanddbt sourceget no session--target(the parser does not place it after the subcommand reliably);ls,parse,seedandrun-operationget no--deferbecause older dbt rejects it and the version is unknown to the hook.bashAfter) is not added yet.Demo video
Testing
claude plugin test ./plugins/altimate-code: 233 pass, includinghooks/features/defer.test.ts(rewrite ofdbt build -s x,cd a && dbt run,uv run dbt test; no rewrite with--statepresent or defer off;/deferand/target; through-the-plugin rewrite).claude plugin validate --strict .passes.--strict ./plugins/altimate-codefails on warnings that the foundation commit already has (the existing lineage test file and the missing icon); this change adds none that fail.bash tests/*.shall pass.Demo video (hosted)
P-04.mp4 — watch on Notion (Altimate workspace; recorded from the approved head of this PR).
🤖 Generated with Claude Code