debug-agent 0.5.1 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,284 @@
1
+ require 'net/http'
2
+ require 'uri'
3
+ require 'json'
4
+ require 'time'
5
+
6
+ module DebugAgent
7
+ @tested_routes = []
8
+ @tested_routes_lock = Mutex.new
9
+
10
+ class << self
11
+ attr_reader :tested_routes
12
+
13
+ def record_tested_route(method, path, status, duration_ms)
14
+ @tested_routes_lock.synchronize do
15
+ @tested_routes << {
16
+ method: method,
17
+ path: path,
18
+ status: status,
19
+ duration_ms: duration_ms,
20
+ tested_at: Time.now.iso8601
21
+ }
22
+ @tested_routes.shift if @tested_routes.size > 500
23
+ end
24
+ end
25
+
26
+ def reset_tested_routes
27
+ @tested_routes_lock.synchronize { @tested_routes.clear }
28
+ end
29
+ end
30
+
31
+ class << self
32
+ private
33
+
34
+ def app_port
35
+ app = DebugAgent.app
36
+ if app
37
+ app_class = app.is_a?(Class) ? app : app.class
38
+ if app_class.respond_to?(:port)
39
+ return app_class.port
40
+ end
41
+ if app_class.respond_to?(:settings) && app_class.settings.respond_to?(:port)
42
+ return app_class.settings.port
43
+ end
44
+ end
45
+ # Common defaults
46
+ ENV['PORT']&.to_i || 4567
47
+ end
48
+
49
+ def app_host
50
+ 'localhost'
51
+ end
52
+
53
+ def perform_http_request(method, path, headers, body)
54
+ port = app_port
55
+ host = app_host
56
+
57
+ uri = URI("http://#{host}:#{port}#{path}")
58
+ http = Net::HTTP.new(uri.host, uri.port)
59
+ http.read_timeout = 30
60
+ http.open_timeout = 10
61
+
62
+ request_method = Net::HTTP.const_get(method.capitalize)
63
+ req = request_method.new(uri.request_uri)
64
+
65
+ # Set headers
66
+ headers&.each do |k, v|
67
+ req[k.to_s] = v.to_s
68
+ end
69
+
70
+ # Set body if provided
71
+ if body && !body.to_s.empty?
72
+ req['Content-Type'] ||= 'application/json'
73
+ req.body = body.to_s
74
+ end
75
+
76
+ start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
77
+ response = http.request(req)
78
+ duration = ((Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000).round(2)
79
+
80
+ resp_body = response.body
81
+ parsed_body = nil
82
+ begin
83
+ parsed_body = JSON.parse(resp_body) if resp_body && !resp_body.empty?
84
+ rescue JSON::ParserError
85
+ parsed_body = resp_body
86
+ end
87
+
88
+ {
89
+ status: response.code.to_i,
90
+ status_message: response.message,
91
+ headers: response.each_header.to_h,
92
+ body: parsed_body,
93
+ duration_ms: duration,
94
+ method: method,
95
+ path: path,
96
+ url: uri.to_s
97
+ }
98
+ rescue Errno::ECONNREFUSED
99
+ { error: "Connection refused — app not running on #{host}:#{app_port}" }
100
+ rescue => e
101
+ { error: "Request failed: #{e.message}", method: method, path: path }
102
+ end
103
+ end
104
+
105
+ register_tool('test_endpoint',
106
+ 'Send an HTTP request to your own running app. Returns status, headers, body, ' \
107
+ 'and duration. Useful for testing API endpoints from the debug agent',
108
+ method: { type: 'string', description: 'HTTP method: GET, POST, PUT, DELETE, PATCH', required: true },
109
+ path: { type: 'string', description: 'Request path (e.g. /api/orders)', required: true },
110
+ headers: { type: 'object', description: 'Optional HTTP headers as key-value pairs (e.g. {"X-API-Key": "demo-key-12345"})', required: false },
111
+ body: { type: 'string', description: 'Optional request body (JSON string for POST/PUT)', required: false }) do |method:, path:, headers: nil, body: nil|
112
+ method_up = method.to_s.upcase
113
+ unless %w[GET POST PUT DELETE PATCH HEAD OPTIONS].include?(method_up)
114
+ next { error: "Unsupported HTTP method: #{method}. Use GET, POST, PUT, DELETE, PATCH, HEAD, or OPTIONS." }
115
+ end
116
+
117
+ result = perform_http_request(method_up, path, headers, body)
118
+
119
+ if result[:error]
120
+ next result
121
+ end
122
+
123
+ record_tested_route(method_up, path, result[:status], result[:duration_ms])
124
+
125
+ result
126
+ rescue => e
127
+ { error: e.message }
128
+ end
129
+
130
+ register_tool('batch_test_endpoints',
131
+ 'Run multiple endpoint tests with assertions. Each test specifies method, path, ' \
132
+ 'optional headers/body, and optional assertions (expected_status, expected_body_contains)',
133
+ tests: { type: 'array', description: 'Array of test objects: {method, path, headers?, body?, expected_status?, expected_body_contains?}', required: true }) do |tests:|
134
+ unless tests.is_a?(Array)
135
+ next { error: 'tests must be an array of test objects' }
136
+ end
137
+
138
+ results = tests.map do |test|
139
+ test = test.is_a?(Hash) ? test : {}
140
+ method = (test['method'] || test[:method] || 'GET').to_s.upcase
141
+ path = test['path'] || test[:path]
142
+ headers = test['headers'] || test[:headers]
143
+ body = test['body'] || test[:body]
144
+
145
+ unless path
146
+ next { method: method, path: '(missing)', error: 'Missing required field: path' }
147
+ end
148
+
149
+ http_result = perform_http_request(method, path, headers, body)
150
+
151
+ if http_result[:error]
152
+ next { method: method, path: path, error: http_result[:error], passed: false }
153
+ end
154
+
155
+ record_tested_route(method, path, http_result[:status], http_result[:duration_ms])
156
+
157
+ # Run assertions
158
+ passed = true
159
+ failures = []
160
+
161
+ expected_status = test['expected_status'] || test[:expected_status]
162
+ if expected_status && http_result[:status] != expected_status.to_i
163
+ passed = false
164
+ failures << "Expected status #{expected_status}, got #{http_result[:status]}"
165
+ end
166
+
167
+ expected_contains = test['expected_body_contains'] || test[:expected_body_contains]
168
+ if expected_contains
169
+ body_str = http_result[:body].is_a?(String) ? http_result[:body] : JSON.generate(http_result[:body])
170
+ unless body_str.include?(expected_contains.to_s)
171
+ passed = false
172
+ failures << "Body does not contain: '#{expected_contains}'"
173
+ end
174
+ end
175
+
176
+ {
177
+ method: method,
178
+ path: path,
179
+ status: http_result[:status],
180
+ duration_ms: http_result[:duration_ms],
181
+ passed: passed,
182
+ failures: failures,
183
+ body_preview: (http_result[:body].is_a?(String) ? http_result[:body][0..200] : http_result[:body])
184
+ }
185
+ end
186
+
187
+ total = results.size
188
+ passed_count = results.count { |r| r[:passed] }
189
+ failed_count = total - passed_count
190
+
191
+ {
192
+ total: total,
193
+ passed: passed_count,
194
+ failed: failed_count,
195
+ pass_rate: total.zero? ? '0%' : format('%.0f%%', passed_count.to_f / total * 100),
196
+ results: results
197
+ }
198
+ rescue => e
199
+ { error: e.message }
200
+ end
201
+
202
+ register_tool('get_endpoint_coverage',
203
+ 'Compare registered Sinatra/Rails routes against tested routes. Shows ' \
204
+ 'which endpoints have been tested via the agent and which are untested') do
205
+ # Get all routes from the app
206
+ all_routes = []
207
+ app = DebugAgent.app
208
+
209
+ if app
210
+ app_class = app.is_a?(Class) ? app : app.class
211
+
212
+ if app_class.respond_to?(:routes)
213
+ app_class.routes.each do |method, route_list|
214
+ route_list.each do |route|
215
+ pattern = route[0]
216
+ pattern_str = case pattern
217
+ when Regexp then pattern.source
218
+ else pattern.to_s
219
+ end
220
+ all_routes << { method: method.to_s.upcase, pattern: pattern_str }
221
+ end
222
+ end
223
+ end
224
+ end
225
+
226
+ if all_routes.empty? && defined?(Sinatra) && defined?(Sinatra::Base)
227
+ Sinatra::Base.routes.each do |method, route_list|
228
+ route_list.each do |route|
229
+ pattern = route[0]
230
+ pattern_str = case pattern
231
+ when Regexp then pattern.source
232
+ else pattern.to_s
233
+ end
234
+ all_routes << { method: method.to_s.upcase, pattern: pattern_str }
235
+ end
236
+ end
237
+ end
238
+
239
+ tested = tested_routes_lock.synchronize { @tested_routes.dup }
240
+ tested_routes_set = tested.map { |t| "#{t[:method]} #{t[:path]}" }.to_set rescue tested.map { |t| "#{t[:method]} #{t[:path]}" }
241
+
242
+ # Match tested routes against app routes
243
+ covered = []
244
+ uncovered = []
245
+
246
+ all_routes.each do |route|
247
+ pattern = route[:pattern]
248
+ # Simplify regex patterns for matching (e.g. \A\/api\/orders\/(?<id>[^\/?]+) -> /api/orders)
249
+ base_pattern = pattern
250
+ .gsub(/\A\^?\\A?/, '')
251
+ .gsub(/\$?\\z?\z/, '')
252
+ .gsub(/\(\?<\w+>[^\)]+\)/, ':param')
253
+ .gsub(/\(\?:[^\)]+\)/, ':param')
254
+ .gsub(/\+|\*/, '')
255
+ .gsub(/\\\//, '/')
256
+
257
+ was_tested = tested.any? do |t|
258
+ t[:method] == route[:method] && (
259
+ t[:path] == pattern ||
260
+ t[:path].start_with?(base_pattern.gsub(/:param.*/, ''))
261
+ )
262
+ end
263
+
264
+ if was_tested
265
+ covered << route
266
+ else
267
+ uncovered << route
268
+ end
269
+ end
270
+
271
+ {
272
+ total_routes: all_routes.size,
273
+ tested_routes: tested_routes_set.size,
274
+ covered: covered.size,
275
+ uncovered: uncovered.size,
276
+ coverage_rate: all_routes.empty? ? '0%' : format('%.0f%%', covered.size.to_f / all_routes.size * 100),
277
+ covered_routes: covered,
278
+ uncovered_routes: uncovered,
279
+ recent_tests: tested.last(50)
280
+ }
281
+ rescue => e
282
+ { error: e.message }
283
+ end
284
+ end
@@ -0,0 +1,215 @@
1
+ require 'time'
2
+
3
+ module DebugAgent
4
+ # Register feature flags for inspection.
5
+ #
6
+ # DebugAgent.register_feature_flag(:new_ui, enabled: true, variant: 'v2')
7
+ @feature_flags = {}
8
+
9
+ class << self
10
+ attr_reader :feature_flags
11
+
12
+ def register_feature_flag(name, enabled:, variant: nil)
13
+ @feature_flags[name.to_s] = {
14
+ enabled: enabled,
15
+ variant: variant,
16
+ registered_at: Time.now.iso8601
17
+ }
18
+ end
19
+ end
20
+
21
+ class << self
22
+ private
23
+
24
+ def flipper_flags
25
+ return nil unless defined?(::Flipper)
26
+ begin
27
+ flipper = if ::Flipper.respond_to?(:instance)
28
+ ::Flipper.instance
29
+ elsif defined?(::Flipper::DSL)
30
+ ::Flipper
31
+ end
32
+ return nil unless flipper
33
+
34
+ flags = []
35
+ flipper.features.each do |feature|
36
+ state = feature.state
37
+ flags << {
38
+ name: feature.key,
39
+ enabled: state == :on,
40
+ variant: feature.enabled? ? 'enabled' : 'disabled',
41
+ source: 'flipper'
42
+ }
43
+ end
44
+ flags
45
+ rescue
46
+ nil
47
+ end
48
+ end
49
+
50
+ def rollout_flags
51
+ return nil unless defined?(::Rollout)
52
+ begin
53
+ r = if defined?($rollout)
54
+ $rollout
55
+ elsif ::Rollout.respond_to?(:instance)
56
+ ::Rollout.instance
57
+ end
58
+ return nil unless r
59
+
60
+ # Rollout stores features internally
61
+ flags = []
62
+ if r.respond_to?(:features)
63
+ r.features.each do |name|
64
+ flags << {
65
+ name: name.to_s,
66
+ enabled: r.active?(name),
67
+ variant: nil,
68
+ source: 'rollout'
69
+ }
70
+ end
71
+ end
72
+ flags
73
+ rescue
74
+ nil
75
+ end
76
+ end
77
+ end
78
+
79
+ register_tool('get_feature_flags',
80
+ 'List all feature flags (registered + auto-detected Flipper/Rollout). ' \
81
+ 'Shows name, enabled state, and variant') do
82
+ flags = []
83
+
84
+ # Registered flags
85
+ feature_flags.each do |name, data|
86
+ flags << {
87
+ name: name,
88
+ enabled: data[:enabled],
89
+ variant: data[:variant],
90
+ source: 'registered',
91
+ registered_at: data[:registered_at]
92
+ }
93
+ end
94
+
95
+ # Flipper detection
96
+ flipper = flipper_flags
97
+ if flipper
98
+ existing = flags.map { |f| f[:name] }
99
+ flipper.each do |f|
100
+ flags << f unless existing.include?(f[:name])
101
+ end
102
+ end
103
+
104
+ # Rollout detection
105
+ rollout = rollout_flags
106
+ if rollout
107
+ existing = flags.map { |f| f[:name] }
108
+ rollout.each do |f|
109
+ flags << f unless existing.include?(f[:name])
110
+ end
111
+ end
112
+
113
+ {
114
+ total_flags: flags.size,
115
+ enabled_count: flags.count { |f| f[:enabled] },
116
+ disabled_count: flags.count { |f| !f[:enabled] },
117
+ flags: flags,
118
+ detected_providers: {
119
+ flipper: defined?(::Flipper),
120
+ rollout: defined?(::Rollout)
121
+ }
122
+ }
123
+ rescue => e
124
+ { error: e.message }
125
+ end
126
+
127
+ register_tool('evaluate_flag',
128
+ 'Evaluate a feature flag for a given context/user. Returns enabled state ' \
129
+ 'and variant for the specified flag',
130
+ flag_name: { type: 'string', description: 'Name of the feature flag to evaluate', required: true },
131
+ user_context: { type: 'string', description: 'User/context identifier for targeted flag evaluation (optional)', required: false }) do |flag_name:, user_context: nil|
132
+ # Check registered flags first
133
+ reg = feature_flags[flag_name.to_s]
134
+ if reg
135
+ result = {
136
+ flag_name: flag_name,
137
+ enabled: reg[:enabled],
138
+ variant: reg[:variant],
139
+ source: 'registered'
140
+ }
141
+
142
+ # Context-aware evaluation for Flipper/Rollout
143
+ if user_context && defined?(::Flipper)
144
+ begin
145
+ flipper = ::Flipper.instance rescue ::Flipper
146
+ feature = flipper[flag_name.to_sym]
147
+ result[:flipper_enabled_for_user] = feature.enabled?(user_context)
148
+ result[:flipper_source] = 'flipper'
149
+ rescue
150
+ nil
151
+ end
152
+ end
153
+
154
+ if user_context && defined?(::Rollout)
155
+ begin
156
+ r = $rollout || (::Rollout.instance rescue nil)
157
+ if r
158
+ result[:rollout_active_for_user] = r.active?(flag_name.to_sym, user_context)
159
+ result[:rollout_source] = 'rollout'
160
+ end
161
+ rescue
162
+ nil
163
+ end
164
+ end
165
+
166
+ next result
167
+ end
168
+
169
+ # Try Flipper
170
+ if defined?(::Flipper)
171
+ begin
172
+ flipper = ::Flipper.instance rescue ::Flipper
173
+ feature = flipper[flag_name.to_sym]
174
+ next {
175
+ flag_name: flag_name,
176
+ enabled: feature.enabled?,
177
+ variant: nil,
178
+ source: 'flipper',
179
+ user_context: user_context,
180
+ enabled_for_user: user_context ? feature.enabled?(user_context) : nil
181
+ }
182
+ rescue
183
+ nil
184
+ end
185
+ end
186
+
187
+ # Try Rollout
188
+ if defined?(::Rollout)
189
+ begin
190
+ r = $rollout || (::Rollout.instance rescue nil)
191
+ if r
192
+ next {
193
+ flag_name: flag_name,
194
+ enabled: r.active?(flag_name.to_sym),
195
+ variant: nil,
196
+ source: 'rollout',
197
+ user_context: user_context,
198
+ enabled_for_user: user_context ? r.active?(flag_name.to_sym, user_context) : nil
199
+ }
200
+ end
201
+ rescue
202
+ nil
203
+ end
204
+ end
205
+
206
+ {
207
+ flag_name: flag_name,
208
+ enabled: false,
209
+ source: 'not_found',
210
+ error: "Flag '#{flag_name}' not found in registered flags, Flipper, or Rollout"
211
+ }
212
+ rescue => e
213
+ { error: e.message }
214
+ end
215
+ end
@@ -0,0 +1,161 @@
1
+ require 'objspace'
2
+
3
+ module DebugAgent
4
+ # Memory leak detector inspector. Records heap snapshots and compares them
5
+ # to identify object types with consistent growth.
6
+ @heap_snapshots = {}
7
+ @heap_snapshot_counter = 0
8
+
9
+ class << self
10
+ attr_reader :heap_snapshots
11
+ end
12
+
13
+ register_tool('take_heap_snapshot',
14
+ 'Take a heap snapshot recording object counts by type, heap slots, ' \
15
+ 'and GC counts. Returns a snapshot ID for later comparison.') do
16
+ counts = Hash.new(0)
17
+ ObjectSpace.each_object do |obj|
18
+ begin
19
+ name = obj.class.name || obj.class.to_s
20
+ counts[name] += 1
21
+ rescue
22
+ counts['<unknown>'] += 1
23
+ end
24
+ end
25
+
26
+ gc_stats = GC.stat
27
+ total_objects = counts.values.sum
28
+
29
+ @heap_snapshot_counter += 1
30
+ snapshot_id = "heap-#{@heap_snapshot_counter}"
31
+
32
+ snapshot = {
33
+ id: snapshot_id,
34
+ taken_at: Time.now,
35
+ object_counts: counts,
36
+ total_objects: total_objects,
37
+ live_slots: gc_stats[:heap_live_slots],
38
+ free_slots: gc_stats[:heap_free_slots],
39
+ total_slots: gc_stats[:heap_live_slots].to_i + gc_stats[:heap_free_slots].to_i,
40
+ gc_count: gc_stats[:count],
41
+ major_gc_count: gc_stats[:major_gc_count],
42
+ minor_gc_count: gc_stats[:minor_gc_count],
43
+ total_allocated_objects: gc_stats[:total_allocated_objects],
44
+ total_freed_objects: gc_stats[:total_freed_objects],
45
+ heap_pages: gc_stats[:heap_length]
46
+ }
47
+
48
+ @heap_snapshots[snapshot_id] = snapshot
49
+
50
+ {
51
+ snapshot_id: snapshot_id,
52
+ taken_at: snapshot[:taken_at].iso8601,
53
+ summary: {
54
+ total_objects: total_objects,
55
+ total_classes: counts.size,
56
+ live_slots: snapshot[:live_slots],
57
+ free_slots: snapshot[:free_slots],
58
+ gc_count: snapshot[:gc_count],
59
+ top_types: counts.sort_by { |_, v| -v }.first(10).to_h
60
+ }
61
+ }
62
+ rescue => e
63
+ { error: e.message }
64
+ end
65
+
66
+ register_tool('compare_heap_snapshots',
67
+ 'Compare two heap snapshots. Returns per-type count delta and growth ' \
68
+ 'percentage, sorted by absolute growth.',
69
+ snapshot_a: { type: 'string', description: 'First snapshot ID', required: true },
70
+ snapshot_b: { type: 'string', description: 'Second snapshot ID', required: true }) do |snapshot_a:, snapshot_b:|
71
+ snap_a = @heap_snapshots[snapshot_a.to_s]
72
+ snap_b = @heap_snapshots[snapshot_b.to_s]
73
+
74
+ next { error: "Snapshot '#{snapshot_a}' not found. Available: #{@heap_snapshots.keys.join(', ')}" } unless snap_a
75
+ next { error: "Snapshot '#{snapshot_b}' not found. Available: #{@heap_snapshots.keys.join(', ')}" } unless snap_b
76
+
77
+ counts_a = snap_a[:object_counts]
78
+ counts_b = snap_b[:object_counts]
79
+
80
+ all_types = (counts_a.keys | counts_b.keys).uniq
81
+ deltas = all_types.map do |type|
82
+ ca = counts_a[type] || 0
83
+ cb = counts_b[type] || 0
84
+ delta = cb - ca
85
+ growth_pct = ca > 0 ? (delta.to_f / ca * 100).round(2) : (delta > 0 ? Float::INFINITY : 0.0)
86
+
87
+ {
88
+ type: type,
89
+ count_before: ca,
90
+ count_after: cb,
91
+ count_delta: delta,
92
+ growth_percentage: growth_pct
93
+ }
94
+ end
95
+
96
+ # Sort by absolute growth descending
97
+ deltas.sort_by! { |d| -d[:count_delta].abs }
98
+
99
+ {
100
+ snapshot_a: snapshot_a,
101
+ snapshot_b: snapshot_b,
102
+ time_between: (snap_b[:taken_at] - snap_a[:taken_at]).round(2),
103
+ summary: {
104
+ total_objects_before: snap_a[:total_objects],
105
+ total_objects_after: snap_b[:total_objects],
106
+ net_delta: snap_b[:total_objects] - snap_a[:total_objects],
107
+ gc_runs_between: snap_b[:gc_count] - snap_a[:gc_count],
108
+ live_slots_delta: snap_b[:live_slots] - snap_a[:live_slots]
109
+ },
110
+ type_changes: deltas.first(50)
111
+ }
112
+ rescue => e
113
+ { error: e.message }
114
+ end
115
+
116
+ register_tool('get_leak_candidates',
117
+ 'Identify object types with consistent growth across stored snapshots. ' \
118
+ 'Shows top growing object types.') do |snapshot_limit: 10|
119
+ next { error: 'Need at least 2 snapshots to detect trends' } if @heap_snapshots.size < 2
120
+
121
+ snapshots = @heap_snapshots.values.sort_by { |s| s[:taken_at] }
122
+ snapshots = snapshots.last([snapshot_limit.to_i, 2].max)
123
+
124
+ # For each type, compute growth across consecutive snapshot pairs
125
+ type_growth = Hash.new { |h, k| h[k] = { deltas: [], total_growth: 0 } }
126
+
127
+ snapshots.each_cons(2) do |s1, s2|
128
+ all_types = (s1[:object_counts].keys | s2[:object_counts].keys)
129
+ all_types.each do |type|
130
+ c1 = s1[:object_counts][type] || 0
131
+ c2 = s2[:object_counts][type] || 0
132
+ delta = c2 - c1
133
+ type_growth[type][:deltas] << delta
134
+ type_growth[type][:total_growth] += delta
135
+ end
136
+ end
137
+
138
+ candidates = type_growth
139
+ .select { |_, g| g[:total_growth] > 0 && g[:deltas].all? { |d| d >= 0 } }
140
+ .map do |type, g|
141
+ {
142
+ type: type,
143
+ total_growth: g[:total_growth],
144
+ snapshots_growing: g[:deltas].count(&:positive?),
145
+ total_snapshots_compared: g[:deltas].size,
146
+ consistency: g[:deltas].all?(&:positive?) ? 'consistent' : 'partial',
147
+ per_period_deltas: g[:deltas]
148
+ }
149
+ end
150
+ .sort_by { |c| -c[:total_growth] }
151
+
152
+ {
153
+ snapshots_analyzed: snapshots.size,
154
+ first_snapshot: snapshots.first[:id],
155
+ last_snapshot: snapshots.last[:id],
156
+ leak_candidates: candidates.first(20)
157
+ }
158
+ rescue => e
159
+ { error: e.message }
160
+ end
161
+ end