rtk icon indicating copy to clipboard operation
rtk copied to clipboard

`rtk ruff` reads the subcommand from fixed positions, so ruff global options make `rtk ruff --isolated analyze graph` truncate the JSON

Open KuSh opened this issue 1 month ago • 4 comments

rtk ruff decides the route from fixed argument positions: is_check_invocation reads args[0], is_format matches format anywhere, and (with #3942) is_analyze_graph_invocation reads args[0] and args[1]. ruff's global options are accepted before the subcommand and between analyze and graph, so any of them moves the subcommand out of the position rtk looks at.

First reported by @Protocol-zero-0 in https://github.com/rtk-ai/rtk/pull/3942#pullrequestreview-5543352106, for the global options before analyze.

Reproduction (ruff 0.16.6, LC_ALL=C, a 301-file package big/)

args native ruff rtk on develop 83fea3509 rtk with #3942
analyze graph big 12628 B, valid JSON 2001 B, invalid 12628 B, identical
--isolated analyze graph big 12628 B, valid JSON 2001 B, invalid 2001 B, invalid
--color never analyze graph big 12628 B 2001 B 2001 B
--config ruff.toml analyze graph big 12628 B 2001 B 2001 B
--config=ruff.toml analyze graph big 12628 B 2001 B 2001 B
-q analyze graph big 12628 B 2001 B 2001 B
analyze -v graph big 12628 B 2001 B 2001 B
analyze --isolated graph big 12628 B 2001 B 2001 B
analyze --config ruff.toml graph big 12628 B 2001 B 2001 B

All exit 0 on both sides, so the caller only finds out when parsing stdout.

Same class, already filed

  • #3927: is_check_invocation gives up at the first -, so rtk ruff --select F401 src never routes to check.
  • #3928: is_format matches a bare format token anywhere in argv.

Direction

Find the subcommand once, through arg_tokenizer::tokenize_grammar with ruff's global grammar transcribed from ruff --help (--config <v> and --color <v> take a value, --isolated, -v, -q, -s, -h, -V do not), and have all three detectors read that one result (.claude/rules/rust-patterns.md rule 6). Open PRs #3933 and #3968 touch the same detectors.

KuSh avatar Oct 19 '26 00:10 KuSh

wshm · Automated triage by AI

🔍 Automated Triage

🐛 Category bug
🟡 Priority medium
🎯 Confidence 93%

Summary

rtk ruff routes subcommands by fixed arg position, so any ruff global option (--isolated, --color, -q, etc.) before/between subcommand tokens makes it misdetect and truncate output; fix by tokenizing against ruff's global grammar once and sharing that result across detectors.

📁 Relevant files
  • src/arg_tokenizer.rs
  • src/discover/ruff.rs

Suggested Actions

  1. Reconcile with open PRs #3933 and #3968 which touch the same detectors before merging a fix
  2. Implement shared grammar-based tokenization per .claude/rules/rust-patterns.md rule 6, used by is_check_invocation/is_f…
  3. Cross-reference #3927 and #3928 — same root cause (positional/token-scan detection) across ruff detectors
  4. Add regression tests covering each table row (--isolated, --color, --config, -q, analyze -v graph, etc.)

Triaged automatically by wshm · This is an automated analysis, not a human review.

rtk-wshm-sync-bot avatar Oct 19 '26 00:10 rtk-wshm-sync-bot

PR delivery after #3968 merged: https://github.com/rtk-ai/rtk/pull/4892 (rebased on the merged router; the integration patch below is historical).

Thanks for splitting this out. I verified an integration of #3968 (6345475492) with the merged #3942 on develop 9a501c8d.

The reusable finder is already in #3968: route_ruff_args consumes --config/--color values through tokenize_grammar, and both check and format use that result. The merge conflicts in ruff_cmd.rs; the patch below resolves it by adding an AnalyzeGraph route to that same finder. It reads the next free positional before --, so global options can occur between analyze and graph without treating an option value as the action. #3942's captured-output tests are retained. This is an integration of the existing PR, with its implementation and tests preserved.

Verified with real Ruff 0.17.0 on Linux: 28 scenarios / 84 native, current-develop and combined executions. All eight forms in this issue return the full 12,628-byte graph, matching native stdout; current develop returns 2,001 bytes for those forms. Additional controls cover both option levels, command-like config filenames, a directory named format, reversed graph direction, small graphs, check routing, help/version and invalid inputs. All combined exit codes match the corresponding native command; the implicit-check control compares with native ruff check.

24 Ruff unit tests, three process integration tests (including exact forwarded argv for the eight forms), fmt and warnings-denied all-targets clippy pass. The full Linux local suite passes: 4,693 passed, 8 ignored across 42 test targets.

The patch applies cleanly to 9a501c8d; it includes #3968's routing changes plus the graph integration, and is ready for the chosen integration branch. #3933 overlaps the format routing already covered here. #4655's other structured formats remain separate; the existing rule E501 cap is deliberately pinned. Other platforms and Ruff versions have not been run locally.

Apply-ready integration patch against develop 9a501c8d (reuses #3968)
diff --git a/src/cmds/python/ruff_cmd.rs b/src/cmds/python/ruff_cmd.rs
index d8dede3d..1b5fce2c 100644
--- a/src/cmds/python/ruff_cmd.rs
+++ b/src/cmds/python/ruff_cmd.rs
@@ -1,5 +1,8 @@
 //! Filters Ruff linter and formatter output.
 
+use crate::core::arg_tokenizer::{
+    Dialect, TokenKind, ValueSpec, before_dashdash, dashdash_index, tokenize_grammar,
+};
 use crate::core::config;
 use crate::core::runner;
 use crate::core::shell::display_args;
@@ -49,10 +52,8 @@ struct RuffDiagnostic {
 }
 
 pub fn run(args: &[String], verbose: u8) -> Result<i32> {
-    let is_check = is_check_invocation(args);
-
-    let is_format = args.iter().any(|a| a == "format");
-    let is_analyze_graph = is_analyze_graph_invocation(args);
+    let route = route_ruff_args(args);
+    let is_check = matches!(route, RuffRoute::Check { .. });
 
     let mut cmd = resolved_command("ruff");
 
@@ -61,84 +62,176 @@ pub fn run(args: &[String], verbose: u8) -> Result<i32> {
         .iter()
         .any(|a| a == "--output-format" || a.starts_with("--output-format="));
 
-    let user_json_format = args.iter().enumerate().any(|(i, a)| {
-        a == "--output-format=json"
-            || (a == "--output-format" && args.get(i + 1).is_some_and(|n| n == "json"))
-    });
-    let use_json_filter = !user_set_output_format || user_json_format;
-    // `[]` is a clean run only when rtk chose the format; a user who asked for JSON gets `[]` back.
     let clean_outputs: &[&str] = if is_check && !user_set_output_format {
         &["[]"]
     } else {
         &[]
     };
 
-    if is_check {
-        if user_set_output_format {
-            cmd.arg("check");
-        } else {
-            cmd.arg("check").arg("--output-format=json");
-        }
-
-        let start_idx = if !args.is_empty() && args[0] == "check" {
-            1
-        } else {
-            0
-        };
-        for arg in &args[start_idx..] {
-            cmd.arg(arg);
-        }
-
-        if args
-            .iter()
-            .skip(start_idx)
-            .all(|a| a.starts_with('-') || a.contains('='))
-        {
-            cmd.arg(".");
-        }
-    } else {
-        for arg in args {
-            cmd.arg(arg);
-        }
+    for arg in plan_ruff_command(args) {
+        cmd.arg(arg);
     }
 
     if verbose > 0 {
         eprintln!("Running: ruff {}", args.join(" "));
     }
 
+    let owned_args = args.to_vec();
     runner::run_filtered(
         cmd,
         "ruff",
         &display_args(args),
-        move |stdout| {
-            if is_check && use_json_filter && !stdout.trim().is_empty() {
-                filter_ruff_check_json(stdout)
-            } else if is_format {
-                filter_ruff_format(stdout)
-            } else {
-                filter_passthrough_output(stdout, is_analyze_graph)
-            }
-        },
+        move |stdout| filter_ruff_output(&owned_args, stdout),
         runner::RunOptions::stdout_only().clean_outputs(clean_outputs),
     )
 }
 
-fn is_analyze_graph_invocation(args: &[String]) -> bool {
-    matches!(args, [subcommand, action, ..] if subcommand == "analyze" && action == "graph")
+/// Choose the output treatment for a routed invocation: check runs get the
+/// JSON summary, format runs the format summary, help and version requests
+/// stay complete, and everything else is a bounded passthrough.
+fn filter_ruff_output(args: &[String], stdout: &str) -> String {
+    let route = route_ruff_args(args);
+    let is_check = matches!(route, RuffRoute::Check { .. });
+    let is_format = matches!(route, RuffRoute::Subcommand { at } if args[at] == "format");
+    let trimmed = stdout.trim();
+
+    let user_set_output_format = args
+        .iter()
+        .any(|a| a == "--output-format" || a.starts_with("--output-format="));
+    let user_json_format = args.iter().enumerate().any(|(i, a)| {
+        a == "--output-format=json"
+            || (a == "--output-format" && args.get(i + 1).is_some_and(|n| n == "json"))
+    });
+    let use_json_filter = !user_set_output_format || user_json_format;
+
+    if is_check && use_json_filter && !trimmed.is_empty() {
+        filter_ruff_check_json(stdout)
+    } else if is_format {
+        filter_ruff_format(stdout)
+    } else if ruff_output_is_complete(route, args) {
+        // Help and version output are complete documentation: raw Ruff
+        // returns every byte, and so does rtk.
+        trimmed.to_string()
+    } else {
+        truncate(trimmed, config::limits().passthrough_max_chars)
+    }
+}
+
+/// Help, version and analyze graph requests must keep their full stdout.
+fn ruff_output_is_complete(route: RuffRoute, args: &[String]) -> bool {
+    match route {
+        RuffRoute::TopLevel | RuffRoute::AnalyzeGraph => true,
+        RuffRoute::Subcommand { at } => matches!(args[at].as_str(), "help" | "version"),
+        RuffRoute::Check { .. } => false,
+    }
 }
 
-fn filter_passthrough_output(stdout: &str, is_analyze_graph: bool) -> String {
-    if is_analyze_graph {
-        stdout.trim().to_string()
+/// Route an invocation through the shared tokenizer, consuming the values of
+/// ruff's value-taking global options so an option value is never mistaken
+/// for the subcommand or a path.
+fn route_ruff_args(args: &[String]) -> RuffRoute {
+    let tokens = tokenize_grammar(args, &ruff_takes_value, Dialect::Posix);
+    for (index, token) in before_dashdash(&tokens).iter().enumerate() {
+        if !token.is_free_positional() {
+            continue;
+        }
+        // The first free positional decides: a known subcommand routes,
+        // anything else is a path and the invocation is an implicit check.
+        if RUFF_SUBCOMMANDS.contains(&token.text) {
+            // `analyze` has its own subcommands, with the same global options
+            // allowed between the two command words (ruff analyze --help).
+            // Read the next free positional from this same grammar, so neither
+            // --config's value nor text past `--` can become the graph action.
+            if token.text == "analyze"
+                && before_dashdash(&tokens)[index + 1..]
+                    .iter()
+                    .find(|token| token.is_free_positional())
+                    .is_some_and(|token| token.text == "graph")
+            {
+                return RuffRoute::AnalyzeGraph;
+            }
+            if token.text == "check" {
+                return RuffRoute::Check {
+                    explicit_at: Some(token.source_index),
+                };
+            }
+            return RuffRoute::Subcommand {
+                at: token.source_index,
+            };
+        }
+        return RuffRoute::Check { explicit_at: None };
+    }
+    // No free positional before the `--` boundary: a path after it keeps the
+    // run an implicit check, because everything past the boundary is a path.
+    if dashdash_index(&tokens).is_some() && tokens.iter().any(|t| t.is_free_positional()) {
+        return RuffRoute::Check { explicit_at: None };
+    }
+    top_level_request(args)
+}
+
+/// Ruff's only global options that consume a separate value
+/// (`ruff --help`, 0.17: `--config` and `--color`). Every other global token
+/// is a flag; rule-selection options belong to the subcommand and only
+/// appear once the routing decision has been made.
+const RUFF_GLOBAL_VALUE_OPTIONS: &[&str] = &["config", "color"];
+
+fn ruff_takes_value(kind: TokenKind, name: &str) -> Option<ValueSpec> {
+    (kind == TokenKind::Long && RUFF_GLOBAL_VALUE_OPTIONS.contains(&name)).then(ValueSpec::value)
+}
+
+/// How an invocation routes once global option values are consumed.
+#[derive(Clone, Copy, Debug)]
+enum RuffRoute {
+    /// The JSON graph is a document; preserve it whole like #3942.
+    AnalyzeGraph,
+    /// Run `ruff check`. `explicit_at` is the index of the user's `check`
+    /// token when present, so it can be forwarded without duplication.
+    Check { explicit_at: Option<usize> },
+    /// An explicit non-check subcommand at `at`; forwarded verbatim.
+    Subcommand { at: usize },
+    /// No subcommand and no path: a top-level request such as `--version`.
+    TopLevel,
+}
+
+/// Flag-only invocations stay top-level for `--version`/`--help`; every other
+/// flags-only call (for example `--statistics`) is an implicit check.
+fn top_level_request(args: &[String]) -> RuffRoute {
+    if args
+        .iter()
+        .any(|arg| matches!(arg.as_str(), "--version" | "-V" | "--help" | "-h"))
+    {
+        RuffRoute::TopLevel
     } else {
-        truncate(stdout.trim(), config::limits().passthrough_max_chars)
+        RuffRoute::Check { explicit_at: None }
     }
 }
 
-fn is_check_invocation(args: &[String]) -> bool {
-    args.first().is_none_or(|arg| {
-        arg == "check" || (!arg.starts_with('-') && !RUFF_SUBCOMMANDS.contains(&arg.as_str()))
-    })
+/// The complete argument vector rtk passes to ruff.
+fn plan_ruff_command(args: &[String]) -> Vec<String> {
+    let user_set_output_format = args
+        .iter()
+        .any(|a| a == "--output-format" || a.starts_with("--output-format="));
+    if let RuffRoute::Check { explicit_at } = route_ruff_args(args) {
+        let forwarded: Vec<&str> = args
+            .iter()
+            .enumerate()
+            .filter(|(i, _)| Some(*i) != explicit_at)
+            .map(|(_, arg)| arg.as_str())
+            .collect();
+        let mut plan = vec!["check".to_string()];
+        if !user_set_output_format {
+            plan.push("--output-format=json".to_string());
+        }
+        plan.extend(forwarded.iter().map(|arg| (*arg).to_string()));
+        if forwarded
+            .iter()
+            .all(|arg| arg.starts_with('-') || arg.contains('='))
+        {
+            plan.push(".".to_string());
+        }
+        return plan;
+    }
+    args.to_vec()
 }
 
 /// Filter ruff check JSON output - group by rule and file
@@ -396,7 +489,7 @@ mod tests {
         for subcommand in RUFF_SUBCOMMANDS {
             let args = vec![subcommand.to_string()];
             assert_eq!(
-                is_check_invocation(&args),
+                matches!(route_ruff_args(&args), RuffRoute::Check { .. }),
                 *subcommand == "check",
                 "unexpected routing for ruff {subcommand}"
             );
@@ -427,16 +520,46 @@ mod tests {
 
     #[test]
     fn paths_and_explicit_check_route_through_check() {
-        assert!(is_check_invocation(&[]));
-        assert!(is_check_invocation(&["check".to_string(), ".".to_string()]));
-        assert!(is_check_invocation(&["src".to_string()]));
-        assert!(is_check_invocation(&["pyproject.toml".to_string()]));
+        assert_plan(&[], &["check", "--output-format=json", "."]);
+        assert_plan(&["check", "."], &["check", "--output-format=json", "."]);
+        assert_plan(&["src"], &["check", "--output-format=json", "src"]);
+        assert_plan(
+            &["pyproject.toml"],
+            &["check", "--output-format=json", "pyproject.toml"],
+        );
     }
 
     #[test]
     fn top_level_flags_are_not_misclassified_as_paths() {
-        assert!(!is_check_invocation(&["--version".to_string()]));
-        assert!(!is_check_invocation(&["--help".to_string()]));
+        assert_plan(&["--version"], &["--version"]);
+        assert_plan(&["--help"], &["--help"]);
+        assert_plan(&["-V"], &["-V"]);
+        assert_plan(&["-h"], &["-h"]);
+    }
+
+    #[test]
+    fn flag_first_implicit_check_routes_to_check() {
+        assert_plan(
+            &["--select", "F401", "src"],
+            &["check", "--output-format=json", "--select", "F401", "src"],
+        );
+        assert_plan(
+            &["--fix", "src"],
+            &["check", "--output-format=json", "--fix", "src"],
+        );
+        assert_plan(
+            &["-q", "src"],
+            &["check", "--output-format=json", "-q", "src"],
+        );
+    }
+
+    #[test]
+    fn flag_only_implicit_check_routes_to_check() {
+        assert_plan(&["--fix"], &["check", "--output-format=json", "--fix", "."]);
+        assert_plan(
+            &["--statistics"],
+            &["check", "--output-format=json", "--statistics", "."],
+        );
     }
 
     #[test]
@@ -445,7 +568,7 @@ mod tests {
         assert!(raw.len() > config::limits().passthrough_max_chars);
 
         let args = ["analyze".to_string(), "graph".to_string()];
-        let result = filter_passthrough_output(raw, is_analyze_graph_invocation(&args));
+        let result = filter_ruff_output(&args, raw);
 
         assert_eq!(result, raw.trim());
         serde_json::from_str::<serde_json::Value>(&result)
@@ -457,6 +580,8 @@ mod tests {
     #[test]
     fn only_analyze_graph_skips_the_passthrough_cap() {
         let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::<Vec<_>>();
+        let is_analyze_graph_invocation =
+            |args: &[String]| matches!(route_ruff_args(args), RuffRoute::AnalyzeGraph);
         assert!(is_analyze_graph_invocation(&args(&["analyze", "graph"])));
         assert!(is_analyze_graph_invocation(&args(&[
             "analyze",
@@ -472,8 +597,7 @@ mod tests {
 
         let raw = include_str!("../../../tests/fixtures/ruff_rule_e501_raw.txt");
         assert!(raw.len() > config::limits().passthrough_max_chars);
-        let result =
-            filter_passthrough_output(raw, is_analyze_graph_invocation(&args(&["rule", "E501"])));
+        let result = filter_ruff_output(&args(&["rule", "E501"]), raw);
         assert!(
             result.ends_with("...") && raw.starts_with(result.trim_end_matches("...")),
             "rule output must be a capped prefix of ruff's, got {} of {} bytes",
@@ -596,4 +720,224 @@ Would reformat: tests/test_utils.py
         );
         assert_eq!(compact_path("relative/file.py"), "file.py");
     }
+
+    fn owned(args: &[&str]) -> Vec<String> {
+        args.iter().map(|a| a.to_string()).collect()
+    }
+
+    fn assert_plan(args: &[&str], expected: &[&str]) {
+        assert_eq!(
+            plan_ruff_command(&owned(args)),
+            owned(expected),
+            "plan for {args:?}"
+        );
+    }
+
+    #[test]
+    fn ruff_routes_implicit_check_flags_before_paths() {
+        // #3927: flags meant for `ruff check` used to bail into passthrough.
+        assert_plan(
+            &["--select", "F401", "bad.py"],
+            &[
+                "check",
+                "--output-format=json",
+                "--select",
+                "F401",
+                "bad.py",
+            ],
+        );
+        assert_plan(
+            &["-q", "clean.py"],
+            &["check", "--output-format=json", "-q", "clean.py"],
+        );
+        assert_plan(
+            &["--statistics"],
+            &["check", "--output-format=json", "--statistics", "."],
+        );
+        assert_plan(&[], &["check", "--output-format=json", "."]);
+    }
+
+    #[test]
+    fn ruff_routes_explicit_check_and_drops_it_in_place() {
+        assert_plan(
+            &["check", "a.py"],
+            &["check", "--output-format=json", "a.py"],
+        );
+        assert_plan(&["check"], &["check", "--output-format=json", "."]);
+        // The reviewer case: an explicit `check` after a global flag must be
+        // consumed at its actual position, not forwarded as a path.
+        assert_plan(
+            &["--isolated", "check", "clean.py"],
+            &["check", "--output-format=json", "--isolated", "clean.py"],
+        );
+        assert_plan(
+            &["--config", "ruff.toml", "check", "clean.py"],
+            &[
+                "check",
+                "--output-format=json",
+                "--config",
+                "ruff.toml",
+                "clean.py",
+            ],
+        );
+    }
+
+    #[test]
+    fn ruff_routes_global_option_values_not_subcommands() {
+        // `ruff.toml` is `--config`'s value: the `format` that follows is the
+        // subcommand and the whole invocation is forwarded verbatim.
+        assert_plan(
+            &["--config", "ruff.toml", "format", "--check", "clean.py"],
+            &["--config", "ruff.toml", "format", "--check", "clean.py"],
+        );
+        // A top-level request keeps its place even after a value-taking option.
+        assert_plan(
+            &["--config", "ruff.toml", "--version"],
+            &["--config", "ruff.toml", "--version"],
+        );
+        assert_plan(&["--version"], &["--version"]);
+        assert_plan(
+            &["--config=ruff.toml", "clean.py"],
+            &[
+                "check",
+                "--output-format=json",
+                "--config=ruff.toml",
+                "clean.py",
+            ],
+        );
+        assert_plan(
+            &["--", "clean.py"],
+            &["check", "--output-format=json", "--", "clean.py"],
+        );
+    }
+
+    #[test]
+    fn ruff_routes_user_output_format_without_json_injection() {
+        assert_plan(
+            &["--output-format", "concise", "bad.py"],
+            &["check", "--output-format", "concise", "bad.py"],
+        );
+        assert_plan(
+            &["--output-format=json", "bad.py"],
+            &["check", "--output-format=json", "bad.py"],
+        );
+    }
+
+    #[test]
+    fn ruff_format_filter_only_for_the_effective_format_subcommand() {
+        // `format` as the effective subcommand routes to the format filter.
+        assert!(matches!(
+            route_ruff_args(&owned(&[
+                "--config",
+                "ruff.toml",
+                "format",
+                "--check",
+                "a.py"
+            ])),
+            RuffRoute::Subcommand { at: 2 }
+        ));
+        // `help format` is a help request, and `check ... format ...` is a
+        // check invocation: neither routes to the format filter.
+        assert!(matches!(
+            route_ruff_args(&owned(&["help", "format"])),
+            RuffRoute::Subcommand { at: 0 }
+        ));
+        assert!(matches!(
+            route_ruff_args(&owned(&["check", "--format", "json"])),
+            RuffRoute::Check {
+                explicit_at: Some(0)
+            }
+        ));
+        // A path named `format.py` never matches a subcommand.
+        assert!(matches!(
+            route_ruff_args(&owned(&["format.py"])),
+            RuffRoute::Check { explicit_at: None }
+        ));
+    }
+
+    #[test]
+    fn ruff_help_and_version_output_stay_complete() {
+        // Pin the stdout bytes: help output longer than the bounded
+        // passthrough must come back exactly as ruff printed it.
+        let max_chars = config::limits().passthrough_max_chars;
+        let help = "usage: ruff help\n".repeat(max_chars);
+        assert_eq!(
+            filter_ruff_output(&owned(&["help", "format"]), &help),
+            help.trim()
+        );
+        assert_eq!(filter_ruff_output(&owned(&["version"]), &help), help.trim());
+        assert_eq!(
+            filter_ruff_output(&owned(&["--version"]), &help),
+            help.trim()
+        );
+        assert_eq!(
+            filter_ruff_output(&owned(&["--config", "ruff.toml", "--help"]), &help),
+            help.trim()
+        );
+    }
+
+    #[test]
+    fn ruff_other_subcommands_keep_the_bounded_passthrough() {
+        let max_chars = config::limits().passthrough_max_chars;
+        let long = "rule F401: ".repeat(max_chars);
+        let out = filter_ruff_output(&owned(&["rule", "F401"]), &long);
+        assert!(out.len() < long.len());
+        assert!(out.ends_with("..."));
+    }
+
+    #[test]
+    fn ruff_output_filter_selects_by_route() {
+        // Check runs keep the JSON summary.
+        let json = r#"[{"code":"F401","message":"`os` imported but unused","location":{"row":1,"column":1},"end_location":{"row":1,"column":9},"filename":"dirty.py","fix":null}]"#;
+        assert!(filter_ruff_output(&owned(&["check", "dirty.py"]), json).contains("F401"));
+        // The format filter still serves effective format subcommands
+        // (pre-0.16 wording; the ruff >= 0.16 shapes are #3965's scope).
+        let mixed =
+            "Would reformat: dirty.py\n2 files would be reformatted, 3 files left unchanged";
+        assert!(
+            filter_ruff_output(&owned(&["format", "--check", "dirty.py"]), mixed)
+                .contains("1 files need formatting")
+        );
+    }
+    #[test]
+    fn graph_routing_skips_global_options_at_both_command_levels() {
+        let raw = include_str!("../../../tests/fixtures/ruff_analyze_graph_raw.json");
+        for args in [
+            vec!["--isolated", "analyze", "graph", "big"],
+            vec!["--color", "never", "analyze", "graph", "big"],
+            vec!["--config", "ruff.toml", "analyze", "graph", "big"],
+            vec!["--config=ruff.toml", "analyze", "graph", "big"],
+            vec!["-q", "analyze", "graph", "big"],
+            vec!["analyze", "-v", "graph", "big"],
+            vec!["analyze", "--isolated", "graph", "big"],
+            vec!["analyze", "--config", "ruff.toml", "graph", "big"],
+            vec![
+                "--config", "format", "analyze", "--config", "check", "graph", "big",
+            ],
+        ] {
+            let args = owned(&args);
+            assert!(
+                matches!(route_ruff_args(&args), RuffRoute::AnalyzeGraph),
+                "{args:?}"
+            );
+            assert_eq!(plan_ruff_command(&args), args, "forward original argv");
+            assert_eq!(filter_ruff_output(&args, raw), raw.trim(), "{args:?}");
+        }
+    }
+
+    #[test]
+    fn graph_action_is_not_an_option_value_help_argument_or_path() {
+        for args in [
+            vec!["analyze", "--config", "graph", "help"],
+            vec!["analyze", "--", "graph"],
+            vec!["help", "analyze", "graph"],
+            vec!["--config", "analyze", "help", "graph"],
+            vec!["check", "--", "analyze", "graph"],
+        ] {
+            assert!(
+                !matches!(route_ruff_args(&owned(&args)), RuffRoute::AnalyzeGraph),
+                "{args:?}"
+            );
+        }
+    }
 }
diff --git a/tests/ruff_passthrough_test.rs b/tests/ruff_passthrough_test.rs
index 7938faeb..4a06f833 100644
--- a/tests/ruff_passthrough_test.rs
+++ b/tests/ruff_passthrough_test.rs
@@ -88,3 +88,27 @@ fn other_passthrough_subcommands_keep_the_cap() {
         context(&out)
     );
 }
+
+#[test]
+fn global_options_keep_graph_json_complete_and_argv_unchanged() {
+    for args in [
+        vec!["--isolated", "analyze", "graph", "big"],
+        vec!["--color", "never", "analyze", "graph", "big"],
+        vec!["--config", "ruff.toml", "analyze", "graph", "big"],
+        vec!["--config=ruff.toml", "analyze", "graph", "big"],
+        vec!["-q", "analyze", "graph", "big"],
+        vec!["analyze", "-v", "graph", "big"],
+        vec!["analyze", "--isolated", "graph", "big"],
+        vec!["analyze", "--config", "ruff.toml", "graph", "big"],
+    ] {
+        let dir = common::tempdir();
+        fake_ruff(dir.path(), &args, GRAPH);
+        let out = rtk_ruff(dir.path(), &args);
+        assert_eq!(out.status.code(), Some(0), "{args:?}: {}", context(&out));
+        assert_eq!(
+            String::from_utf8_lossy(&out.stdout).trim(),
+            GRAPH.trim(),
+            "{args:?}"
+        );
+    }
+}

Protocol-zero-0 avatar Oct 19 '26 01:10 Protocol-zero-0

@Protocol-zero-0 thank you for the integration and the 28-scenario run. I applied the patch on develop 5ab629136: it builds, and the eight forms above return the complete graph.

#3968 had its review today (https://github.com/rtk-ai/rtk/pull/3968#pullrequestreview-5593429901). It stays scoped to #3927, and its rebase keeps #3942's positional exemption, so this issue stays open after it lands. Would you open the #4654 fix as its own PR once #3968 merges, with the AnalyzeGraph route on top of its router? Your scenario set is the test plan I'd expect. One thing to know: item 1 of that review makes any option outside ruff's global grammar end the subcommand search, so the analyze … graph lookahead should read from the same tokens. Opening it earlier as a draft stacked on #3968's branch works too, if you prefer.

KuSh avatar Oct 21 '26 00:10 KuSh

I’ll open #4654 as a separate PR after #3968 merges, using its revised router tokens for the AnalyzeGraph lookahead. I’ll carry over the 28-scenario matrix and add controls where a check-only option ends the subcommand search, so a later analyze or graph value cannot change the route.

I’ve also noted the generate-shell-completion bash and implicit-check --output-format concise rows for the #4655 follow-up. The shell-completion case needs byte-for-byte output preservation and a shell syntax check, rather than only a length check.

Protocol-zero-0 avatar Oct 21 '26 07:10 Protocol-zero-0