aia 2.0.0.0.pre.beta2 → 2.0.1

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.
Files changed (227) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +152 -223
  3. data/README.md +41 -18
  4. data/bin/aia +8 -3
  5. data/lib/aia/aia_completion.bash +2 -3
  6. data/lib/aia/aia_completion.fish +6 -5
  7. data/lib/aia/aia_completion.zsh +2 -3
  8. data/lib/aia/chat_loop.rb +16 -14
  9. data/lib/aia/config/cli_parser.rb +123 -91
  10. data/lib/aia/config/defaults.yml +18 -40
  11. data/lib/aia/config/mcp_parser.rb +30 -36
  12. data/lib/aia/config/model_spec.rb +8 -14
  13. data/lib/aia/config/validator.rb +102 -103
  14. data/lib/aia/config/value_caster.rb +76 -0
  15. data/lib/aia/config.rb +70 -53
  16. data/lib/aia/crew.rb +29 -19
  17. data/lib/aia/debate_handler.rb +27 -10
  18. data/lib/aia/directives/configuration_directives.rb +55 -14
  19. data/lib/aia/directives/context_directives.rb +24 -12
  20. data/lib/aia/directives/execution_directives.rb +18 -23
  21. data/lib/aia/directives/model_directives.rb +41 -104
  22. data/lib/aia/directives/utility_directives.rb +16 -17
  23. data/lib/aia/directives/web_and_file_directives.rb +21 -14
  24. data/lib/aia/fact_asserter.rb +3 -3
  25. data/lib/aia/history_transfer.rb +64 -24
  26. data/lib/aia/logger.rb +14 -46
  27. data/lib/aia/mcp_config_normalizer.rb +27 -14
  28. data/lib/aia/mcp_connection_manager.rb +181 -184
  29. data/lib/aia/mcp_discovery.rb +43 -15
  30. data/lib/aia/mcp_grouper.rb +2 -1
  31. data/lib/aia/mcp_server_config.rb +20 -2
  32. data/lib/aia/mcp_utility.rb +24 -19
  33. data/lib/aia/mention_router.rb +15 -2
  34. data/lib/aia/modality_query.rb +36 -0
  35. data/lib/aia/model_alias_registry.rb +11 -11
  36. data/lib/aia/model_registry.rb +75 -0
  37. data/lib/aia/network_builder.rb +8 -7
  38. data/lib/aia/patches/mcp_stdio_stderr.rb +102 -0
  39. data/lib/aia/patches/ruby_llm_streaming_error.rb +21 -4
  40. data/lib/aia/patches/ruby_llm_tool_param_compat.rb +18 -0
  41. data/lib/aia/pipeline_orchestrator.rb +71 -38
  42. data/lib/aia/prompt_decomposer.rb +1 -1
  43. data/lib/aia/prompt_handler.rb +56 -29
  44. data/lib/aia/provider_registry.rb +105 -0
  45. data/lib/aia/robot_builder.rb +1 -1
  46. data/lib/aia/robot_factory.rb +67 -63
  47. data/lib/aia/robot_sync.rb +79 -0
  48. data/lib/aia/role_catalog.rb +89 -0
  49. data/lib/aia/session.rb +25 -11
  50. data/lib/aia/skill_utils.rb +60 -19
  51. data/lib/aia/spawn_handler.rb +16 -4
  52. data/lib/aia/spawn_spec_parser.rb +6 -7
  53. data/lib/aia/special_mode_handler.rb +28 -25
  54. data/lib/aia/speech.rb +70 -34
  55. data/lib/aia/startup_coordinator.rb +17 -92
  56. data/lib/aia/streaming_runner.rb +10 -2
  57. data/lib/aia/system_prompt_assembler.rb +12 -11
  58. data/lib/aia/task_board.rb +60 -0
  59. data/lib/aia/tool_approver.rb +205 -0
  60. data/lib/aia/tool_filter.rb +1 -10
  61. data/lib/aia/tool_filter_strategy.rb +12 -1
  62. data/lib/aia/tool_introspection.rb +9 -1
  63. data/lib/aia/tool_loader.rb +67 -33
  64. data/lib/aia/tool_utility.rb +6 -5
  65. data/lib/aia/tools/delegate_to_foreman_tool.rb +6 -4
  66. data/lib/aia/tools/recruit_robot_tool.rb +12 -12
  67. data/lib/aia/tools/reskill_robot_tool.rb +7 -7
  68. data/lib/aia/tools/task_board_tool.rb +16 -16
  69. data/lib/aia/trakflow_bridge.rb +14 -8
  70. data/lib/aia/turn_state.rb +31 -8
  71. data/lib/aia/ui_presenter.rb +16 -0
  72. data/lib/aia/utility.rb +6 -24
  73. data/lib/aia/variable_input_collector.rb +0 -3
  74. data/lib/aia/verification_network.rb +9 -10
  75. data/lib/aia/version.rb +1 -9
  76. data/lib/aia.rb +34 -8
  77. metadata +20 -161
  78. data/.better-commits.json +0 -150
  79. data/.config/tocer/configuration.yml +0 -6
  80. data/.envrc +0 -19
  81. data/.loki +0 -11
  82. data/.reek.yml +0 -160
  83. data/.rubocop.yml +0 -116
  84. data/.rubocop_strict.yml +0 -15
  85. data/.version +0 -1
  86. data/COMMITS.md +0 -196
  87. data/IMPLEMENTATION_PLAN.md +0 -506
  88. data/Rakefile +0 -47
  89. data/_typos.toml +0 -10
  90. data/aia.gemspec +0 -92
  91. data/architecture_review.md +0 -314
  92. data/config/aia.yml +0 -13
  93. data/docs/AGENTS.md +0 -40
  94. data/docs/advanced-prompting.md +0 -814
  95. data/docs/assets/images/aia.png +0 -0
  96. data/docs/cli-reference.md +0 -1241
  97. data/docs/configuration.md +0 -747
  98. data/docs/contributing.md +0 -386
  99. data/docs/directives-reference.md +0 -1145
  100. data/docs/examples/index.md +0 -277
  101. data/docs/examples/mcp/index.md +0 -475
  102. data/docs/examples/prompts/analysis/index.md +0 -78
  103. data/docs/examples/prompts/automation/index.md +0 -109
  104. data/docs/examples/prompts/development/index.md +0 -125
  105. data/docs/examples/prompts/index.md +0 -333
  106. data/docs/examples/prompts/learning/index.md +0 -127
  107. data/docs/examples/prompts/writing/index.md +0 -62
  108. data/docs/examples/tools/index.md +0 -282
  109. data/docs/faq.md +0 -578
  110. data/docs/guides/available-models.md +0 -366
  111. data/docs/guides/basic-usage.md +0 -478
  112. data/docs/guides/chat.md +0 -680
  113. data/docs/guides/crew.md +0 -239
  114. data/docs/guides/executable-prompts.md +0 -331
  115. data/docs/guides/first-prompt.md +0 -454
  116. data/docs/guides/getting-started.md +0 -455
  117. data/docs/guides/image-generation.md +0 -507
  118. data/docs/guides/index.md +0 -48
  119. data/docs/guides/local-models.md +0 -306
  120. data/docs/guides/migrate-prompts.md +0 -335
  121. data/docs/guides/models.md +0 -1017
  122. data/docs/guides/shared-tools.md +0 -254
  123. data/docs/guides/tools.md +0 -831
  124. data/docs/index.md +0 -259
  125. data/docs/installation.md +0 -274
  126. data/docs/mcp-integration.md +0 -603
  127. data/docs/prompt_management.md +0 -665
  128. data/docs/security.md +0 -674
  129. data/docs/special_projects_guide.md +0 -386
  130. data/docs/tools-and-mcp-examples.md +0 -1211
  131. data/docs/workflows-and-pipelines.md +0 -636
  132. data/examples/.gitignore +0 -2
  133. data/examples/00_setup_aia.sh +0 -111
  134. data/examples/01_basic_usage.sh +0 -23
  135. data/examples/02_frontmatter.sh +0 -33
  136. data/examples/03_shell_integration.sh +0 -55
  137. data/examples/04_erb_templating.sh +0 -56
  138. data/examples/05_shell_then_erb.sh +0 -38
  139. data/examples/06_prompt_chaining.sh +0 -59
  140. data/examples/07_pipeline.sh +0 -46
  141. data/examples/08_context_files.sh +0 -43
  142. data/examples/09_roles.sh +0 -67
  143. data/examples/10_stdin_piping.sh +0 -49
  144. data/examples/11_multi_model.sh +0 -65
  145. data/examples/12_token_usage.sh +0 -52
  146. data/examples/13_cost_tracking.sh +0 -68
  147. data/examples/14_output_file.sh +0 -91
  148. data/examples/15_parameters.sh +0 -68
  149. data/examples/16_directives.sh +0 -113
  150. data/examples/17_require_and_conditionals.sh +0 -68
  151. data/examples/18_tools.sh +0 -61
  152. data/examples/19_local_tools.sh +0 -34
  153. data/examples/20_mcp_servers.sh +0 -102
  154. data/examples/21_executable_prompts.sh +0 -78
  155. data/examples/22_chat_mode.sh +0 -217
  156. data/examples/23_verify.sh +0 -139
  157. data/examples/24_decompose.sh +0 -139
  158. data/examples/25_spawn.sh +0 -139
  159. data/examples/26_debate.sh +0 -97
  160. data/examples/27_mention_routing.sh +0 -157
  161. data/examples/28_model_switching.sh +0 -106
  162. data/examples/29_agent_harness.sh +0 -177
  163. data/examples/README.md +0 -321
  164. data/examples/advanced_multi_robot_capabilities_without_examples.md +0 -106
  165. data/examples/aia_config.yml +0 -22
  166. data/examples/aia_config_orchestrator.yml +0 -45
  167. data/examples/aia_config_with_mcp.yml +0 -21
  168. data/examples/common.sh +0 -39
  169. data/examples/context/project_goals.md +0 -6
  170. data/examples/context/tech_stack.md +0 -7
  171. data/examples/directives/timestamp_directive.rb +0 -22
  172. data/examples/mcp/filesystem.json +0 -9
  173. data/examples/prompts_dir/analyze.md +0 -2
  174. data/examples/prompts_dir/brainstorm.md +0 -2
  175. data/examples/prompts_dir/conditional.md +0 -17
  176. data/examples/prompts_dir/creative.md +0 -4
  177. data/examples/prompts_dir/erbinfo.md +0 -5
  178. data/examples/prompts_dir/erbinfo_raw.md +0 -8
  179. data/examples/prompts_dir/evaluate.md +0 -2
  180. data/examples/prompts_dir/explain_joke.md +0 -1
  181. data/examples/prompts_dir/explain_recursion.md +0 -1
  182. data/examples/prompts_dir/fun_fact +0 -3
  183. data/examples/prompts_dir/greeting.md +0 -8
  184. data/examples/prompts_dir/greeting_required.md +0 -7
  185. data/examples/prompts_dir/hello.md +0 -1
  186. data/examples/prompts_dir/includes/ruby_facts.md +0 -4
  187. data/examples/prompts_dir/limerick.md +0 -1
  188. data/examples/prompts_dir/list_with_mcp.md +0 -3
  189. data/examples/prompts_dir/pick_best.md +0 -2
  190. data/examples/prompts_dir/project_summary +0 -12
  191. data/examples/prompts_dir/quiz_with_include.md +0 -6
  192. data/examples/prompts_dir/require_demo.md +0 -5
  193. data/examples/prompts_dir/roles/formal.md +0 -3
  194. data/examples/prompts_dir/roles/orchestrator.md +0 -21
  195. data/examples/prompts_dir/roles/pirate.md +0 -3
  196. data/examples/prompts_dir/shell_then_erb.md +0 -6
  197. data/examples/prompts_dir/sort_compare.md +0 -2
  198. data/examples/prompts_dir/summarize_context.md +0 -2
  199. data/examples/prompts_dir/sysinfo.md +0 -5
  200. data/examples/prompts_dir/sysinfo_raw.md +0 -8
  201. data/examples/prompts_dir/tagline.md +0 -1
  202. data/examples/prompts_dir/tell_joke.md +0 -1
  203. data/examples/prompts_dir/tell_joke_with_next.md +0 -4
  204. data/examples/prompts_dir/use_local_tool.md +0 -8
  205. data/examples/prompts_dir/use_tools.md +0 -8
  206. data/examples/prompts_dir/weather.md +0 -2
  207. data/examples/prompts_dir/whats_new.md +0 -2
  208. data/examples/prompts_dir/with_timestamp.md +0 -5
  209. data/examples/requirements/sinatra_taskflow_app.md +0 -139
  210. data/examples/rules/01_classify_ruby.rb +0 -16
  211. data/examples/rules/02_prefer_claude_for_code.rb +0 -19
  212. data/examples/rules/03_gate_prompt_length.rb +0 -19
  213. data/examples/rules/04_tool_selection.rb +0 -41
  214. data/examples/rules/README.md +0 -30
  215. data/examples/run_all.sh +0 -294
  216. data/examples/tools/word_count_tool.rb +0 -30
  217. data/lib/AGENTS.md +0 -57
  218. data/lib/aia/model_switch_handler.rb +0 -100
  219. data/mcp_servers/README.md +0 -110
  220. data/mcp_servers/apple-mcp.json +0 -8
  221. data/mcp_servers/filesystem.json +0 -9
  222. data/mcp_servers/mcp_server_chart.json +0 -11
  223. data/mcp_servers/playwright_one.json +0 -8
  224. data/mcp_servers/playwright_server_definition.json +0 -9
  225. data/mcp_servers/playwright_two.json +0 -8
  226. data/mcp_servers/tavily_mcp_server.json +0 -8
  227. data/mkdocs.yml +0 -169
@@ -1,1211 +0,0 @@
1
- <!-- Tocer[start]: Auto-generated, don't remove. -->
2
-
3
- ## Table of Contents
4
-
5
- - [Tools and MCP Examples](#tools-and-mcp-examples)
6
- - [Real-World Tool Examples](#real-world-tool-examples)
7
- - [File Processing Tools](#file-processing-tools)
8
- - [Advanced Log Analyzer](#advanced-log-analyzer)
9
- - [Configuration File Manager](#configuration-file-manager)
10
- - [Development Tools](#development-tools)
11
- - [Code Quality Analyzer](#code-quality-analyzer)
12
- - [MCP Integration Examples](#mcp-integration-examples)
13
- - [GitHub Repository Analyzer MCP](#github-repository-analyzer-mcp)
14
- - [Database Schema Analyzer MCP](#database-schema-analyzer-mcp)
15
- - [Integration Workflows](#integration-workflows)
16
- - [Full-Stack Application Analysis](#full-stack-application-analysis)
17
- - [DevOps Pipeline Assessment](#devops-pipeline-assessment)
18
- - [Advanced Integration Patterns](#advanced-integration-patterns)
19
- - [Multi-Environment Consistency Checker](#multi-environment-consistency-checker)
20
- - [Related Documentation](#related-documentation)
21
-
22
- <!-- Tocer[finish]: Auto-generated, don't remove. -->
23
-
24
- # Tools and MCP Examples
25
-
26
- This comprehensive collection showcases real-world examples of RubyLLM tools and MCP client integrations, demonstrating practical applications and advanced techniques.
27
-
28
- ## Real-World Tool Examples
29
-
30
- ### File Processing Tools
31
-
32
- #### Advanced Log Analyzer
33
- ```ruby
34
- # ~/.config/aia/tools/log_analyzer.rb
35
- require 'time'
36
- require 'json'
37
-
38
- class LogAnalyzer < RubyLLM::Tool
39
- description "Analyzes log files for patterns, errors, and performance metrics"
40
-
41
- def analyze_logs(log_file, time_range = "24h", error_threshold = 10)
42
- return "Log file not found: #{log_file}" unless File.exist?(log_file)
43
-
44
- logs = parse_log_file(log_file)
45
- filtered_logs = filter_by_time(logs, time_range)
46
-
47
- analysis = {
48
- total_entries: filtered_logs.length,
49
- error_count: count_errors(filtered_logs),
50
- warning_count: count_warnings(filtered_logs),
51
- top_errors: find_top_errors(filtered_logs, 5),
52
- performance_stats: calculate_performance_stats(filtered_logs),
53
- anomalies: detect_anomalies(filtered_logs),
54
- recommendations: generate_recommendations(filtered_logs, error_threshold)
55
- }
56
-
57
- JSON.pretty_generate(analysis)
58
- end
59
-
60
- def extract_error_patterns(log_file, pattern_limit = 10)
61
- return "Log file not found: #{log_file}" unless File.exist?(log_file)
62
-
63
- errors = []
64
- File.foreach(log_file) do |line|
65
- if line.match?(/ERROR|FATAL|EXCEPTION/i)
66
- errors << extract_error_context(line)
67
- end
68
- end
69
-
70
- patterns = group_similar_errors(errors)
71
- top_patterns = patterns.sort_by { |_, count| -count }.first(pattern_limit)
72
-
73
- {
74
- total_errors: errors.length,
75
- unique_patterns: patterns.length,
76
- top_patterns: top_patterns.map { |pattern, count|
77
- { pattern: pattern, occurrences: count, severity: assess_severity(pattern) }
78
- }
79
- }.to_json
80
- end
81
-
82
- def performance_report(log_file, metric = "response_time")
83
- logs = parse_log_file(log_file)
84
- performance_data = extract_performance_data(logs, metric)
85
-
86
- return "No performance data found for metric: #{metric}" if performance_data.empty?
87
-
88
- stats = calculate_detailed_stats(performance_data)
89
- percentiles = calculate_percentiles(performance_data)
90
- trends = analyze_trends(performance_data)
91
-
92
- {
93
- metric: metric,
94
- statistics: stats,
95
- percentiles: percentiles,
96
- trends: trends,
97
- alerts: generate_performance_alerts(stats, percentiles)
98
- }.to_json
99
- end
100
-
101
- private
102
-
103
- def parse_log_file(file_path)
104
- logs = []
105
- File.foreach(file_path) do |line|
106
- parsed = parse_log_line(line.strip)
107
- logs << parsed if parsed
108
- end
109
- logs
110
- end
111
-
112
- def parse_log_line(line)
113
- # Support multiple log formats
114
- formats = [
115
- /^(?<timestamp>\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}) \[(?<level>\w+)\] (?<message>.*)/,
116
- /^(?<level>\w+) (?<timestamp>\w{3} \d{2} \d{2}:\d{2}:\d{2}) (?<message>.*)/,
117
- /^\[(?<timestamp>.*?)\] (?<level>\w+): (?<message>.*)/
118
- ]
119
-
120
- formats.each do |format|
121
- match = line.match(format)
122
- if match
123
- return {
124
- timestamp: parse_timestamp(match[:timestamp]),
125
- level: match[:level].upcase,
126
- message: match[:message],
127
- raw: line
128
- }
129
- end
130
- end
131
-
132
- nil # Unable to parse
133
- end
134
-
135
- def filter_by_time(logs, time_range)
136
- cutoff = case time_range
137
- when /(\d+)h/ then Time.now - ($1.to_i * 3600)
138
- when /(\d+)d/ then Time.now - ($1.to_i * 86400)
139
- when /(\d+)m/ then Time.now - ($1.to_i * 60)
140
- else Time.now - 86400 # Default: 24 hours
141
- end
142
-
143
- logs.select { |log| log[:timestamp] && log[:timestamp] > cutoff }
144
- end
145
-
146
- def count_errors(logs)
147
- logs.count { |log| ['ERROR', 'FATAL', 'CRITICAL'].include?(log[:level]) }
148
- end
149
-
150
- def count_warnings(logs)
151
- logs.count { |log| log[:level] == 'WARN' || log[:level] == 'WARNING' }
152
- end
153
-
154
- def find_top_errors(logs, limit)
155
- error_logs = logs.select { |log| ['ERROR', 'FATAL'].include?(log[:level]) }
156
- error_groups = error_logs.group_by { |log| normalize_error_message(log[:message]) }
157
-
158
- error_groups.map { |error, occurrences|
159
- {
160
- error: error,
161
- count: occurrences.length,
162
- first_seen: occurrences.map { |o| o[:timestamp] }.min,
163
- last_seen: occurrences.map { |o| o[:timestamp] }.max,
164
- sample: occurrences.first[:raw]
165
- }
166
- }.sort_by { |e| -e[:count] }.first(limit)
167
- end
168
-
169
- def detect_anomalies(logs)
170
- anomalies = []
171
-
172
- # Detect error spikes
173
- hourly_errors = group_by_hour(logs.select { |l| l[:level] == 'ERROR' })
174
- avg_errors = hourly_errors.values.sum.to_f / hourly_errors.length
175
-
176
- hourly_errors.each do |hour, count|
177
- if count > avg_errors * 3 # 3x average is anomalous
178
- anomalies << {
179
- type: 'error_spike',
180
- hour: hour,
181
- count: count,
182
- severity: 'high'
183
- }
184
- end
185
- end
186
-
187
- # Detect unusual silence periods
188
- if hourly_errors.values.any? { |count| count == 0 }
189
- anomalies << {
190
- type: 'unusual_silence',
191
- description: 'Periods with zero activity detected',
192
- severity: 'medium'
193
- }
194
- end
195
-
196
- anomalies
197
- end
198
- end
199
- ```
200
-
201
- #### Configuration File Manager
202
- ```ruby
203
- # ~/.config/aia/tools/config_manager.rb
204
- require 'yaml'
205
- require 'json'
206
- require 'fileutils'
207
-
208
- class ConfigManager < RubyLLM::Tool
209
- description "Manages configuration files across different formats (YAML, JSON, ENV)"
210
-
211
- def analyze_config(config_file)
212
- return "Config file not found: #{config_file}" unless File.exist?(config_file)
213
-
214
- format = detect_format(config_file)
215
- config_data = load_config(config_file, format)
216
-
217
- analysis = {
218
- file: config_file,
219
- format: format,
220
- structure: analyze_structure(config_data),
221
- security: security_analysis(config_data),
222
- completeness: completeness_check(config_data),
223
- recommendations: generate_config_recommendations(config_data, format)
224
- }
225
-
226
- JSON.pretty_generate(analysis)
227
- end
228
-
229
- def validate_config(config_file, schema_file = nil)
230
- return "Config file not found: #{config_file}" unless File.exist?(config_file)
231
-
232
- format = detect_format(config_file)
233
- config_data = load_config(config_file, format)
234
-
235
- validation_results = {
236
- syntax_valid: true,
237
- structure_issues: [],
238
- security_issues: [],
239
- recommendations: []
240
- }
241
-
242
- # Syntax validation
243
- begin
244
- load_config(config_file, format)
245
- rescue => e
246
- validation_results[:syntax_valid] = false
247
- validation_results[:structure_issues] << "Syntax error: #{e.message}"
248
- end
249
-
250
- # Security validation
251
- security_issues = find_security_issues(config_data)
252
- validation_results[:security_issues] = security_issues
253
-
254
- # Schema validation if provided
255
- if schema_file && File.exist?(schema_file)
256
- schema_validation = validate_against_schema(config_data, schema_file)
257
- validation_results[:schema_validation] = schema_validation
258
- end
259
-
260
- JSON.pretty_generate(validation_results)
261
- end
262
-
263
- def merge_configs(base_config, override_config, output_file = nil)
264
- base_format = detect_format(base_config)
265
- override_format = detect_format(override_config)
266
-
267
- base_data = load_config(base_config, base_format)
268
- override_data = load_config(override_config, override_format)
269
-
270
- merged_data = deep_merge(base_data, override_data)
271
-
272
- if output_file
273
- output_format = detect_format(output_file)
274
- save_config(merged_data, output_file, output_format)
275
- "Configuration merged and saved to: #{output_file}"
276
- else
277
- JSON.pretty_generate(merged_data)
278
- end
279
- end
280
-
281
- def extract_secrets(config_file, patterns = nil)
282
- content = File.read(config_file)
283
-
284
- default_patterns = [
285
- /password\s*[:=]\s*["']?([^"'\s]+)["']?/i,
286
- /api[_-]?key\s*[:=]\s*["']?([^"'\s]+)["']?/i,
287
- /secret\s*[:=]\s*["']?([^"'\s]+)["']?/i,
288
- /token\s*[:=]\s*["']?([^"'\s]+)["']?/i,
289
- /database_url\s*[:=]\s*["']?([^"'\s]+)["']?/i
290
- ]
291
-
292
- patterns ||= default_patterns
293
- secrets = []
294
-
295
- patterns.each do |pattern|
296
- content.scan(pattern) do |match|
297
- secrets << {
298
- type: detect_secret_type(pattern),
299
- value: mask_secret(match[0]),
300
- line: content.lines.find_index { |line| line.include?(match[0]) } + 1,
301
- severity: assess_secret_severity(match[0])
302
- }
303
- end
304
- end
305
-
306
- {
307
- file: config_file,
308
- secrets_found: secrets.length,
309
- secrets: secrets,
310
- recommendations: generate_secret_recommendations(secrets)
311
- }.to_json
312
- end
313
-
314
- private
315
-
316
- def detect_format(file_path)
317
- ext = File.extname(file_path).downcase
318
- case ext
319
- when '.yml', '.yaml' then 'yaml'
320
- when '.json' then 'json'
321
- when '.env' then 'env'
322
- when '.ini' then 'ini'
323
- else
324
- # Try to detect from content
325
- content = File.read(file_path).strip
326
- return 'json' if content.start_with?('{') || content.start_with?('[')
327
- return 'yaml' if content.match?(/^\w+:/)
328
- return 'env' if content.match?(/^\w+=/)
329
- 'unknown'
330
- end
331
- end
332
-
333
- def load_config(file_path, format)
334
- content = File.read(file_path)
335
-
336
- case format
337
- when 'yaml'
338
- YAML.safe_load(content)
339
- when 'json'
340
- JSON.parse(content)
341
- when 'env'
342
- parse_env_file(content)
343
- else
344
- { raw_content: content }
345
- end
346
- end
347
-
348
- def parse_env_file(content)
349
- env_vars = {}
350
- content.lines.each do |line|
351
- line = line.strip
352
- next if line.empty? || line.start_with?('#')
353
-
354
- key, value = line.split('=', 2)
355
- env_vars[key] = value&.gsub(/^["']|["']$/, '') if key
356
- end
357
- env_vars
358
- end
359
-
360
- def deep_merge(base, override)
361
- base.merge(override) do |key, base_val, override_val|
362
- if base_val.is_a?(Hash) && override_val.is_a?(Hash)
363
- deep_merge(base_val, override_val)
364
- else
365
- override_val
366
- end
367
- end
368
- end
369
- end
370
- ```
371
-
372
- ### Development Tools
373
-
374
- #### Code Quality Analyzer
375
- ```ruby
376
- # ~/.config/aia/tools/code_quality.rb
377
- class CodeQualityAnalyzer < RubyLLM::Tool
378
- description "Analyzes code quality metrics, complexity, and best practices"
379
-
380
- def analyze_codebase(directory, language = nil)
381
- return "Directory not found: #{directory}" unless Dir.exist?(directory)
382
-
383
- files = find_code_files(directory, language)
384
- return "No code files found" if files.empty?
385
-
386
- results = {
387
- summary: {
388
- total_files: files.length,
389
- total_lines: 0,
390
- languages: {}
391
- },
392
- quality_metrics: {},
393
- issues: [],
394
- recommendations: []
395
- }
396
-
397
- files.each do |file|
398
- file_analysis = analyze_file(file)
399
- results[:summary][:total_lines] += file_analysis[:line_count]
400
-
401
- lang = detect_language(file)
402
- results[:summary][:languages][lang] ||= 0
403
- results[:summary][:languages][lang] += 1
404
-
405
- results[:quality_metrics][file] = file_analysis
406
- results[:issues].concat(file_analysis[:issues])
407
- end
408
-
409
- results[:recommendations] = generate_recommendations(results)
410
- JSON.pretty_generate(results)
411
- end
412
-
413
- def calculate_complexity(file_path)
414
- return "File not found: #{file_path}" unless File.exist?(file_path)
415
-
416
- content = File.read(file_path)
417
- language = detect_language(file_path)
418
-
419
- complexity = case language
420
- when 'ruby'
421
- calculate_ruby_complexity(content)
422
- when 'python'
423
- calculate_python_complexity(content)
424
- when 'javascript'
425
- calculate_js_complexity(content)
426
- else
427
- calculate_generic_complexity(content)
428
- end
429
-
430
- {
431
- file: file_path,
432
- language: language,
433
- cyclomatic_complexity: complexity[:cyclomatic],
434
- cognitive_complexity: complexity[:cognitive],
435
- maintainability_index: complexity[:maintainability],
436
- complexity_rating: rate_complexity(complexity[:cyclomatic])
437
- }.to_json
438
- end
439
-
440
- def check_best_practices(file_path)
441
- return "File not found: #{file_path}" unless File.exist?(file_path)
442
-
443
- content = File.read(file_path)
444
- language = detect_language(file_path)
445
-
446
- violations = []
447
-
448
- case language
449
- when 'ruby'
450
- violations.concat(check_ruby_practices(content))
451
- when 'python'
452
- violations.concat(check_python_practices(content))
453
- when 'javascript'
454
- violations.concat(check_js_practices(content))
455
- end
456
-
457
- # Generic checks
458
- violations.concat(check_generic_practices(content, file_path))
459
-
460
- {
461
- file: file_path,
462
- language: language,
463
- violations: violations,
464
- score: calculate_practice_score(violations),
465
- recommendations: prioritize_fixes(violations)
466
- }.to_json
467
- end
468
-
469
- private
470
-
471
- def find_code_files(directory, language = nil)
472
- extensions = if language
473
- language_extensions(language)
474
- else
475
- %w[.rb .py .js .java .cpp .c .go .rs .php .cs .swift .kt]
476
- end
477
-
478
- Dir.glob("#{directory}/**/*").select do |file|
479
- File.file?(file) && extensions.include?(File.extname(file).downcase)
480
- end
481
- end
482
-
483
- def analyze_file(file_path)
484
- content = File.read(file_path)
485
- lines = content.lines
486
-
487
- {
488
- file: file_path,
489
- line_count: lines.length,
490
- blank_lines: lines.count(&:strip.empty?),
491
- comment_lines: count_comment_lines(content, detect_language(file_path)),
492
- complexity: calculate_complexity_metrics(content),
493
- issues: find_code_issues(content, file_path),
494
- maintainability: assess_maintainability(content)
495
- }
496
- end
497
-
498
- def calculate_ruby_complexity(content)
499
- # Simplified Ruby complexity calculation
500
- cyclomatic = 1 # Base complexity
501
-
502
- # Add complexity for control structures
503
- cyclomatic += content.scan(/\b(if|unless|while|until|for|case|rescue)\b/).length
504
- cyclomatic += content.scan(/&&|\|\|/).length
505
- cyclomatic += content.scan(/\?.*:/).length # Ternary operators
506
-
507
- # Method definitions add complexity
508
- method_count = content.scan(/def\s+\w+/).length
509
-
510
- {
511
- cyclomatic: cyclomatic,
512
- cognitive: calculate_cognitive_complexity(content, 'ruby'),
513
- maintainability: calculate_maintainability_index(content, cyclomatic),
514
- method_count: method_count
515
- }
516
- end
517
-
518
- def check_ruby_practices(content)
519
- violations = []
520
-
521
- # Check for long methods (>20 lines)
522
- methods = content.scan(/def\s+\w+.*?end/m)
523
- methods.each do |method|
524
- if method.lines.length > 20
525
- violations << {
526
- type: 'long_method',
527
- severity: 'medium',
528
- message: 'Method exceeds 20 lines',
529
- line: find_line_number(content, method)
530
- }
531
- end
532
- end
533
-
534
- # Check for deep nesting
535
- max_indent = content.lines.map { |line| line.match(/^\s*/)[0].length }.max
536
- if max_indent > 8
537
- violations << {
538
- type: 'deep_nesting',
539
- severity: 'medium',
540
- message: 'Excessive nesting detected',
541
- max_depth: max_indent / 2
542
- }
543
- end
544
-
545
- # Check for missing documentation
546
- if !content.match?(/^#.*/) && content.match?(/class\s+\w+/)
547
- violations << {
548
- type: 'missing_documentation',
549
- severity: 'low',
550
- message: 'Class lacks documentation'
551
- }
552
- end
553
-
554
- violations
555
- end
556
-
557
- def generate_recommendations(analysis_results)
558
- recommendations = []
559
-
560
- # File count recommendations
561
- if analysis_results[:summary][:total_files] > 100
562
- recommendations << "Consider organizing large codebase into modules or packages"
563
- end
564
-
565
- # Language diversity
566
- if analysis_results[:summary][:languages].keys.length > 3
567
- recommendations << "High language diversity may increase maintenance complexity"
568
- end
569
-
570
- # Quality-based recommendations
571
- high_complexity_files = analysis_results[:quality_metrics].select do |file, metrics|
572
- metrics[:complexity][:cyclomatic] > 10
573
- end
574
-
575
- if high_complexity_files.any?
576
- recommendations << "#{high_complexity_files.length} files have high complexity - consider refactoring"
577
- end
578
-
579
- recommendations
580
- end
581
- end
582
- ```
583
-
584
- ## MCP Integration Examples
585
-
586
- ### GitHub Repository Analyzer MCP
587
- ```python
588
- # github_analyzer_mcp.py
589
- import asyncio
590
- import os
591
- from mcp.server import Server
592
- from mcp.types import Resource, Tool, TextContent
593
- import aiohttp
594
- import json
595
- from datetime import datetime, timedelta
596
-
597
- server = Server("github-analyzer", "1.0.0")
598
-
599
- class GitHubAnalyzer:
600
- def __init__(self, token):
601
- self.token = token
602
- self.headers = {
603
- 'Authorization': f'token {token}',
604
- 'Accept': 'application/vnd.github.v3+json'
605
- }
606
-
607
- async def analyze_repository(self, owner, repo):
608
- """Comprehensive repository analysis"""
609
- async with aiohttp.ClientSession() as session:
610
- # Get basic repo info
611
- repo_info = await self._get_repo_info(session, owner, repo)
612
-
613
- # Get commit activity
614
- commits = await self._get_commit_activity(session, owner, repo)
615
-
616
- # Get issues and PRs
617
- issues = await self._get_issues_analysis(session, owner, repo)
618
- prs = await self._get_pr_analysis(session, owner, repo)
619
-
620
- # Get contributors
621
- contributors = await self._get_contributors_analysis(session, owner, repo)
622
-
623
- # Get code quality indicators
624
- code_quality = await self._analyze_code_quality(session, owner, repo)
625
-
626
- return {
627
- 'repository': repo_info,
628
- 'activity': commits,
629
- 'issues': issues,
630
- 'pull_requests': prs,
631
- 'contributors': contributors,
632
- 'code_quality': code_quality,
633
- 'health_score': self._calculate_health_score(repo_info, commits, issues, prs),
634
- 'recommendations': self._generate_recommendations(repo_info, commits, issues, prs)
635
- }
636
-
637
- async def _get_repo_info(self, session, owner, repo):
638
- url = f'https://api.github.com/repos/{owner}/{repo}'
639
- async with session.get(url, headers=self.headers) as response:
640
- if response.status == 200:
641
- data = await response.json()
642
- return {
643
- 'name': data['name'],
644
- 'description': data.get('description', ''),
645
- 'language': data.get('language', 'Unknown'),
646
- 'stars': data['stargazers_count'],
647
- 'forks': data['forks_count'],
648
- 'open_issues': data['open_issues_count'],
649
- 'created_at': data['created_at'],
650
- 'updated_at': data['updated_at'],
651
- 'size': data['size'],
652
- 'license': data.get('license', {}).get('name', 'None') if data.get('license') else 'None'
653
- }
654
- return {}
655
-
656
- async def _get_commit_activity(self, session, owner, repo):
657
- # Get commits from last 30 days
658
- since = (datetime.now() - timedelta(days=30)).isoformat()
659
- url = f'https://api.github.com/repos/{owner}/{repo}/commits'
660
- params = {'since': since, 'per_page': 100}
661
-
662
- async with session.get(url, headers=self.headers, params=params) as response:
663
- if response.status == 200:
664
- commits = await response.json()
665
-
666
- # Analyze commit patterns
667
- daily_commits = {}
668
- authors = {}
669
-
670
- for commit in commits:
671
- date = commit['commit']['author']['date'][:10]
672
- author = commit['commit']['author']['name']
673
-
674
- daily_commits[date] = daily_commits.get(date, 0) + 1
675
- authors[author] = authors.get(author, 0) + 1
676
-
677
- return {
678
- 'total_commits_30d': len(commits),
679
- 'daily_average': len(commits) / 30,
680
- 'most_active_day': max(daily_commits.items(), key=lambda x: x[1]) if daily_commits else None,
681
- 'active_contributors': len(authors),
682
- 'top_contributor': max(authors.items(), key=lambda x: x[1]) if authors else None
683
- }
684
- return {}
685
-
686
- def _calculate_health_score(self, repo_info, commits, issues, prs):
687
- """Calculate overall repository health score (0-100)"""
688
- score = 0
689
-
690
- # Activity score (30 points)
691
- if commits.get('total_commits_30d', 0) > 10:
692
- score += 30
693
- elif commits.get('total_commits_30d', 0) > 5:
694
- score += 20
695
- elif commits.get('total_commits_30d', 0) > 0:
696
- score += 10
697
-
698
- # Documentation score (20 points)
699
- if repo_info.get('description'):
700
- score += 10
701
- # Additional checks would go here (README, wiki, etc.)
702
-
703
- # Community score (25 points)
704
- if repo_info.get('stars', 0) > 100:
705
- score += 15
706
- elif repo_info.get('stars', 0) > 10:
707
- score += 10
708
- elif repo_info.get('stars', 0) > 0:
709
- score += 5
710
-
711
- if issues.get('response_time_avg', float('inf')) < 7: # Average response < 7 days
712
- score += 10
713
-
714
- # Maintenance score (25 points)
715
- last_update = datetime.fromisoformat(repo_info.get('updated_at', '1970-01-01T00:00:00Z').replace('Z', '+00:00'))
716
- days_since_update = (datetime.now(last_update.tzinfo) - last_update).days
717
-
718
- if days_since_update < 30:
719
- score += 25
720
- elif days_since_update < 90:
721
- score += 15
722
- elif days_since_update < 365:
723
- score += 5
724
-
725
- return min(score, 100)
726
-
727
- @server.list_tools()
728
- async def list_tools():
729
- return [
730
- Tool(
731
- name="analyze_repository",
732
- description="Analyze GitHub repository health, activity, and metrics",
733
- inputSchema={
734
- "type": "object",
735
- "properties": {
736
- "owner": {"type": "string", "description": "Repository owner"},
737
- "repo": {"type": "string", "description": "Repository name"}
738
- },
739
- "required": ["owner", "repo"]
740
- }
741
- ),
742
- Tool(
743
- name="compare_repositories",
744
- description="Compare multiple repositories across key metrics",
745
- inputSchema={
746
- "type": "object",
747
- "properties": {
748
- "repositories": {
749
- "type": "array",
750
- "items": {
751
- "type": "object",
752
- "properties": {
753
- "owner": {"type": "string"},
754
- "repo": {"type": "string"}
755
- }
756
- }
757
- }
758
- }
759
- }
760
- )
761
- ]
762
-
763
- @server.call_tool()
764
- async def call_tool(name: str, arguments: dict):
765
- token = os.getenv('GITHUB_TOKEN')
766
- if not token:
767
- return TextContent(type="text", text="Error: GITHUB_TOKEN environment variable not set")
768
-
769
- analyzer = GitHubAnalyzer(token)
770
-
771
- if name == "analyze_repository":
772
- result = await analyzer.analyze_repository(arguments["owner"], arguments["repo"])
773
- return TextContent(type="text", text=json.dumps(result, indent=2))
774
-
775
- elif name == "compare_repositories":
776
- comparisons = []
777
- for repo_data in arguments["repositories"]:
778
- analysis = await analyzer.analyze_repository(repo_data["owner"], repo_data["repo"])
779
- comparisons.append({
780
- "repository": f"{repo_data['owner']}/{repo_data['repo']}",
781
- "analysis": analysis
782
- })
783
-
784
- return TextContent(type="text", text=json.dumps(comparisons, indent=2))
785
-
786
- return TextContent(type="text", text=f"Unknown tool: {name}")
787
-
788
- if __name__ == "__main__":
789
- asyncio.run(server.run())
790
- ```
791
-
792
- ### Database Schema Analyzer MCP
793
- ```python
794
- # database_schema_mcp.py
795
- import asyncio
796
- import os
797
- from mcp.server import Server
798
- from mcp.types import Resource, Tool, TextContent
799
- import asyncpg
800
- import json
801
- from datetime import datetime
802
-
803
- server = Server("database-analyzer", "1.0.0")
804
-
805
- class DatabaseAnalyzer:
806
- def __init__(self, connection_string):
807
- self.connection_string = connection_string
808
-
809
- async def analyze_schema(self, schema_name='public'):
810
- """Comprehensive database schema analysis"""
811
- conn = await asyncpg.connect(self.connection_string)
812
-
813
- try:
814
- # Get all tables
815
- tables = await self._get_tables(conn, schema_name)
816
-
817
- # Analyze each table
818
- table_analyses = {}
819
- for table in tables:
820
- table_analyses[table['table_name']] = await self._analyze_table(conn, schema_name, table['table_name'])
821
-
822
- # Get relationships
823
- relationships = await self._get_relationships(conn, schema_name)
824
-
825
- # Get indexes
826
- indexes = await self._get_indexes(conn, schema_name)
827
-
828
- # Performance analysis
829
- performance = await self._analyze_performance(conn, schema_name)
830
-
831
- return {
832
- 'schema': schema_name,
833
- 'tables': table_analyses,
834
- 'relationships': relationships,
835
- 'indexes': indexes,
836
- 'performance': performance,
837
- 'recommendations': self._generate_schema_recommendations(table_analyses, relationships, indexes)
838
- }
839
-
840
- finally:
841
- await conn.close()
842
-
843
- async def _get_tables(self, conn, schema_name):
844
- query = """
845
- SELECT table_name,
846
- pg_total_relation_size(quote_ident(table_name)) as size_bytes
847
- FROM information_schema.tables
848
- WHERE table_schema = $1 AND table_type = 'BASE TABLE'
849
- ORDER BY table_name
850
- """
851
- return await conn.fetch(query, schema_name)
852
-
853
- async def _analyze_table(self, conn, schema_name, table_name):
854
- # Get columns
855
- columns_query = """
856
- SELECT column_name, data_type, is_nullable, column_default,
857
- character_maximum_length, numeric_precision, numeric_scale
858
- FROM information_schema.columns
859
- WHERE table_schema = $1 AND table_name = $2
860
- ORDER BY ordinal_position
861
- """
862
- columns = await conn.fetch(columns_query, schema_name, table_name)
863
-
864
- # Get row count
865
- try:
866
- row_count = await conn.fetchval(f'SELECT COUNT(*) FROM {schema_name}.{table_name}')
867
- except:
868
- row_count = 0
869
-
870
- # Get primary keys
871
- pk_query = """
872
- SELECT column_name
873
- FROM information_schema.table_constraints tc
874
- JOIN information_schema.key_column_usage kcu ON tc.constraint_name = kcu.constraint_name
875
- WHERE tc.table_schema = $1 AND tc.table_name = $2 AND tc.constraint_type = 'PRIMARY KEY'
876
- """
877
- primary_keys = await conn.fetch(pk_query, schema_name, table_name)
878
-
879
- return {
880
- 'columns': [dict(col) for col in columns],
881
- 'row_count': row_count,
882
- 'primary_keys': [pk['column_name'] for pk in primary_keys],
883
- 'data_quality': await self._assess_data_quality(conn, schema_name, table_name, columns)
884
- }
885
-
886
- async def _assess_data_quality(self, conn, schema_name, table_name, columns):
887
- quality_issues = []
888
-
889
- for column in columns:
890
- col_name = column['column_name']
891
-
892
- # Check for null values in non-nullable columns
893
- if column['is_nullable'] == 'NO':
894
- null_count = await conn.fetchval(
895
- f'SELECT COUNT(*) FROM {schema_name}.{table_name} WHERE {col_name} IS NULL'
896
- )
897
- if null_count > 0:
898
- quality_issues.append({
899
- 'type': 'unexpected_nulls',
900
- 'column': col_name,
901
- 'count': null_count
902
- })
903
-
904
- # Check for duplicate values in potential key columns
905
- if 'id' in col_name.lower() or col_name.lower().endswith('_key'):
906
- duplicate_query = f"""
907
- SELECT COUNT(*) FROM (
908
- SELECT {col_name}, COUNT(*) as cnt
909
- FROM {schema_name}.{table_name}
910
- WHERE {col_name} IS NOT NULL
911
- GROUP BY {col_name}
912
- HAVING COUNT(*) > 1
913
- ) duplicates
914
- """
915
- duplicate_count = await conn.fetchval(duplicate_query)
916
- if duplicate_count > 0:
917
- quality_issues.append({
918
- 'type': 'duplicates',
919
- 'column': col_name,
920
- 'duplicate_groups': duplicate_count
921
- })
922
-
923
- return quality_issues
924
-
925
- @server.list_tools()
926
- async def list_tools():
927
- return [
928
- Tool(
929
- name="analyze_schema",
930
- description="Analyze database schema structure, relationships, and quality",
931
- inputSchema={
932
- "type": "object",
933
- "properties": {
934
- "schema_name": {"type": "string", "default": "public"}
935
- }
936
- }
937
- ),
938
- Tool(
939
- name="performance_analysis",
940
- description="Analyze database performance metrics and slow queries",
941
- inputSchema={
942
- "type": "object",
943
- "properties": {
944
- "time_period": {"type": "string", "default": "1h"}
945
- }
946
- }
947
- ),
948
- Tool(
949
- name="suggest_indexes",
950
- description="Suggest database indexes based on query patterns",
951
- inputSchema={
952
- "type": "object",
953
- "properties": {
954
- "table_name": {"type": "string"},
955
- "schema_name": {"type": "string", "default": "public"}
956
- }
957
- }
958
- )
959
- ]
960
-
961
- @server.call_tool()
962
- async def call_tool(name: str, arguments: dict):
963
- connection_string = os.getenv('DATABASE_URL')
964
- if not connection_string:
965
- return TextContent(type="text", text="Error: DATABASE_URL environment variable not set")
966
-
967
- analyzer = DatabaseAnalyzer(connection_string)
968
-
969
- try:
970
- if name == "analyze_schema":
971
- schema_name = arguments.get("schema_name", "public")
972
- result = await analyzer.analyze_schema(schema_name)
973
- return TextContent(type="text", text=json.dumps(result, indent=2, default=str))
974
-
975
- elif name == "performance_analysis":
976
- # Implementation for performance analysis
977
- return TextContent(type="text", text="Performance analysis not yet implemented")
978
-
979
- elif name == "suggest_indexes":
980
- # Implementation for index suggestions
981
- return TextContent(type="text", text="Index suggestions not yet implemented")
982
-
983
- except Exception as e:
984
- return TextContent(type="text", text=f"Error: {str(e)}")
985
-
986
- return TextContent(type="text", text=f"Unknown tool: {name}")
987
-
988
- if __name__ == "__main__":
989
- asyncio.run(server.run())
990
- ```
991
-
992
- ## Integration Workflows
993
-
994
- ### Full-Stack Application Analysis
995
- ```markdown
996
- # ~/.prompts/full_stack_analysis.md
997
- /tools file_analyzer.rb,code_quality.rb,config_manager.rb
998
- # Requires MCP servers: github, filesystem, database
999
- # Run with: aia --mcp-use github,filesystem,database --tools file_analyzer.rb,code_quality.rb,config_manager.rb full_stack_analysis
1000
-
1001
- # Full-Stack Application Analysis
1002
-
1003
- Application: <%= app_name %>
1004
- Repository: <%= repo_url %>
1005
- Environment: <%= environment %>
1006
-
1007
- ## Phase 1: Repository Analysis
1008
- Using GitHub MCP client:
1009
- 1. Repository health and activity metrics
1010
- 2. Issue and PR management effectiveness
1011
- 3. Contributor activity and code review patterns
1012
- 4. Release and deployment frequency
1013
-
1014
- ## Phase 2: Codebase Quality Assessment
1015
- Using code analysis tools:
1016
- 1. Code quality metrics across all languages
1017
- 2. Complexity analysis and refactoring opportunities
1018
- 3. Security vulnerability scanning
1019
- 4. Test coverage and quality assessment
1020
-
1021
- ## Phase 3: Configuration Management
1022
- Using configuration tools:
1023
- 1. Configuration file analysis and security
1024
- 2. Environment-specific settings validation
1025
- 3. Secret management assessment
1026
- 4. Deployment configuration review
1027
-
1028
- ## Phase 4: Database Architecture
1029
- Using database MCP client:
1030
- 1. Schema design and normalization analysis
1031
- 2. Index optimization opportunities
1032
- 3. Query performance analysis
1033
- 4. Data integrity and quality assessment
1034
-
1035
- ## Phase 5: File System Organization
1036
- Using filesystem MCP client:
1037
- 1. Project structure and organization
1038
- 2. Build and deployment artifacts
1039
- 3. Documentation completeness
1040
- 4. Security file analysis
1041
-
1042
- ## Integration Report
1043
- Cross-analyze findings to provide:
1044
- - Overall application health score
1045
- - Security risk assessment
1046
- - Performance optimization priorities
1047
- - Maintenance burden analysis
1048
- - Deployment readiness checklist
1049
- - Prioritized improvement recommendations
1050
-
1051
- Generate comprehensive analysis with actionable insights for each identified area.
1052
- ```
1053
-
1054
- ### DevOps Pipeline Assessment
1055
- ```markdown
1056
- # ~/.prompts/devops_pipeline_analysis.md
1057
- /tools log_analyzer.rb,config_manager.rb
1058
- # Requires MCP servers: github, filesystem
1059
- # Run with: aia --mcp-use github,filesystem --tools log_analyzer.rb,config_manager.rb devops_pipeline_analysis
1060
-
1061
- # DevOps Pipeline Analysis
1062
-
1063
- Project: <%= project_name %>
1064
- Pipeline type: <%= pipeline_type %>
1065
-
1066
- ## CI/CD Configuration Analysis
1067
- Using configuration tools:
1068
- 1. Build configuration validation (GitHub Actions, Jenkins, etc.)
1069
- 2. Deployment script analysis and security
1070
- 3. Environment configuration consistency
1071
- 4. Secret management in CI/CD
1072
-
1073
- ## Pipeline Performance Analysis
1074
- Using log analysis tools:
1075
- 1. Build time trends and optimization opportunities
1076
- 2. Failure rate analysis and common failure patterns
1077
- 3. Deployment frequency and success rates
1078
- 4. Resource utilization during builds
1079
-
1080
- ## Repository Integration Assessment
1081
- Using GitHub MCP:
1082
- 1. Branch protection rules and policies
1083
- 2. Automated testing integration
1084
- 3. Code review automation
1085
- 4. Release management processes
1086
-
1087
- ## Infrastructure as Code Review
1088
- Using filesystem MCP:
1089
- 1. Terraform/CloudFormation template analysis
1090
- 2. Docker configuration optimization
1091
- 3. Kubernetes manifest validation
1092
- 4. Infrastructure security assessment
1093
-
1094
- ## Recommendations
1095
- Generate prioritized recommendations for:
1096
- - Pipeline speed improvements
1097
- - Security enhancements
1098
- - Reliability improvements
1099
- - Cost optimization opportunities
1100
- - Automation enhancement suggestions
1101
-
1102
- Provide implementation timeline and impact assessment for each recommendation.
1103
- ```
1104
-
1105
- ## Advanced Integration Patterns
1106
-
1107
- ### Multi-Environment Consistency Checker
1108
- ```ruby
1109
- # ~/.config/aia/tools/environment_checker.rb
1110
- class EnvironmentChecker < RubyLLM::Tool
1111
- description "Compares configurations and deployments across multiple environments"
1112
-
1113
- def compare_environments(environments_config)
1114
- environments = JSON.parse(environments_config)
1115
- comparison_results = {}
1116
-
1117
- environments.each do |env_name, config|
1118
- comparison_results[env_name] = analyze_environment(env_name, config)
1119
- end
1120
-
1121
- # Cross-environment analysis
1122
- consistency_report = analyze_consistency(comparison_results)
1123
- drift_analysis = detect_configuration_drift(comparison_results)
1124
-
1125
- {
1126
- environments: comparison_results,
1127
- consistency: consistency_report,
1128
- drift: drift_analysis,
1129
- recommendations: generate_consistency_recommendations(consistency_report, drift_analysis)
1130
- }.to_json
1131
- end
1132
-
1133
- def validate_deployment_readiness(environment, checklist_items = nil)
1134
- default_checklist = [
1135
- 'configuration_files_present',
1136
- 'secrets_configured',
1137
- 'database_migrations_applied',
1138
- 'dependencies_installed',
1139
- 'health_checks_passing',
1140
- 'monitoring_configured',
1141
- 'backup_procedures_verified'
1142
- ]
1143
-
1144
- checklist = checklist_items || default_checklist
1145
- results = {}
1146
-
1147
- checklist.each do |item|
1148
- results[item] = check_deployment_item(environment, item)
1149
- end
1150
-
1151
- readiness_score = calculate_readiness_score(results)
1152
- blocking_issues = identify_blocking_issues(results)
1153
-
1154
- {
1155
- environment: environment,
1156
- readiness_score: readiness_score,
1157
- checklist_results: results,
1158
- blocking_issues: blocking_issues,
1159
- deployment_recommended: blocking_issues.empty? && readiness_score > 80
1160
- }.to_json
1161
- end
1162
-
1163
- private
1164
-
1165
- def analyze_environment(env_name, config)
1166
- # Analyze single environment
1167
- {
1168
- name: env_name,
1169
- config_files: find_config_files(config['path']),
1170
- services: check_services(config['services']),
1171
- database: check_database_connection(config['database']),
1172
- monitoring: check_monitoring(config['monitoring']),
1173
- last_deployment: get_last_deployment_info(env_name)
1174
- }
1175
- end
1176
-
1177
- def analyze_consistency(environments)
1178
- consistency_issues = []
1179
-
1180
- # Compare configuration structures
1181
- config_structures = environments.map { |env, data| data[:config_files] }
1182
- unless config_structures.all? { |structure| structure.keys.sort == config_structures.first.keys.sort }
1183
- consistency_issues << "Configuration file structures differ between environments"
1184
- end
1185
-
1186
- # Compare service configurations
1187
- service_configs = environments.map { |env, data| data[:services] }
1188
- unless service_configs.all? { |config| config.keys.sort == service_configs.first.keys.sort }
1189
- consistency_issues << "Service configurations differ between environments"
1190
- end
1191
-
1192
- {
1193
- consistent: consistency_issues.empty?,
1194
- issues: consistency_issues,
1195
- score: calculate_consistency_score(consistency_issues)
1196
- }
1197
- end
1198
- end
1199
- ```
1200
-
1201
- ## Related Documentation
1202
-
1203
- - [Tools Integration](guides/tools.md) - Detailed tool development guide
1204
- - [MCP Integration](mcp-integration.md) - MCP client development and usage
1205
- - [Advanced Prompting](advanced-prompting.md) - Complex integration patterns
1206
- - [Configuration](configuration.md) - Tool and MCP configuration
1207
- - [Examples Directory](examples/index.md) - Additional examples and templates
1208
-
1209
- ---
1210
-
1211
- These examples demonstrate the power of combining RubyLLM tools with MCP clients to create sophisticated analysis and automation workflows. Use them as templates and inspiration for building your own integrated solutions!