feat(agent): add dbt-optimizer agent — 6-lane dbt project optimization with evals - #1092
Open
anandgupta42 wants to merge 19 commits into
Open
feat(agent): add dbt-optimizer agent — 6-lane dbt project optimization with evals#1092anandgupta42 wants to merge 19 commits into
anandgupta42 wants to merge 19 commits into
Conversation
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Issue for this PR
Closes #1091
Type of change
What does this PR do?
Adds
dbt-optimizer, a 5th native primary agent that scans a dbt project for fixable issues and proposes targeted fixes with cost/impact reporting (the agent behind the planned Optimize workflow). Four parts:1. Agent registration (
agent.ts). Deny-by-default permission allowlist: read/analysis/finops tools allowed,editandbashprompt per action,sql_execute_writedenied. The deny is re-applied after the global user-config merge AND after the per-agent config merge — permission evaluation is last-match-wins, so without the second re-applicationagent."dbt-optimizer".permission.sql_execute_write: "allow"would have silently won (regression tests cover both paths). Nameddbt-optimizerrather thanoptimizerbecause more optimizer agents are planned; no alias shim needed since nothing shipped under the old name.2. Prompt (
prompts/dbt-optimizer.txt). Encodes the taxonomy fromdocs/internal/2026-08-12-dbt-optimization-taxonomy-research.md: 6 detection lanes, an evidence-attribution ladder (invocation-ID/query-tag down to lineage-match, with confidence labeling), ROI-ranked triage, cost-honesty rules ("not estimable" is a valid answer; never invent dollar figures), a 4-phase loop that stops after scan for candidate selection, and an auto-fix vs propose-only boundary. Builder's self-review gains a dbt-scoped "Optimization handoff" nudge — primary agents are excluded from the task tool (task.tsfiltersmode !== "primary"), so the nudge is the only build-time bridge and auto-delegation of cost-incurring scans is deliberately NOT wired.3. Verification-tool fixes. Three latent bugs in existing tools the agent's core promises depend on, found during review: the rewrite verify gate trusted
equivalent: trueeven when the engine saiddecidable: false(now UNDECIDABLE = unproven, everywhere it surfaces);sql_explain analyze:trueexecutes the statement on Postgres/MySQL/DuckDB/Trino and had no statement-class guard (now blocked for anything non-read-only, includingSELECT ... INTO); thesql_diffwrapper read response fields the native handler never returns, so every comparison reported "identical".4. Evals. Tier 1 (CI): 20 deterministic tests asserting the prompt's non-negotiable invariants (whitespace-normalized so reflow doesn't break them) plus an evidence-chain suite proving each planted fixture issue is genuinely detectable. Tier 2 (opt-in): a live eval that runs the compiled binary against a 7-model DuckDB fixture with 6 planted issues (incremental candidate, dead model, SELECT * propagation, ORDER BY, verbatim-duplicated CTE ×3, untested model) and grades deterministically — ≥4/6 recall with directional signal phrases, exit-code check, and a tree-snapshot proving the scan modified/removed/added nothing. Answer key lives outside the scanned directory.
How did you verify your code works?
tsgo --noEmitclean; upstream marker check clean (--markers --base main --strict); oxlint 0 errors on changed files.Screenshots / recordings
Not a UI change — the agent appears in the existing Tab ring/agent list.
Checklist
🤖 Generated with Claude Code
Summary by cubic
Adds the
dbt-optimizeragent for six‑lane dbt project scans with evidence‑backed fixes, and strengthens SQL, path, and permission safety. Previously, EXPLAIN ANALYZE and equivalence gates could execute or misclassify writes, built‑ins could bypass deny‑by‑default exposure, session/persisted approvals could override denies, and path‑taking tools could read outside the project; now analyze requires write approval with a safe fallback, UNDECIDABLE never counts as equivalent, denied tools are not exposed, approvals cannot flip a deny, and out‑of‑project reads are gated.Agent and permissions: registers
dbt-optimizerwith deny‑by‑default;edit/bashask;sql_execute_writeis non‑overridable and re‑applied after config merges. Built‑in tool exposure honors denies viaPermission.disabled(internalinvalidexempt). Persisted “always allow” approvals and session‑supplied rules can no longer override configured denies (session rules merge before agent at ask time).SQL/paths/analysis:
sql_explainanalyze mode requires write approval and uses a single‑pass masker for literals/comments/delimited identifiers (incl. bracket/dollar quoting and subscript cases); unsafe SQL falls back to estimated plans.sql_classifyshares the masker, normalizes CR/CRLF, detects quoted side‑effect calls (including identifier‑quoted), and rejects write keywords hidden inside read‑shaped WITH/EXPLAIN/SELECT; statement‑form checks anchor at start.sql_diffuses LCS line diffs withcontext_linesand robust hunking, forwardsschema_context/dialect, and reportsequivalence_assessed/decidable; undecidable results never count as proven equivalent. All dbt readers andschema_pathwrappers gate throughexternal_directory, resolve paths relative to the project, read the same resolved path, and propagate permission rejections. Impact analysis is a true multi‑seed BFS by dbtunique_id(shortest depths, no self‑loops); affected tests counted byunique_id. Prompt encodes six lanes and build safety with a builder handoff nudge; deterministic prompt/evidence tests ship, plus an opt‑in DuckDB live eval with same‑candidate scoring. Docs surfacereviewer/dbt-optimizeragents.Written for commit 81ec904. Summary will update on new commits.
Summary by CodeRabbit
New Features
dbt-optimizeragent for evidence-based analysis and approval-gated fixes.Bug Fixes
Documentation
Note
High Risk
Changes touch permission evaluation, warehouse SQL execution paths (EXPLAIN ANALYZE and write classification), and a new agent that can propose edits and approved shell/dbt builds—mistakes could allow unintended writes or bypass user denials.
Overview
Introduces the
dbt-optimizerprimary agent: a deny-by-default allowlist for scan/analysis/finops tools, approval-gatededit/bash, and a non-overridablesql_execute_writedeny (re-applied after global and per-agent config merges). A new prompt defines a four-phase loop (scan → fix → impact → PR) across six optimization lanes with cost-honesty rules; docs andbuilderself-review now nudge users to switch agents instead of silent out-of-scope fixes.SQL and verification behavior is tightened: a lexer-based
maskLiteralsAndCommentsbacks safer write classification (side-effect functions, read-shaped writes) andsql_explainblocks or permission-gatesanalyze:trueso executing plans cannot bypass warehouse-write controls.sql_diff/ equivalence tooling now match the native handler (LCS diffs,equivalence_assessed/decidable) and treat undecidable results as unproven across rewrite/equivalence surfaces.Path and session safety: dbt manifest/lineage/parse tools and
schema_patharguments go throughexternal_directorygating with project-relative resolution;schema_indexand training mutations prompt explicitly. Permission evaluation no longer lets stored “always allow” approvals override configured deny rules (protecting optimizer/reviewer write denials after agent switches).impact_analysisdownstream traversal is improved (multi-seed BFS byunique_id, clearer column-impact caveats).Reviewed by Cursor Bugbot for commit 81ec904. Bugbot is set up for automated code reviews on this repo. Configure here.