Skip to content

Implement dbt-tools#26

Merged
yu-iskw merged 13 commits intomainfrom
dbt-tools
Mar 13, 2026
Merged

Implement dbt-tools#26
yu-iskw merged 13 commits intomainfrom
dbt-tools

Conversation

@yu-iskw
Copy link
Owner

@yu-iskw yu-iskw commented Mar 12, 2026

No description provided.

yu-iskw added 4 commits March 10, 2026 13:36
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
@github-advanced-security
Copy link

You are seeing this message because GitHub Code Scanning has recently been set up for this repository, or this pull request contains the workflow file for the Code Scanning tool.

What Enabling Code Scanning Means:

  • The 'Security' tab will display more code scanning analysis results (e.g., for the default branch).
  • Depending on your configuration and choice of analysis tool, future pull requests will be annotated with code scanning analysis results.
  • You will be able to see the analysis results for the pull request's branch on this overview once the scans have completed and the checks have passed.

For more information about GitHub Code Scanning, check out the documentation.

yu-iskw added 3 commits March 12, 2026 14:20
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
@yu-iskw yu-iskw marked this pull request as ready for review March 12, 2026 05:32
@qodo-code-review
Copy link

Review Summary by Qodo

Implement dbt-tools: Complete CLI and analysis library for dbt artifact processing

✨ Enhancement 🧪 Tests 📝 Documentation

Grey Divider

Walkthroughs

Description
• Implements comprehensive dbt-tools package suite with CLI and core analysis libraries for dbt
  artifact processing
• **Core Analysis**: ManifestGraph class transforms dbt manifests into directed graphs with
  dependency traversal, cycle detection, and topological sorting
• **Execution Analysis**: ExecutionAnalyzer processes run_results.json to calculate critical paths
  and generate Gantt chart data for visualization
• **Dependency Service**: Provides upstream/downstream dependency analysis with flat/tree output
  formats, field filtering, and depth limiting
• **CLI Commands**: Five main commands (analyze, graph, run-report, deps, schema) with
  JSON/DOT/GEXF export formats and tree-based visualization
• **Security & Validation**: Input validation prevents path traversal and injection attacks; field
  filtering includes prototype pollution protection
• **Output Formatting**: Human-readable and JSON output modes with TTY detection and tree-based
  ASCII visualization for dependencies
• **Comprehensive Testing**: 13+ test suites covering manifest graph, execution analysis, dependency
  service, CLI integration, and security validation
• **Documentation**: CLI user guide, agent context guide, ADRs for architectural decisions
  (Graphology, topological sort, npm scoping), and skill definitions
• **Infrastructure**: CodeQL security analysis workflow, ESLint configuration with quality plugins,
  version bump and ADR management skills
Diagram
flowchart LR
  A["dbt Artifacts<br/>manifest.json<br/>run_results.json"] -->|Load| B["ArtifactLoader"]
  B -->|Parse| C["ManifestGraph"]
  C -->|Build Graph| D["Graphology<br/>DAG"]
  D -->|Analyze| E["DependencyService"]
  D -->|Analyze| F["ExecutionAnalyzer"]
  E -->|Format| G["OutputFormatter"]
  F -->|Format| G
  G -->|Display| H["CLI Commands<br/>analyze, graph,<br/>deps, run-report"]
  I["InputValidator"] -->|Validate| H
  J["FieldFilter"] -->|Filter| G
Loading

Grey Divider

File Changes

1. packages/dbt-tools/core/src/analysis/manifest-graph.test.ts 🧪 Tests +544/-0

ManifestGraph test suite with version and dependency validation

• Comprehensive test suite for ManifestGraph class covering version validation, graph building,
 and dependency traversal
• Tests validate manifest schema versions (v10, v11, v12) and reject unsupported versions with
 appropriate error messages
• Tests verify graph construction including node and edge creation from manifest data
• Tests cover upstream/downstream dependency queries with optional depth limiting and parent
 tracking

packages/dbt-tools/core/src/analysis/manifest-graph.test.ts


2. packages/dbt-tools/core/src/analysis/manifest-graph.ts ✨ Enhancement +582/-0

Core manifest graph construction and dependency analysis

• Implements ManifestGraph class that transforms dbt manifests into a directed graph using
 graphology library
• Builds graph from manifest nodes (models, sources, macros, exposures, metrics, semantic models,
 unit tests)
• Provides methods for graph traversal: getUpstream(), getDownstream(),
 getUpstreamWithParents(), getDownstreamWithParents()
• Includes cycle detection, topological sorting, and summary statistics generation

packages/dbt-tools/core/src/analysis/manifest-graph.ts


3. packages/dbt-tools/cli/src/cli.ts ✨ Enhancement +482/-0

Command-line interface for dbt artifact analysis

• Implements CLI entry point with five main commands: analyze, graph, run-report, deps, and
 schemaanalyze command provides project structure summary; graph exports dependency graph in
 JSON/DOT/GEXF formats
• run-report generates execution reports from run_results.json with optional critical path
 analysis
• deps command retrieves upstream/downstream dependencies with filtering, depth limiting, and
 tree/flat output formats

packages/dbt-tools/cli/src/cli.ts


View more (52)
4. packages/dbt-tools/core/src/formatting/output-formatter.test.ts 🧪 Tests +315/-0

Output formatting and display logic tests

• Test suite for output formatting functions covering TTY detection and JSON/human-readable output
 selection
• Tests validate formatting of analyze, deps, and run-report command outputs
• Tests verify tree-based dependency visualization with proper indentation and depth indicators
• Tests ensure critical path information is included in run reports when available

packages/dbt-tools/core/src/formatting/output-formatter.test.ts


5. packages/dbt-tools/core/src/analysis/execution-analyzer.test.ts 🧪 Tests +266/-0

Execution analysis and critical path detection tests

• Test suite for ExecutionAnalyzer class that processes run_results.json and correlates with
 dependency graph
• Tests validate extraction of node execution information including status and timing data
• Tests verify critical path calculation and Gantt chart data generation for visualization
• Tests handle edge cases like missing timestamps and non-existent nodes

packages/dbt-tools/core/src/analysis/execution-analyzer.test.ts


6. packages/dbt-tools/core/src/analysis/dependency-service.test.ts 🧪 Tests +274/-0

Dependency service retrieval and formatting tests

• Test suite for DependencyService covering upstream/downstream dependency retrieval
• Tests validate flat and tree-structured output formats with field filtering and depth limiting
• Tests verify consistency between flat and tree formats and proper parent-child edge relationships
• Tests ensure dependency counts match across different output formats

packages/dbt-tools/core/src/analysis/dependency-service.test.ts


7. packages/dbt-tools/core/src/analysis/execution-analyzer.ts ✨ Enhancement +274/-0

Execution timing analysis and critical path computation

• Implements ExecutionAnalyzer class for processing run_results.json and extracting timing
 information
• Provides methods for calculating critical path (longest execution path through dependency graph)
• Generates Gantt chart data with relative timestamps for execution visualization
• Correlates execution results with manifest graph for comprehensive analysis

packages/dbt-tools/core/src/analysis/execution-analyzer.ts


8. packages/dbt-tools/core/src/introspection/schema-generator.ts ✨ Enhancement +258/-0

Command schema definitions for CLI introspection

• Implements schema generation for CLI command introspection with CommandSchema interface
• Provides schemas for all five commands: analyze, graph, run-report, deps, and schema
• Includes argument and option definitions with types, defaults, and descriptions
• Exports getCommandSchema() and getAllSchemas() functions for runtime schema access

packages/dbt-tools/core/src/introspection/schema-generator.ts


9. packages/dbt-tools/core/src/validation/input-validator.test.ts 🧪 Tests +197/-0

Input validation and security testing

• Test suite for input validation functions covering path safety, resource ID validation, and
 control character detection
• Tests validate rejection of path traversal attempts and pre-encoded malicious patterns
• Tests verify control character filtering while allowing newlines, tabs, and carriage returns
• Tests ensure proper handling of empty strings and non-string inputs

packages/dbt-tools/core/src/validation/input-validator.test.ts


10. packages/dbt-tools/core/src/formatting/output-formatter.ts ✨ Enhancement +215/-0

Output formatting and human-readable display logic

• Implements output formatting functions for human-readable and JSON output modes
• Provides formatAnalyze(), formatDeps(), and formatRunReport() for command-specific
 formatting
• Implements tree-based visualization for dependencies with ASCII art connectors and depth
 indicators
• Includes TTY detection and output mode selection logic

packages/dbt-tools/core/src/formatting/output-formatter.ts


11. packages/dbt-tools/core/src/version.test.ts 🧪 Tests +154/-0

Manifest version detection and validation tests

• Test suite for version detection and validation functions
• Tests validate extraction of manifest schema versions (v10, v11, v12) and dbt versions
• Tests verify support status checking with minimum version requirements
• Tests ensure proper handling of missing or malformed version metadata

packages/dbt-tools/core/src/version.test.ts


12. packages/dbt-tools/core/src/types.ts ✨ Enhancement +58/-0

Core type definitions for dbt tools

• Defines TypeScript types and interfaces for dbt resource types and graph structures
• Exports DbtResourceType union type covering all dbt artifact types (models, sources, tests,
 etc.)
• Defines GraphNodeAttributes and GraphEdgeAttributes interfaces for graph data storage
• Exports GraphSummary and VersionInfo interfaces for analysis results

packages/dbt-tools/core/src/types.ts


13. packages/dbt-tools/core/src/analysis/dependency-service.ts ✨ Enhancement +196/-0

Dependency analysis service with filtering and tree formats

• Implements DependencyService class for analyzing upstream/downstream dependencies with optional
 field filtering and depth limiting
• Provides both flat and tree output formats for dependency results
• Supports topological build order for upstream dependencies via getUpstreamBuildOrder()
• Includes nested tree building with parent tracking for hierarchical dependency visualization

packages/dbt-tools/core/src/analysis/dependency-service.ts


14. packages/dbt-artifacts-parser/src/test-utils.ts 🧪 Tests +173/-0

Test utilities for artifact loading and resource resolution

• Exports utility functions for loading test artifacts (manifest, run_results, sources, catalog)
• Provides getTestResourcePath() for flexible resource location resolution
• Handles version normalization and supports both test and resources directories
• Includes fallback logic for __dirname resolution in different execution contexts

packages/dbt-artifacts-parser/src/test-utils.ts


15. packages/dbt-tools/core/src/formatting/field-filter.test.ts 🧪 Tests +138/-0

Field filter unit tests with security validation

• Comprehensive test suite for FieldFilter class with 13 test cases
• Tests simple and nested field filtering, array filtering, and edge cases
• Includes security tests for prototype pollution prevention
• Validates whitespace trimming and non-object data handling

packages/dbt-tools/core/src/formatting/field-filter.test.ts


16. packages/dbt-tools/core/src/io/artifact-loader.test.ts 🧪 Tests +134/-0

Artifact loader integration tests

• Tests for artifact loading functions (loadManifest, loadRunResults)
• Validates path resolution with environment variables and custom directories
• Tests error handling for missing files and invalid JSON
• Uses temporary directories for isolated test execution

packages/dbt-tools/core/src/io/artifact-loader.test.ts


17. packages/dbt-tools/core/src/introspection/schema-generator.test.ts 🧪 Tests +118/-0

Command schema generator unit tests

• Tests command schema generation and retrieval functions
• Validates schema structure for all commands (analyze, deps, graph, run-report, schema)
• Tests argument and option structure validation
• Verifies enum values and default values for command options

packages/dbt-tools/core/src/introspection/schema-generator.test.ts


18. packages/dbt-tools/cli/src/cli.test.ts 🧪 Tests +111/-0

CLI integration tests with schema validation

• Integration tests for CLI core functionality and command schemas
• Tests input validation functions and output formatting
• Validates schema availability for all commands
• Tests deps command schema structure and options

packages/dbt-tools/cli/src/cli.test.ts


19. packages/dbt-tools/core/src/io/artifact-loader.ts ✨ Enhancement +119/-0

Artifact loading with path resolution and parsing

• Implements artifact loading and path resolution for manifest and run_results files
• Provides resolveArtifactPaths() with support for environment variables and custom directories
• Includes loadManifest() and loadRunResults() with JSON parsing and error handling
• Defaults to ./target directory following dbt conventions

packages/dbt-tools/core/src/io/artifact-loader.ts


20. packages/dbt-tools/core/src/validation/input-validator.ts Error handling +114/-0

Input validation with security hardening

• Implements input validation functions for security hardening
• Validates resource IDs, paths, and general strings against injection attacks
• Prevents path traversal (../), control characters, and URL encoding exploits
• Provides specific validators for different input types

packages/dbt-tools/core/src/validation/input-validator.ts


21. packages/dbt-tools/core/src/formatting/field-filter.ts ✨ Enhancement +132/-0

Field filtering with nested path support

• Implements FieldFilter class for selective field extraction from objects and arrays
• Supports nested field paths using dot notation
• Includes prototype pollution protection in setNestedValue()
• Provides filterFields() and filterArrayFields() static methods

packages/dbt-tools/core/src/formatting/field-filter.ts


22. packages/dbt-tools/core/src/errors/error-handler.test.ts 🧪 Tests +78/-0

Error handler unit tests

• Tests error formatting for both TTY and non-TTY environments
• Validates error code assignment based on error type
• Tests validation error creation with optional field details
• Verifies structured error format for JSON output

packages/dbt-tools/core/src/errors/error-handler.test.ts


23. packages/dbt-tools/core/src/version.ts ✨ Enhancement +68/-0

Version checking and extraction utilities

• Extracts and validates manifest schema version from dbt artifacts
• Provides version checking against minimum supported version (v10)
• Includes getVersionInfo() for comprehensive version information
• Supports dbt version extraction from manifest metadata

packages/dbt-tools/core/src/version.ts


24. packages/dbt-tools/core/src/errors/error-handler.ts Error handling +72/-0

Structured error handling and formatting

• Implements structured error formatting for JSON and human-readable output
• Provides createValidationError() for field-specific validation errors
• Includes error code mapping based on error message patterns
• Supports TTY detection for appropriate output formatting

packages/dbt-tools/core/src/errors/error-handler.ts


25. packages/dbt-tools/core/src/index.ts ✨ Enhancement +24/-0

Core package public API exports

• Central export file for @dbt-tools/core package
• Exports analysis, I/O, validation, formatting, error handling, and introspection modules
• Provides unified API surface for package consumers

packages/dbt-tools/core/src/index.ts


26. .claude/skills/manage-adr/scripts/create-adr.sh Miscellaneous +15/-0

ADR creation automation script

• Bash script for non-interactive ADR creation
• Sets VISUAL=true to prevent editor opening
• Returns created ADR filename to stdout
• Includes error handling for adr-tools availability

.claude/skills/manage-adr/scripts/create-adr.sh


27. packages/dbt-tools/cli/README.md 📝 Documentation +243/-0

CLI user documentation and command reference

• Comprehensive CLI documentation with command reference and examples
• Documents all commands: analyze, graph, run-report, deps, schema
• Includes field filtering, input validation, and JSON output behavior
• Provides agent usage guidance and environment variable documentation

packages/dbt-tools/cli/README.md


28. .claude/skills/manage-adr/references/mermaid-diagrams.md 📝 Documentation +251/-0

Mermaid diagram guide for architecture documentation

• Guide for using Mermaid diagrams in ADRs with examples
• Covers system architecture, software architecture, sequence, and state diagrams
• Provides templates and best practices for diagram usage
• Includes rendering information and diagram type reference

.claude/skills/manage-adr/references/mermaid-diagrams.md


29. .claude/skills/manage-adr/SKILL.md 📝 Documentation +154/-0

ADR management skill and workflow documentation

• Skill definition for managing Architecture Decision Records
• Documents ADR creation, linking, and listing procedures
• Provides decision significance criteria and ADR vs design doc guidance
• Includes Mermaid diagram integration instructions

.claude/skills/manage-adr/SKILL.md


30. packages/dbt-tools/cli/CONTEXT.md 📝 Documentation +199/-0

Agent context guide for CLI usage

• Agent context guide for dbt-tools CLI usage
• Documents default artifact locations and JSON output behavior
• Provides field filtering patterns and input validation guidance
• Includes common patterns and best practices for agent consumption

packages/dbt-tools/cli/CONTEXT.md


31. .claude/skills/version-bump/SKILL.md 📝 Documentation +72/-0

Version bump skill documentation

• Skill definition for interactive version bumping
• Documents semantic versioning increment logic (patch, minor, major)
• Specifies files to update in monorepo structure
• Includes version calculation and example workflow

.claude/skills/version-bump/SKILL.md


32. eslint.config.mjs ⚙️ Configuration changes +85/-0

ESLint configuration with quality plugins

• ESLint configuration with TypeScript, SonarJS, and eslint-for-ai plugins
• Configures complexity rules and code quality checks
• Ignores test files, dist, and resources directories
• Includes project-specific tsconfig paths for monorepo

eslint.config.mjs


33. docs/adr/0004-use-topological-sort-for-upstream-build-order.md 📝 Documentation +70/-0

ADR for topological sort build order implementation

• ADR documenting decision to use topological sort for build order analysis
• Explains alternatives considered and rationale for graphology-dag
• Includes Mermaid diagram showing process flow
• Documents consequences and mitigation strategies

docs/adr/0004-use-topological-sort-for-upstream-build-order.md


34. package.json ⚙️ Configuration changes +8/-1

Root package configuration with CodeQL and lint reporting

• Adds CodeQL analysis scripts (codeql, codeql:db, codeql:analyze)
• Adds lint:report script for structured ESLint feedback
• Adds eslint-for-ai and eslint-plugin-sonarjs dependencies
• Adds lodash override for security

package.json


35. .claude/skills/manage-adr/references/adr-granularity.md 📝 Documentation +52/-0

ADR granularity and scope guidance

• Guide for determining ADR granularity (why vs how)
• Provides examples distinguishing architectural decisions from implementation details
• Includes checklist for ADR vs design doc decisions
• Clarifies scope and documentation placement

.claude/skills/manage-adr/references/adr-granularity.md


36. scripts/eslint-score.mjs Miscellaneous +67/-0

ESLint scoring and report generation script

• Node script for generating structured ESLint report
• Calculates lint score: 100 - (errors * 5) - (warnings * 1)
• Outputs lint-report.json with violations and score
• Provides machine-readable feedback for AI agents

scripts/eslint-score.mjs


37. docs/adr/0002-use-graphology-for-graph-management.md 📝 Documentation +68/-0

ADR for Graphology graph management library

• ADR documenting decision to use Graphology library for graph management
• Explains alternatives and rationale for selection
• Includes Mermaid diagram showing architecture
• Documents positive/negative consequences and mitigation

docs/adr/0002-use-graphology-for-graph-management.md


38. docs/adr/0003-use-dbt-tools-scope-for-npm-packages.md 📝 Documentation +63/-0

ADR for @dbt-tools npm scope naming

• ADR documenting npm scoping decision for dbt-tools packages
• Explains package structure and naming conventions
• Includes Mermaid diagram showing package relationships
• Documents consequences and mitigation strategies

docs/adr/0003-use-dbt-tools-scope-for-npm-packages.md


39. packages/dbt-tools/core/README.md 📝 Documentation +51/-0

Core package documentation and API reference

• Package documentation for @dbt-tools/core
• Documents features: ManifestGraph, ExecutionAnalyzer, performance
• Provides usage examples and API reference
• Includes installation instructions

packages/dbt-tools/core/README.md


40. .claude/skills/codeql-fix/SKILL.md 📝 Documentation +37/-0

CodeQL security analysis skill documentation

• Skill definition for CodeQL security analysis and fixing
• Documents command execution and pre-check verification
• Provides fixer loop guidance for addressing findings
• Includes installation instructions for CodeQL CLI

.claude/skills/codeql-fix/SKILL.md


41. .github/workflows/codeql.yml ⚙️ Configuration changes +45/-0

CodeQL GitHub Actions workflow

• GitHub Actions workflow for CodeQL security analysis
• Runs on push to main and pull requests
• Uses GitHub's CodeQL action for JavaScript/TypeScript analysis
• Includes concurrency control and security event permissions

.github/workflows/codeql.yml


42. .claude/skills/lint-fix/SKILL.md 📝 Documentation +2/-1

Lint-fix skill documentation update

• Updates lint-fix skill description to include static analysis
• Adds guidance for structured feedback via lint:report
• Documents ESLint harness for AI agent consumption

.claude/skills/lint-fix/SKILL.md


43. packages/dbt-tools/cli/package.json ⚙️ Configuration changes +38/-0

CLI package configuration and metadata

• Package configuration for @dbt-tools/cli
• Defines bin entry point for dbt-tools command
• Specifies dependencies on @dbt-tools/core and commander
• Includes build, test, and publish configuration

packages/dbt-tools/cli/package.json


44. packages/dbt-tools/core/package.json ⚙️ Configuration changes +37/-0

Core package configuration and dependencies

• Package configuration for @dbt-tools/core
• Specifies dependencies: graphology, graphology-dag, dbt-artifacts-parser
• Includes build, test, and publish configuration
• Defines main entry point and TypeScript declarations

packages/dbt-tools/core/package.json


45. .claude/agents/verifier.md ⚙️ Configuration changes +5/-3

Verifier agent configuration with CodeQL

• Updates verifier agent to include codeql-fix skill
• Adds CodeQL analysis step between lint and test
• Updates success criteria to include CodeQL findings

.claude/agents/verifier.md


46. packages/dbt-artifacts-parser/package.json ⚙️ Configuration changes +26/-0

Package exports configuration for modular imports

• Adds exports field with subpath exports for modular imports
• Exports manifest, run_results, catalog, sources, and test-utils
• Enables tree-shaking and explicit module boundaries
• Maintains backward compatibility with main entry point

packages/dbt-artifacts-parser/package.json


47. scripts/codeql-check.mjs Miscellaneous +16/-0

CodeQL CLI availability pre-check script

• Pre-check script verifying CodeQL CLI availability
• Provides installation instructions if CodeQL not found
• Exits with error code 1 if check fails
• Supports macOS and other platforms

scripts/codeql-check.mjs


48. docs/adr/0001-record-architecture-decisions.md 📝 Documentation +19/-0

ADR for recording architecture decisions

• Initial ADR establishing decision recording practice
• References Michael Nygard's ADR methodology
• Establishes adr-tools as the lightweight toolset

docs/adr/0001-record-architecture-decisions.md


49. .github/workflows/build.yml ⚙️ Configuration changes +7/-0

Build workflow with lint reporting

• Adds ESLint report generation step to build workflow
• Uploads lint report as artifact for CI visibility
• Runs pnpm lint:report to generate structured feedback

.github/workflows/build.yml


50. packages/dbt-tools/core/tsconfig.json 📦 Other +16/-0
• TypeScript configuration for @dbt-tools/core
• Targets ES2017 with CommonJS modules

packages/dbt-tools/core/tsconfig.json


51. .adr-dir Additional files +1/-0

...

.adr-dir


52. .github/workflows/test.yml Additional files +2/-0

...

.github/workflows/test.yml


53. packages/dbt-tools/cli/tsconfig.json Additional files +16/-0

...

packages/dbt-tools/cli/tsconfig.json


54. pnpm-lock.yaml Additional files +4368/-706

...

pnpm-lock.yaml


55. pnpm-workspace.yaml Additional files +2/-1

...

pnpm-workspace.yaml


Grey Divider

Qodo Logo

@qodo-code-review
Copy link

qodo-code-review bot commented Mar 12, 2026

Code Review by Qodo

🐞 Bugs (6) 📘 Rule violations (0) 📎 Requirement gaps (0)

Grey Divider


Action required

1. Run-report path undefined crash🐞 Bug ✓ Correctness
Description
The run-report command always calls loadRunResults(paths.runResults!) even when
[run-results-path] is omitted, but resolveArtifactPaths only sets runResults when
runResultsPath !== undefined. This makes dbt-tools run-report crash at runtime instead of
defaulting to ./target/run_results.json.
Code

packages/dbt-tools/cli/src/cli.ts[R263-277]

+        // Resolve artifact paths
+        const paths = resolveArtifactPaths(
+          manifestPath,
+          runResultsPath,
+          options.targetDir,
+        );
+
+        // Validate paths
+        validateSafePath(paths.manifest);
+        if (paths.runResults) {
+          validateSafePath(paths.runResults);
+        }
+
+        // Load run results
+        const runResults = loadRunResults(paths.runResults!);
Evidence
run-report passes an optional argument (runResultsPath) into resolveArtifactPaths, but
resolveArtifactPaths intentionally omits runResults when that argument is undefined; the CLI
then non-null-asserts paths.runResults and dereferences it, producing an undefined-path failure.
This contradicts the documented default (./target/run_results.json).

packages/dbt-tools/cli/src/cli.ts[239-278]
packages/dbt-tools/core/src/io/artifact-loader.ts[56-79]
packages/dbt-tools/core/src/introspection/schema-generator.ts[35-38]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`dbt-tools run-report` crashes when `[run-results-path]` is omitted because `resolveArtifactPaths` does not set `runResults` for `undefined`, but the CLI calls `loadRunResults(paths.runResults!)` unconditionally.
## Issue Context
The CLI argument docs and schema both state a default of `./target/run_results.json`, so omitting the arg should still load a default path.
## Fix Focus Areas
- packages/dbt-tools/cli/src/cli.ts[239-278]
- packages/dbt-tools/core/src/io/artifact-loader.ts[56-79]
- packages/dbt-tools/core/src/introspection/schema-generator.ts[35-38]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


2. Safe path check bypass🐞 Bug ⛨ Security
Description
validateSafePath is applied to already-normalized absolute paths returned by path.resolve, so
traversal like ../../secret is normalized away and not detected. This allows reading/writing files
outside the intended working directory despite the validator’s stated purpose.
Code

packages/dbt-tools/core/src/validation/input-validator.ts[R5-22]

+export function validateSafePath(path: string): void {
+  if (!path || typeof path !== "string") {
+    throw new Error("Path must be a non-empty string");
+  }
+
+  // Check for path traversal patterns
+  const normalized = path.replace(/\\/g, "/");
+  if (
+    normalized.includes("../") ||
+    normalized.includes("..\\") ||
+    normalized.startsWith("../") ||
+    normalized.includes("/../") ||
+    normalized.includes("\\..\\")
+  ) {
+    throw new Error(
+      `Path traversal detected in path: ${path}. Paths must not contain ../ or ..\\`,
+    );
+  }
Evidence
The validator only searches for literal traversal substrings in the provided string, but artifact
paths are built using path.resolve(...), which removes .. segments. Since the CLI validates
paths.manifest after resolution, traversal inputs normalize into absolute paths without .. and
pass validation, defeating the safety check and enabling arbitrary filesystem access for both reads
(manifest/run_results) and writes (--output).

packages/dbt-tools/core/src/validation/input-validator.ts[1-23]
packages/dbt-tools/core/src/io/artifact-loader.ts[24-38]
packages/dbt-tools/cli/src/cli.ts[70-83]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`validateSafePath` can be bypassed because it checks for `..` substrings on already-resolved paths; `path.resolve` removes `..`, so traversal inputs normalize into absolute paths and pass validation.
## Issue Context
The CLI relies on `validateSafePath` before reading artifacts and before writing graph output, so this bypass enables unintended filesystem read/write.
## Fix Focus Areas
- packages/dbt-tools/core/src/validation/input-validator.ts[1-23]
- packages/dbt-tools/core/src/io/artifact-loader.ts[24-38]
- packages/dbt-tools/cli/src/cli.ts[70-83]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


3. Critical path ignores durations 🐞 Bug ✓ Correctness
Description
ExecutionAnalyzer.findLongestPathToRoot selects the longest path by node count (newPath.length)
rather than by total execution time. This can return an incorrect critical path even when another
path has a larger summed duration.
Code

packages/dbt-tools/core/src/analysis/execution-analyzer.ts[R173-184]

+    const dfs = (currentNode: string, currentPath: string[]): void => {
+      if (visited.has(currentNode)) {
+        return;
+      }
+
+      visited.add(currentNode);
+      const newPath = [...currentPath, currentNode];
+
+      // Update longest path if this is longer
+      if (newPath.length > longestPath.length) {
+        longestPath = newPath;
+      }
Evidence
The critical path computation calls findLongestPathToRoot for each leaf, but that helper only
maximizes the number of nodes, not the summed execution_time. The final selection compares times
between leaf candidates, but each candidate path may already be wrong because it was chosen by
length rather than time.

packages/dbt-tools/core/src/analysis/execution-analyzer.ts[142-150]
packages/dbt-tools/core/src/analysis/execution-analyzer.ts[173-199]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
Critical path selection is based on path length (node count) instead of total duration, producing incorrect `critical_path` results.
## Issue Context
`calculateCriticalPath` calls `findLongestPathToRoot` and then sums times; but `findLongestPathToRoot` already made a length-based choice.
## Fix Focus Areas
- packages/dbt-tools/core/src/analysis/execution-analyzer.ts[138-150]
- packages/dbt-tools/core/src/analysis/execution-analyzer.ts[165-199]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


View more (1)
4. CI skips dbt-tools tests🐞 Bug ⛯ Reliability
Description
GitHub Actions runs tests only for dbt-artifacts-parser, so tests for new @dbt-tools/core and
@dbt-tools/cli packages never execute in CI. Broken dbt-tools behavior can merge without any
failing check.
Code

.github/workflows/test.yml[R53-56]

+      - name: Build dependencies
+        run: pnpm build
  - name: Run tests
    run: pnpm --filter dbt-artifacts-parser test
Evidence
The workflow explicitly filters tests to a single package, while both new packages define test
scripts. This prevents CI from catching regressions in dbt-tools core/cli.

.github/workflows/test.yml[51-56]
packages/dbt-tools/core/package.json[18-23]
packages/dbt-tools/cli/package.json[19-24]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
CI only runs tests for `dbt-artifacts-parser`, so dbt-tools packages are untested in PR checks.
## Issue Context
Both `@dbt-tools/core` and `@dbt-tools/cli` define `test` scripts.
## Fix Focus Areas
- .github/workflows/test.yml[51-56]
- packages/dbt-tools/core/package.json[18-23]
- packages/dbt-tools/cli/package.json[19-24]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools



Remediation recommended

5. NaN depth passes validation 🐞 Bug ✓ Correctness
Description
The deps command parses --depth using parseInt, but the validation accepts NaN because it
only checks typeof depth !== "number" and depth < 1. Passing an invalid depth string results in
silently wrong traversal behavior.
Code

packages/dbt-tools/cli/src/cli.ts[R344-392]

+  .option(
+    "--depth <number>",
+    "Max traversal depth; 1 = immediate neighbors, omit for all levels",
+    parseInt,
+  )
+  .option(
+    "--format <format>",
+    "Output structure: flat list or nested tree",
+    "tree",
+  )
+  .option(
+    "--build-order",
+    "Output upstream dependencies in topological build order (only with --direction upstream)",
+  )
+  .option("--json", "Force JSON output")
+  .option("--no-json", "Force human-readable output")
+  .action(
+    (
+      resourceId: string,
+      options: {
+        direction?: string;
+        manifestPath?: string;
+        targetDir?: string;
+        fields?: string;
+        depth?: number;
+        format?: string;
+        buildOrder?: boolean;
+        json?: boolean;
+        noJson?: boolean;
+      },
+    ) => {
+      try {
+        // Validate resource ID
+        validateResourceId(resourceId);
+
+        // Validate direction
+        const direction = options.direction?.toLowerCase();
+        if (direction !== "upstream" && direction !== "downstream") {
+          throw new Error(
+            `Invalid direction: ${options.direction}. Must be 'upstream' or 'downstream'`,
+          );
+        }
+
+        // Validate depth if provided
+        const depth = options.depth;
+        if (depth !== undefined && (typeof depth !== "number" || depth < 1)) {
+          throw new Error(
+            `Invalid depth: ${options.depth}. Must be a positive integer`,
+          );
Evidence
parseInt can return NaN for non-numeric input; NaN is still of type number and fails all
numeric comparisons, so the current guard does not reject it. The resulting NaN depth then changes
traversal logic via comparisons like nextDepth < maxDepth (always false) in graph traversal,
causing unexpected results instead of an error.

packages/dbt-tools/cli/src/cli.ts[344-393]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
`--depth` accepts `NaN` due to insufficient validation, leading to incorrect traversal behavior.
## Issue Context
`parseInt` returns `NaN` on malformed input; `typeof NaN === &amp;amp;amp;amp;quot;number&amp;amp;amp;amp;quot;` and comparisons like `NaN &amp;amp;amp;amp;lt; 1` are false.
## Fix Focus Areas
- packages/dbt-tools/cli/src/cli.ts[344-393]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


6. BFS uses array shift🐞 Bug ➹ Performance
Description
ManifestGraph BFS implementations dequeue with queue.shift(), which is O(n) per operation on JS
arrays. On large manifests, dependency traversals can degrade to quadratic time.
Code

packages/dbt-tools/core/src/analysis/manifest-graph.ts[R372-395]

+    const result: Array<{ nodeId: string; depth: number }> = [];
+    const visited = new Set<string>();
+    const queue: Array<{ id: string; depth: number }> = [];
+
+    for (const neighborId of this.graph.inboundNeighbors(nodeId)) {
+      if (!visited.has(neighborId)) {
+        visited.add(neighborId);
+        result.push({ nodeId: neighborId, depth: 1 });
+        if (maxDepth === undefined || 1 < maxDepth) {
+          queue.push({ id: neighborId, depth: 1 });
+        }
+      }
+    }
+
+    while (queue.length > 0) {
+      const { id, depth } = queue.shift()!;
+      const nextDepth = depth + 1;
+      for (const neighborId of this.graph.inboundNeighbors(id)) {
+        if (!visited.has(neighborId)) {
+          visited.add(neighborId);
+          result.push({ nodeId: neighborId, depth: nextDepth });
+          if (maxDepth === undefined || nextDepth < maxDepth) {
+            queue.push({ id: neighborId, depth: nextDepth });
+          }
Evidence
The BFS loop removes the first element with shift(), which requires moving all remaining elements
each time; this increases CPU cost as the queue grows. The same pattern is used across
upstream/downstream traversal methods, so the cost scales with graph size and traversal depth.

packages/dbt-tools/core/src/analysis/manifest-graph.ts[372-398]

Agent prompt
The issue below was found during a code review. Follow the provided context and guidance below and implement a solution

## Issue description
BFS traversal uses `Array.prototype.shift()`, causing unnecessary O(n^2) behavior.
## Issue Context
dbt manifests can be large; traversal is a core operation for `deps` and other analysis.
## Fix Focus Areas
- packages/dbt-tools/core/src/analysis/manifest-graph.ts[364-399]
- packages/dbt-tools/core/src/analysis/manifest-graph.ts[409-446]

ⓘ Copy this prompt and use it to remediate the issue with your preferred AI generation tools


Grey Divider

ⓘ The new review experience is currently in Beta. Learn more

Grey Divider

Qodo Logo

yu-iskw added 3 commits March 12, 2026 15:11
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
yu-iskw added 3 commits March 13, 2026 10:18
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
Signed-off-by: Yu Ishikawa <yu-iskw@users.noreply.github.com>
@yu-iskw yu-iskw merged commit 6c91fa2 into main Mar 13, 2026
6 checks passed
@yu-iskw yu-iskw deleted the dbt-tools branch March 13, 2026 01:59
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.

1 participant