Class: RailsAiContext::Tools::GetRoutes

Inherits:
BaseTool
  • Object
show all
Defined in:
lib/rails_ai_context/tools/get_routes.rb

Constant Summary

Constants inherited from BaseTool

BaseTool::DEFAULT_SESSION, BaseTool::MAX_SESSIONS, BaseTool::MAX_SESSION_ID_LENGTH, BaseTool::SESSION_CONTEXT, BaseTool::SHARED_CACHE

Class Method Summary collapse

Methods inherited from BaseTool

abstract!, abstract?, api_only_app?, api_only_note, cache_key, cached_context, config, current_session, #dedupe_put_patch_routes, detail_param?, error_response, evict_oldest_sessions, extract_method_source_from_file, extract_method_source_from_string, find_closest_match, fuzzy_find_key, guide_row, inherited, introspection_warnings_note, invalid_detail_note, normalize_detail, not_found_response, paginate, rails_app, rails_env_name, registered_tools, reset_all_caches!, reset_cache!, session_from, session_params, session_queries, session_record, session_reset!, static_tier_banner, static_tier_refusal, text_response, touch_session, unavailable_note, with_session, with_session_for

Methods included from SectionFetch

#fetch_section, usable?

Class Method Details

.call(controller: nil, detail: "standard", limit: nil, offset: 0, app_only: true, server_context: nil) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
# File 'lib/rails_ai_context/tools/get_routes.rb', line 54

def self.call(controller: nil, detail: "standard", limit: nil, offset: 0, app_only: true, server_context: nil)
  fetch_section(:routes, subject: "Route introspection") do |routes|
    by_controller = routes[:by_controller] || {}
    offset = [ offset.to_i, 0 ].max

    # Routes with no controller#action (engine mounts like propshaft's
    # /assets) never enter by_controller; surface their count so the
    # header's arithmetic adds up instead of silently dropping them.
    unattributed_count = routes[:unrouted_mounts] || Array(routes[:mounted_engines]).size

    # Filter out internal Rails routes by default, remembering how many
    # were dropped so headers can say the count is app-only, not the total.
    excluded_framework_count = 0
    if app_only
      framework_ctrls = by_controller.select { |k, _| framework_controller?(k) }
      excluded_framework_count = framework_ctrls.values.sum { |actions| dedupe_put_patch_routes(actions).size }
      by_controller = by_controller.reject { |k, _| framework_controller?(k) }
    end

    # Filter by controller - accepts "posts", "PostsController", "posts_controller", "Api::V1::Posts"
    if controller
      normalized = controller.underscore.delete_suffix("_controller")
      normalized_alt = controller.downcase.delete_suffix("_controller").delete_suffix("controller")
      filtered = by_controller.select { |k, _| k.downcase.include?(normalized) || k.downcase.include?(normalized_alt) }
      return text_response("No routes for '#{controller}'. Controllers: #{by_controller.keys.sort.join(', ')}") if filtered.empty?
      by_controller = filtered
    end

    # Combine PUT/PATCH duplicates (Rails generates both for update routes)
    by_controller = by_controller.transform_values { |actions| dedupe_put_patch_routes(actions) }
    filtered_total = by_controller.values.sum(&:size)
    count_label = count_phrase(filtered_total, "route")
    if excluded_framework_count > 0 && controller.nil?
      count_label += ", excluding #{count_phrase(excluded_framework_count, "framework route")}"
    end
    if unattributed_count > 0 && controller.nil?
      count_label += " and #{count_phrase(unattributed_count, "engine mount")}"
    end
    # Dropping the count of what the static tier could not expand let a
    # partial list read as the whole routing table, which is the one
    # thing an unbooted answer must not do. All three detail levels share
    # this label. Gated on `controller` because the caveat is about the
    # whole table, and a filtered answer is not that.
    count_label += RailsAiContext::RouteCoverage.suffix(routes) if controller.nil?

    case detail
    when "summary"
      # Separate app routes from framework routes for cleaner output
      app_routes = controller ? by_controller : by_controller.reject { |k, _| route_prefixes.any? { |p| k.downcase.start_with?(p) } }
      framework_routes = controller ? {} : by_controller.select { |k, _| route_prefixes.any? { |p| k.downcase.start_with?(p) } }

      lines = [ "# Routes Summary (#{count_label})", "" ]

      # Group sibling routes with identical verb patterns (e.g., bonus/*)
      grouped = app_routes.keys.sort.group_by do |ctrl|
        actions = app_routes[ctrl]
        namespace = ctrl.include?("/") ? ctrl.split("/").first : nil
        verbs_sig = actions.map { |r| r[:verb] }.sort.join(",")
        count_sig = actions.size
        namespace && app_routes.count { |k, v| k.start_with?("#{namespace}/") && v.size == count_sig && v.map { |r| r[:verb] }.sort.join(",") == verbs_sig } > 2 ? "#{namespace}/*|#{count_sig}|#{verbs_sig}" : ctrl
      end

      grouped.each do |_key, ctrls|
        if ctrls.size > 2
          namespace = ctrls.first.split("/").first
          actions = app_routes[ctrls.first]
          verbs = actions.map { |r| r[:verb] }.tally.map { |v, c| "#{c} #{v}" }.join(", ")
          short_names = ctrls.map { |c| c.split("/").last }
          lines << "- **#{namespace}/*** (#{short_names.join(', ')}) - #{count_phrase(actions.size, "route")} each (#{verbs})"
        else
          ctrls.each do |ctrl|
            actions = app_routes[ctrl]
            verbs = actions.map { |r| r[:verb] }.tally.map { |v, c| "#{c} #{v}" }.join(", ")
            lines << "- **#{ctrl}** - #{count_phrase(actions.size, "route")} (#{verbs})"
          end
        end
      end

      # Show framework routes as a compact summary
      if framework_routes.any?
        total_fw = framework_routes.values.sum(&:size)
        fw_names = framework_routes.keys.map { |k| k.split("/").first }.uniq.join(", ")
        lines << "- _#{fw_names} framework routes: #{total_fw} total_"
      end

      if routes[:api_namespaces]&.any?
        lines << "" << "API namespaces: #{routes[:api_namespaces].join(', ')}"
      end
      lines << "" << "_Use `controller:\"name\"` to see routes for a specific controller._"
      text_response(lines.join("\n"))

    when "standard"
      # List whatever survived the app_only filter. Re-splitting here
      # dropped the framework routes from the body while the header kept
      # counting them, so `app_only:false` announced 50 routes and showed
      # 24 of them.
      #
      # App controllers first: sorted plainly, `action_mailbox/` and
      # `active_storage/` lead the alphabet, so on an app with more
      # framework routes than the page limit the app's own would
      # paginate out of sight.
      ordered = by_controller.sort_by { |ctrl, _| [ framework_controller?(ctrl) ? 1 : 0, ctrl ] }
      flat_routes = ordered.flat_map { |ctrl, actions| actions.map { |r| r.merge(_ctrl: ctrl) } }
      page = paginate(flat_routes, offset: offset, limit: limit, default_limit: 150)

      lines = [ "# Routes (#{count_label})", "" ]
      current_ctrl = nil

      page[:items].each do |r|
        ctrl = r[:_ctrl]
        if ctrl != current_ctrl
          current_ctrl = ctrl
          ctrl_class = "#{ctrl.camelize}Controller"
          ctrl_data = cached_context.dig(:controllers, :controllers, ctrl_class)
          ctrl_summary = ""
          if ctrl_data
            filters = (ctrl_data[:filters] || []).map { |f| f[:name] }.first(3)
            formats = ctrl_data[:respond_to_formats]
            parts = []
            parts << "filters: #{filters.join(', ')}" if filters.any?
            parts << "formats: #{formats.join(', ')}" if formats&.any?
            ctrl_summary = " (#{parts.join(' | ')})" if parts.any?
          end
          lines << "## #{ctrl}#{ctrl_summary}"
        end

        params = r[:path].scan(/:(\w+)/).flatten
        params_part = params.any? ? " [#{params.join(', ')}]" : ""
        helper_part = if r[:name]
          args = params.any? ? "(#{params.map { |p| p == 'id' ? '@record' : ":#{p}" }.join(', ')})" : ""
          " `#{r[:name]}_path#{args}`"
        else
          ""
        end
        lines << "- `#{r[:verb]}` `#{r[:path]}` → #{r[:action]}#{helper_part}#{params_part}"
      end

      if excluded_framework_count > 0 && controller.nil?
        lines << "" << "_#{count_phrase(excluded_framework_count, "framework route")} hidden. " \
                       "Use `app_only:false` to include them._"
      end

      lines << "" << page[:hint] unless page[:hint].empty?
      text_response(lines.join("\n"))

    when "full"
      flat_routes = by_controller.sort.flat_map { |ctrl, actions| actions.map { |r| r.merge(_ctrl: ctrl) } }
      page = paginate(flat_routes, offset: offset, limit: limit, default_limit: 200)

      lines = [ "# Routes Full Detail (#{count_label})", "" ]
      lines << "| Verb | Path | Controller#Action | Name |"
      lines << "|------|------|-------------------|------|"
      page[:items].each do |r|
        lines << "| #{r[:verb]} | `#{r[:path]}` | #{r[:_ctrl]}##{r[:action]} | #{r[:name] || '-'} |"
      end
      if routes[:api_namespaces]&.any?
        lines << "" << "## API namespaces: #{routes[:api_namespaces].join(', ')}"
      end
      lines << "" << page[:hint] unless page[:hint].empty?
      text_response(lines.join("\n"))
    end
  end
end

.framework_controller?(name) ⇒ Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/rails_ai_context/tools/get_routes.rb', line 37

def self.framework_controller?(name)
  route_prefixes.any? { |p| name.downcase.start_with?(p) }
end

.route_prefixesObject



41
42
43
# File 'lib/rails_ai_context/tools/get_routes.rb', line 41

def self.route_prefixes
  RailsAiContext.configuration.excluded_route_prefixes
end