Skip to content

feat: defer and target — dbt commands run with --defer --state, /defer and /target - #28

Merged
hkaltai merged 35 commits into
mainfrom
feat/defer-target
Nov 18, 2026
Merged

hkaltai merged 35 commits into
mainfrom
feat/defer-target

Conversation

@hkaltai

@hkaltai hkaltai commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor

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-state when set) inserted right after the subcommand.

  • hooks/features/defer.tsx: reads the setting once per session, on first need, through the dbt_defer_state tool (altimate-code PR feat: dbt_defer_state tool — Power User defer setting and profile target altimate-code#1734); a bashRewrite handler 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_STATE and so on. deps, clean, debug, init, retry, docs and source are left alone.
  • /defer [status|on|off|reset] shows or overrides the setting for the session; /defer on says 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.
  • The status line part shows target and defer, for example dbt dev · defer prod.
  • DeferState in types/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

  • The shell reading is lexical: a command with a folder change or project option it cannot follow is left as written (defer does not apply), never rewritten for the wrong project.
  • The project check starts from the session folder (the engine exposes no shell folder), and a nested dbt_project.yml or symlinked folder below the project is treated as the project.
  • cd tracking duplicates a smaller version in lineage.tsx; sharing it is a follow-up.

Follow-ups and known limits

  • dbt docs and dbt source get no session --target (the parser does not place it after the subcommand reliably); ls, parse, seed and run-operation get no --defer because older dbt rejects it and the version is unknown to the hook.
  • A one-line note to Claude when a command was rewritten (bashAfter) is not added yet.

Demo video

Testing

  • claude plugin test ./plugins/altimate-code: 233 pass, including hooks/features/defer.test.ts (rewrite of dbt build -s x, cd a && dbt run, uv run dbt test; no rewrite with --state present or defer off; /defer and /target; through-the-plugin rewrite).
  • claude plugin validate --strict . passes. --strict ./plugins/altimate-code fails 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/*.sh all pass.

Demo video (hosted)

P-04.mp4 — watch on Notion (Altimate workspace; recorded from the approved head of this PR).

🤖 Generated with Claude Code

hkaltai and others added 4 commits November 13, 2026 17:03
…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>
@hkaltai

hkaltai commented Nov 13, 2026

Copy link
Copy Markdown
Contributor Author

Review round 1 (independent claude -p and codex exec reviewers, three attack-the-fix gate runs). Replies per finding — fixes are in ce3f002.

# Finding Reviewer Resolution
1 A project named with --project-dir / DBT_PROJECT_DIR anywhere in the line vouched for every dbt command in it codex, MAJOR Fixed: only a single dbt command with the option inside its own text is judged; anything else is left as written.
2 Folder changes not followed (popd, env -C/--chdir, command cd, bare cd, $/backtick words, quoted forms like 'cd', "."/..) codex, MAJOR Fixed: such lines are left as written (folder unknown). Tests added.
3 Descendant folder judged the same project without checking a nested dbt_project.yml / symlink codex, MAJOR Not changed: needs filesystem access inside a pure function; the case is a nested project inside the one being worked in. Recorded as a known limit.
4 /defer reset could publish a read from an earlier session codex, MAJOR Fixed: the same generation check ensure uses. Checked by the gate with an in-memory race run; not a durable test (the test harness cannot hold a CLI call).
5 --target between a command group and its subcommand (dbt source --target x freshness) claude, MAJOR (0.8) Rebutted with evidence: with the installed dbt 1.10, dbt docs --target x generate and dbt source --target x freshness are accepted, while dbt docs --bogus generate is rejected, so group-level --target is valid.
6 NO_DEFER skip list lets --defer reach parse / run-operation claude, MAJOR (0.6) Rebutted with evidence: installed dbt 1.10 lists --defer for parse and run-operation. Skip list kept for commands that read or write run state.
7 Project check starts from the session root, not the shell's current folder claude, MAJOR (0.55) The engine exposes no shell folder; recorded as a known limit, left in the description.
8 cd tracking duplicates lineage.tsx claude, MAJOR (0.6) lineage.tsx belongs to another change; sharing the helper is a follow-up.
9 /target <name> claims success with no dbt project claude, MINOR Fixed.
10 Rewrites wrong when invocations are not in source order (dbt ls <(dbt ls)) claude, MINOR Fixed: sorted by position; test added.
11 export DBT_STATE=… && dbt build overridden claude, MINOR Fixed: a line with an export of DBT_STATE / DBT_TARGET is left alone, whatever the quoting. Tests added.
12 First read can hold the first dbt command up to 60 s claude, MINOR Not changed: a CLI that does not answer is retried only once a minute; a shorter timeout needs an engine option I could not confirm.
13 Redundant DBT_TARGET= check claude, NIT Kept: the parser's target does not cover an export.

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.

claude plugin test: 233 pass.

…this one, and DBT_DEFER settings of the user

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
@hkaltai

hkaltai commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

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.

@hkaltai
hkaltai marked this pull request as ready for review November 14, 2026 05:44
@hkaltai

hkaltai commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(/\/+$/, '')}/`))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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' }

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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(/[\\/]+[^\\/]*$/, '') || '/'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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($)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@kilo-code-bot

kilo-code-bot Bot commented Nov 14, 2026 •

Copy link
Copy Markdown

Code Review Summary

Status: 14 Issues Found (all SUGGESTION; carried from earlier rounds — the increment 010db64..7eef6d9 adds no new finding) | Recommendation: Address before merge

Reviewed only the new increment 010db64..7eef6d9 (fix: a flag that takes no value before --project-dir ...). It holds up: valueOfPrevious (defer.tsx:108) keeps --full-refresh-style flags from swallowing a real --project-dir while --exclude-style values are still refused, and segmentStart (defer.tsx:29) recovers the assignment that a wrapper clears in readSimple (dbt-command.ts:715), so DBT_FAVOR_STATE=false command dbt run keeps its own choice and dbt run && dbt test still gets the session target. No new defect found in the added lines; the rows below are the earlier findings re-checked at HEAD.

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 14
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.tsx 39 RewriteOptions.defaultTarget (declared here, filled by effective() at 263) is never read by the rewrite, while defer.test.ts still passes defaultTarget: 'dev' as if it mattered. Remove it (and the test parameters) or restore the comparison.
plugins/altimate-code/hooks/features/defer.tsx 60 if (one.dynamic) continue drops defer for the whole invocation, so dbt run -s "$MODEL" and dbt run --profiles-dir ~/.dbt get no --defer --state. Declined by the author as the parser's contract; the description's known limits do not list dynamic value words.
plugins/altimate-code/hooks/features/defer.tsx 104 Two dbt projects directly under the session root leave projectDir null, so no command is rewritten and /target answers "No dbt project found" for the whole session. Not listed under known limits.
plugins/altimate-code/hooks/features/defer.tsx 129 quoted() is a second quote scanner that diverges from the dbt-command.ts lexer (no $'…' rules, no # comments). The $'/\" guard at line 176 covers the ANSI-C case and the comment/apostrophe shape stays fail-safe, so this is a duplication hazard rather than a live miss.
plugins/altimate-code/hooks/features/defer.tsx 172 The \s-C test refuses the whole line for any -C, so dbt build 2>&1 | grep -C 3 error, git -C sub status && dbt build and tar -C dir … && dbt run lose --defer --state; only a launcher's own -C needs the guard. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 176 The $'/$"/backslash-newline guard runs before every folder and project check, so dbt run --select $'a b' and a command continued with \ plus a newline between arguments lose defer although dbt clearly runs in the project. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 177 The control-flow test matches keyword-shaped arguments and is position-blind: cd models && dbt run && echo "done" and dbt run -s done set control and lose --defer --state. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 182 The background-& test runs on the raw line, so a & that is only text inside quotes (--vars '{"url":"https://host/?a=1&b=2"}') refuses the whole line though nothing is backgrounded. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 186 The leading cd chain strip accepts cd <word> [ \t]* && only, so a redirection between the word and && leaves the chain unstripped and the line refused: cd models 2>&1 && dbt run loses --defer --state. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 189 The ;/||/newline test reads the raw remainder, so a trailing newline or ; (cd models && dbt run with a final newline, cd models && dbt run;) and quoted punctuation (--vars '{"sep":";"}') refuse the whole line although nothing follows the separator. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 222 The "cd that may not run" lead check runs for every cd/pushd, including ones after the first dbt invocation, so dbt build && cd target && tail -f logs/dbt.log returns false and dbt build loses defer. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 238 The "another option's value" filter now correctly keeps a real --project-dir after a flag that takes no value (--full-refresh), but it still reads the raw slice: quoting changes nothing for the shell yet bypasses the filter, so dbt run "--exclude" --project-dir=/repo/a is kept, the counts agree, and this project's --defer --state/--target are added to a command whose --project-dir is only --exclude's value. Stripping quotes/backslashes from the slice before the test closes it. Author declined as an exotic quoting limit.
plugins/altimate-code/hooks/features/defer.test.ts 210 The new expectation passes through the existing \s--(?:directory|project)[\s=] check at defer.tsx:172, not the backslash-newline clause, so the guard is unpinned. Use a continuation inside the option name (--pro, backslash, newline, ject-dir). Author agreed; fix deferred to the next change.
plugins/altimate-code/hooks/features/defer.test.ts 270 The fs.list stub is dead here, so completing the entries adds no coverage: findProject returns the root as soon as fs.exists('<root>/dbt_project.yml') is true (defer.tsx:94, and start()'s fs.exists always says yes for ROOT), while runsHere lists no folder at all. Delete the registration, or move it to a test that covers the below.length === 1 fallback at defer.tsx:99-104, which nothing covers.
Files Reviewed (2 files)
  • plugins/altimate-code/hooks/features/defer.tsx - 12 carried findings (lines 39, 60, 104, 129, 172, 176, 177, 182, 186, 189, 222, 238)
  • plugins/altimate-code/hooks/features/defer.test.ts - 2 carried findings (lines 210, 270)

Scope note: the incremental diff 010db64..7eef6d9 is one commit (2 files, +26/-4) that replaces the raw -{1,2}[\w-]+\s+$ filter with a value-less-flag allowlist and widens the "command's own text" to the start of its simple command. Production edits were traced against parseDbtCommand/readSimple rather than re-reviewed as a whole; nothing in the added lines produces a wrong rewrite (the new allowlist only admits options dbt defines as taking no value, and the broadened ownText only suppresses flag insertion). No tests were executed (read-only review).

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

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 14
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.test.ts 270 NEW: the fs.list stub is dead here, so completing the entries adds no coverage — findProject returns the root as soon as fs.exists('<root>/dbt_project.yml') is true (defer.tsx:88, and start()'s fs.exists always says yes for ROOT), while runsHere lists no folder at all. The nested/dbt_packages cases come from the projects list. Delete the registration, or move it to a test that covers the below.length === 1 fallback at defer.tsx:93-98, which nothing covers.
plugins/altimate-code/hooks/features/defer.tsx 177 The ;/||/newline test reads the raw remainder, so a trailing newline or ; (cd models && dbt run with a final newline, cd models && dbt run;) and quoted punctuation (--vars '{"sep":";"}') refuse the whole line although nothing follows the separator: --defer --state is silently not added. Author declined as fail-safe; a trailing newline is ordinary tool input.
plugins/altimate-code/hooks/features/defer.tsx 226 The "another option's value" filter reads raw text. Quoting reopens the hole the guard closes: traced at HEAD, runsInProject('dbt run "--exclude" --project-dir=/repo/a', '/repo/b', '/repo/a') returns true (the slice before the match ends "--exclude" , so -{1,2}[\w-]+\s+$ does not match), and this project's --defer --state/--target are added to a command whose project option is --exclude's value. The opposite case is too broad: dbt build --full-refresh --project-dir ../a is dropped and a valid command loses defer. Strip quotes/backslashes before the test, and drop only for value-taking options.
plugins/altimate-code/hooks/features/defer.test.ts 210 The new expectation passes through the existing \s--(?:directory|project)[\s=] check at defer.tsx:160 (the kept newline satisfies [\s=]), not the new backslash-newline clause, so the guard is unpinned. Use a continuation inside the option name (--pro, backslash, newline, ject-dir). Author agreed; test deferred.
plugins/altimate-code/hooks/features/defer.tsx 164 The $'/$"/backslash-newline guard runs before every folder and project check, so a line with nothing hidden loses defer: dbt run --select $'a b', and a command continued with \ plus a newline between arguments. Scope the guard to positions where a cd word or an option could be hidden. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 170 The background-& test runs on the raw line, so a & that is only text inside quotes refuses the whole line (dbt run --vars '{"url":"https://host/?a=1&b=2"}') though nothing is backgrounded. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 174 The leading cd chain strip accepts cd <word> [ \t]* && only, so a redirection between the word and && leaves the chain unstripped and the line refused: cd models 2>&1 && dbt run loses --defer --state, and defer.test.ts:184 was changed to drop the 2>&1 so nothing pins it. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 117 quoted() is a second quote scanner that diverges from the dbt-command.ts lexer (no $'…' rules, no # comments), so dbt build # don't; cd models is refused. The author cites the $' guard and the shared-file boundary; the comment/apostrophe shape is still handled by the duplicate scanner.
plugins/altimate-code/hooks/features/defer.tsx 160 The \s-C test refuses the whole line for any -C, so dbt build 2>&1 | grep -C 3 error, git -C sub status && dbt build and tar -C dir … && dbt run lose --defer --state; only a launcher's own -C needs the guard. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 165 The control-flow test matches keyword-shaped arguments and is position-blind: cd models && dbt run && echo "done" and dbt run -s done set control and lose --defer --state. Anchor the keywords at command position. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 210 The "cd that may not run" lead check runs for every cd/pushd, including ones after the first dbt invocation, so dbt build && cd target && tail -f logs/dbt.log returns false and dbt build loses defer. Scope it to match.index < first.start. Author declined as fail-safe.
plugins/altimate-code/hooks/features/defer.tsx 43 RewriteOptions.defaultTarget (declared at line 34, filled by effective() at line 251) is never read by the rewrite, while defer.test.ts still passes defaultTarget: 'dev' as if it mattered. The author keeps the field because state.defaultTarget feeds statusText, but the RewriteOptions copy is still dead. Remove it (and the test parameters) or restore the comparison.
plugins/altimate-code/hooks/features/defer.tsx 55 if (one.dynamic) continue drops defer for the whole invocation, so dbt run -s "$MODEL" and dbt run --profiles-dir ~/.dbt get no --defer --state. Author declined; the description's known limits mention folder/project options, not dynamic value words, so this silent case should be listed.
plugins/altimate-code/hooks/features/defer.tsx 98 Two dbt projects directly under the session root leave projectDir null, so no command is rewritten and /target answers "No dbt project found" for the whole session. Not listed under known limits.
Files Reviewed (2 files)
  • plugins/altimate-code/hooks/features/defer.test.ts - 1 new finding (line 270), 1 carried (line 210)
  • plugins/altimate-code/hooks/features/defer.tsx - 12 carried findings (lines 43, 55, 98, 117, 160, 164, 165, 170, 174, 177, 210, 226)

Scope note: the incremental diff 96c49fb..010db64 is one commit (1 changed line) that only completes the fake fs.list entries' type. Production code is unchanged since the last review, so the carried findings were re-checked against current HEAD rather than re-analyzed. No tests were run (read-only review).

Previous review (commit 96c49fb)

Status: 13 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 13
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.tsx 177 NEW: the ;/||/newline test reads the raw remainder, so a trailing newline (cd models && dbt run with a final newline), a trailing ;, and quoted punctuation in an argument (--vars '{"sep":";"}') all refuse the whole line and lose --defer --state, though nothing after the separator runs or it is only quoted text. Test the unquoted text and ignore a trailing terminator with nothing after it.
plugins/altimate-code/hooks/features/defer.tsx 164 NEW: the $'/$"/backslash-newline guard runs before every folder and project check, so dbt run --select $'a b' and a dbt command continued with a trailing backslash return false with nothing hidden, and lose defer. Scope the guard to positions where a cd word or an option could be hidden.
plugins/altimate-code/hooks/features/defer.tsx 226 NEW: the "another option's value" filter reads raw text, so dbt run "--exclude" --project-dir=/repo/a (the same shell words the new test refuses) bypasses it and is judged this project — a wrong-project rewrite; and any option word before a real --project-dir (dbt build --full-refresh --project-dir ../a) drops the match and refuses a valid command. Strip quotes/backslashes as plain does, and drop only for value-taking options.
plugins/altimate-code/hooks/features/defer.test.ts 210 NEW: this expectation passes through the existing \s--(?:directory|project)[\s=] check at defer.tsx:160 (the kept newline satisfies [\s=]), not the new backslash-newline clause, so the new guard is unpinned. Use a continuation inside the option name (--pro, backslash, newline, ject-dir).
plugins/altimate-code/hooks/features/defer.tsx 170 Carried: the background-& test runs on the raw line, so a & that is only text inside quotes refuses the whole line (dbt run --vars '{"url":"https://host/?a=1&b=2"}'), though nothing is backgrounded. Strip quoted spans before the test.
plugins/altimate-code/hooks/features/defer.tsx 174 Carried: the leading cd chain strip accepts cd <word> [ \t]* && only, so a redirection between the word and && leaves the chain unstripped and the line refused: cd models 2>&1 && dbt run loses --defer --state. defer.test.ts:184 was changed to drop the 2>&1, so that case is no longer pinned.
plugins/altimate-code/hooks/features/defer.tsx 117 Carried: quoted() is a second quote scanner that diverges from the dbt-command.ts lexer (no $'…' rules, no # comments), so cd ../b; echo $'don\'t; cd ../a'; dbt run is misjudged and dbt build # don't; cd models loses defer. Reuse the lexer's rules.
plugins/altimate-code/hooks/features/defer.tsx 160 Carried: the \s-C test refuses the whole line for any -C, so dbt build 2>&1 | grep -C 3 error, git -C sub status && dbt build and tar -C dir … && dbt run lose --defer --state/--target; only a launcher's own -C needs the guard.
plugins/altimate-code/hooks/features/defer.tsx 165 Carried: the control-flow test matches keyword-shaped arguments, so cd models && dbt run && echo "done" and dbt run -s done set control and lose --defer --state; it is also position-blind (a construct after the dbt word clears the line). Anchor the keywords at command position.
plugins/altimate-code/hooks/features/defer.tsx 210 Carried: the "cd that may not run" lead check runs for every cd/pushd, including ones after the first dbt invocation, so dbt build && cd target && tail -f logs/dbt.log returns false and dbt build loses --defer --state. Scope it to match.index < first.start.
plugins/altimate-code/hooks/features/defer.tsx 43 Carried: RewriteOptions.defaultTarget (declared at line 34, filled by effective() at line 251) is never read, while defer.test.ts still passes defaultTarget: 'dev' as if it mattered. Remove the dead field and effective() entry (and the test parameters) or restore the comparison.
plugins/altimate-code/hooks/features/defer.tsx 55 Carried (author declined; still not in the description's known limits): if (one.dynamic) continue drops defer for the whole invocation, so dbt run -s "$MODEL" and dbt run --profiles-dir ~/.dbt get no --defer --state. At minimum list it under known limits.
plugins/altimate-code/hooks/features/defer.tsx 98 Carried (author declined; description still lacks it): two dbt projects directly under the session root leave projectDir null, so no command is rewritten and /target answers "No dbt project found" for the whole session.
Files Reviewed (2 files)
  • plugins/altimate-code/hooks/features/defer.tsx - 3 new findings (lines 177, 164, 226), 9 carried (lines 170, 174, 117, 160, 165, 210, 43, 55, 98)
  • plugins/altimate-code/hooks/features/defer.test.ts - 1 new finding (line 210); the other five new expectations trace correctly against current code

Scope note: the incremental diff ab07f32..96c49f is one commit (15 changed lines) touching defer.tsx and defer.test.ts. The three new guards can only refuse (never wrongly vouch) except the raw-text --project-dir filter at line 226, which is covered above. No tests were run (read-only review); the changed branches were traced by hand against the shell's quote, continuation and separator rules.

Previous review (commit ab07f32)

Status: 9 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 9
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.tsx 168 NEW: the background-& test runs on 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"}' (and any argument or # comment holding &) loses --defer --state and the session --target, though nothing is backgrounded. &&, >&, &> and 2>&1 are stripped, but quoted & is not; plain does not help (it removes quotes, not their contents). Strip quoted spans (single and double, honouring escapes) before the test so only a real operator remains.
plugins/altimate-code/hooks/features/defer.tsx 172 Carried: the leading cd chain strip accepts cd <word> [ \t]* && only, so a redirection between the word and && leaves the chain unstripped and the line refused: cd models 2>&1 && dbt run and cd models >/dev/null && dbt run lose --defer --state and the session --target, though the cd is first in the line and && guarantees it ran. defer.test.ts:184 was changed to drop the 2>&1, so the previously covered case is no longer pinned. Accept redirections inside the chain (the \d*>&\d*-?|\&>>?|\d*[<>]+ sweep at line 208 covers the forms).
plugins/altimate-code/hooks/features/defer.tsx 117 Carried: quoted() is a second quote scanner that diverges from the lexer in dbt-command.ts (no $'…' rules, no # comments), so cd ../b; echo $'don\'t; cd ../a'; dbt run still passes as the wrong project and dbt build # don't; cd models loses defer. It also backs the new --project-dir filter at line 222; reuse the lexer's rules.
plugins/altimate-code/hooks/features/defer.tsx 160 Carried: the \s-C test refuses the whole line for any -C, so dbt build 2>&1 | grep -C 3 error, git -C sub status && dbt build and tar -C dir … && dbt run lose --defer --state/--target; only a launcher's own -C (poetry run -C ../b dbt run) needs the guard.
plugins/altimate-code/hooks/features/defer.tsx 163 Carried: the control-flow test matches keyword-shaped arguments, so cd models && dbt run && echo "done" and dbt run -s done set control and lose --defer --state; it is also position-blind (a construct after the dbt word clears the line). Anchor the keywords at command position.
plugins/altimate-code/hooks/features/defer.tsx 206 Carried: the "cd that may not run" lead check runs for every cd/pushd, including ones after the first dbt invocation, so dbt build && cd target && tail -f logs/dbt.log returns false and dbt build loses --defer --state. Scope both this and the leading-chain check to match.index < first.start.
plugins/altimate-code/hooks/features/defer.tsx 43 Carried: RewriteOptions.defaultTarget (declared at line 34, filled by effective() at line 247) is never read — rewriteDeferCommand no longer compares against it, while defer.test.ts still passes defaultTarget: 'dev' as if it mattered and the description says the flag is added only when it differs. Remove the dead field and effective() entry (and the test parameters) or restore the comparison.
plugins/altimate-code/hooks/features/defer.tsx 55 Carried (author declined; still not in the description's known limits): if (one.dynamic) continue drops defer for the whole invocation, so dbt run -s "$MODEL" and dbt run --profiles-dir ~/.dbt get no --defer --state. At minimum list it under known limits.
plugins/altimate-code/hooks/features/defer.tsx 98 Carried (author declined; description still lacks it): two dbt projects directly under the session root leave projectDir null, so no command is rewritten and /target answers "No dbt project found" for the whole session.
Files Reviewed (2 files in the incremental diff)
  • plugins/altimate-code/hooks/features/defer.tsx - 1 new finding (line 168), 8 carried findings (lines 172, 117, 160, 163, 206, 43, 55, 98); the rest of this commit traced sound: the ownsProject loop now breaks when dirname stops moving (the root-project hang is real and fixed, pinned at defer.test.ts:201-202), pushd +1 / cd - are correctly unknown, the named filter only removes matches so it can only refuse (never wrongly vouch), and the new background-& check correctly drops &&, >&, &> and 2>&1 so only a real operator refuses.
  • plugins/altimate-code/hooks/features/defer.test.ts - the five new expectations trace correctly against current code; no new finding.

Scope note: the incremental diff bd87e34..ab07f32 is one commit touching defer.tsx and defer.test.ts; gh pr diff 28 is the same two files plus types/index.d.ts (unchanged). No tests were run (read-only review); the changed branches were traced by hand against the lexer, the CD/PROJECT_DIR patterns and the shell parsing rules.

Previous review (commit bd87e34)

Status: 8 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 8
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.tsx 168 NEW: the leading cd chain strip accepts cd <word> [ \t]* && only, so a redirection between the word and && leaves the chain unstripped and the line is refused: cd models 2>&1 && dbt run and cd models >/dev/null && dbt run lose --defer --state and the session --target, though the cd is first in the line and && guarantees it ran. defer.test.ts:184 was changed from cd models 2>&1 && dbt run | tee out to drop the 2>&1, so the previously covered case is now unpinned. Accept redirections inside the chain (the \d*>&\d*-?|&>>?|\d*[<>]+ sweep at line 199 covers the forms).
plugins/altimate-code/hooks/features/defer.tsx 117 Carried (active comment): quoted() is a second quote scanner that diverges from the lexer in dbt-command.ts (no $'…', no # rules), so cd ../b; echo $'don\'t; cd ../a'; dbt run still passes as the wrong project and dbt build # don't; cd models loses defer. This commit also makes it back the new --project-dir filter at line 212; reuse the lexer's rules.
plugins/altimate-code/hooks/features/defer.tsx 158 Carried (active comment): the \s-C test refuses the whole line for any -C, so dbt build 2>&1 | grep -C 3 error, git -C sub status && dbt build and tar -C dir … && dbt run lose --defer --state/--target; only a launcher's own -C (poetry run -C ../b dbt run) needs the guard.
plugins/altimate-code/hooks/features/defer.tsx 161 Carried (active comment): the control-flow test matches keyword-shaped arguments, so cd models && dbt run && echo "done" and dbt run -s done set control and lose --defer --state; it is also position-blind (a construct after the dbt word clears the line). Anchor the keywords at command position.
plugins/altimate-code/hooks/features/defer.tsx 197 Carried (active comment): the "cd that may not run" lead check runs for every cd/pushd, including ones after the first dbt invocation, so dbt build && cd target && tail -f logs/dbt.log returns false and dbt build loses --defer --state. The new leading-chain check at line 169 now refuses the same shapes first, so both checks must be scoped to match.index < first.start.
plugins/altimate-code/hooks/features/defer.tsx 34 Carried (active comment): RewriteOptions.defaultTarget (declared here, filled by effective() at line 237) is never read — rewriteDeferCommand no longer compares against it and defer.test.ts:139 now pins --target dev when it equals the default, while the PR description still says the flag is added only when it differs. Remove the dead field/effective() entry (and the test parameters) or restore the comparison.
plugins/altimate-code/hooks/features/defer.tsx 55 Carried (author declined; still not in the description's known limits): if (one.dynamic) continue drops defer for the whole invocation, so dbt run -s "$MODEL" and dbt run --profiles-dir ~/.dbt get no --defer --state. At minimum list it under known limits.
plugins/altimate-code/hooks/features/defer.tsx 98 Carried (author declined; description still lacks it): two dbt projects directly under the session root leave projectDir null, so no command is rewritten and /target answers "No dbt project found" for the whole session.
Files Reviewed (2 files in the incremental diff)
  • plugins/altimate-code/hooks/features/defer.tsx - 1 new finding (line 168), 6 carried current findings (lines 117, 158, 161, 197, 34, 55, 98); the rest of this commit traced sound: the new leading-chain strip drops cd a && cd b && before the cd test, and the other four new expectations match what the code does (line 192's quoted --project-dir is caught by the new quoted() filter, which can only remove a match and therefore only refuse, never wrongly vouch); the --project-dir filter is safe because every filtered match makes the raw count disagree with the plain count; /defer reset now uses started captured before ensure(), consistent with on|off and /target.
  • plugins/altimate-code/hooks/features/defer.test.ts - the new test block's five expectations trace correctly, but line 184 no longer pins a redirected leading cd (see defer.tsx:168).

Scope note: the incremental diff 985b610a..bd87e34 is one commit (bd87e34) touching defer.tsx and defer.test.ts; gh pr diff 28 is the same two files plus types/index.d.ts (unchanged). No tests were run (read-only review); the changed branches were traced by hand against the lexer's token/option tables and the regexes in runsInProject.

Fix these issues in Kilo Cloud

Previous review (commit 985b610)

Status: 7 Issues Found | Recommendation: Address before merge

Overview

Severity Count
CRITICAL 0
WARNING 0
SUGGESTION 7
Issue Details (click to expand)

SUGGESTION

File Line Issue
plugins/altimate-code/hooks/features/defer.tsx 117 NEW: quoted() is a second quote scanner that diverges from the lexer in dbt-command.ts (no $'…', no # rules), so cd ../b; echo $'don\'t; cd ../a'; dbt run still returns true and gets the wrong project's --defer --state, and dbt build # don't; cd models loses defer. Reuse the lexer's rules.
`plugins/altimate-code/hooks/f

[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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
if (/\s--(?:directory|project)[\s=]/.test(command) || /\s--(?:directory|project)[\s=]/.test(plain)) return false
if (/\s--(?:directory|project)[\s=]/.test(plain)) return false

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in f4ebfb1: runsInProject now tests only plain, which covers the quoted and unquoted forms.

@hkaltai

hkaltai commented Nov 15, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at 970e648

hkaltai and others added 2 commits November 17, 2026 06:20
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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Suggested change
const root = await projectRoot($, file, { cliOnly: true }).catch(() => null)
const root = await projectRoot($, file, true).catch(() => null)

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d8085a4: one import from ./altimate-cli.

hkaltai and others added 3 commits November 17, 2026 07:38
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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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))

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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'])

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
const COMMAND_KEYWORDS = new Set(['!', '{', 'then', 'do', 'else', 'elif', 'if', 'while', 'until', 'time'])
const COMMAND_KEYWORDS = KEYWORDS

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 9fffbde: COMMAND_KEYWORDS now reuses KEYWORDS.

hkaltai and others added 3 commits November 17, 2026 07:54
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>
@hkaltai

hkaltai commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

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 --target/$FLAGS no longer gets flags injected), and a --project-dir "."/../b word no longer passes the project check. Both re-gated by fresh reviewer processes and approved. Not changed here: the plugin.json settings without a consumer yet (cost/health) come from the foundation branch, and the stub features are its scaffolding.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

hkaltai and others added 2 commits November 17, 2026 09:52
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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:

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

hkaltai and others added 4 commits November 17, 2026 14:28
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>
@hkaltai

hkaltai commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at 2eb09ef (reviewers: gpt-6-astra high, gpt-6.1-sol high)

hkaltai and others added 2 commits November 17, 2026 21:10
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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
const PROJECT_DIR = /(?:--project-dir[\s=]|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g
const PROJECT_DIR = /(?:--project-dir[\s=]+|\bDBT_PROJECT_DIR=)("[^"]+"|'[^']+'|[^\s;&|)]+)/g

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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:

Suggested change
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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 {

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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 run therefore treats the cd ../a inside the string as a real folder change, sets before to /repo/a, and returns true, so the rewrite adds /repo/a's --defer --state to a dbt run that 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 models now 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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]*)*/, '')

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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/a is 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 --state and --target are then added to a command whose --project-dir is only --exclude's value. Applying the same quote and backslash removal plain uses 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 ../a has 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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hkaltai

hkaltai commented Nov 17, 2026

Copy link
Copy Markdown
Contributor Author

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 }] : [] }))

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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>
@hkaltai

hkaltai commented Nov 18, 2026

Copy link
Copy Markdown
Contributor Author

review-loop: APPROVED at 7eef6d9 (reviewers: gpt-6-astra high, gpt-6.1-sol high)

@saravmajestic saravmajestic left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@hkaltai
hkaltai merged commit 9e43a74 into main Nov 18, 2026
4 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants