bug_bunny 4.6.1 → 4.8.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.
Files changed (71) hide show
  1. checksums.yaml +4 -4
  2. data/.agents/skills/rabbitmq-expert/SKILL.md +1555 -0
  3. data/.claude/commands/gem-ai-setup.md +174 -0
  4. data/.claude/commands/pr.md +53 -0
  5. data/.claude/commands/release.md +52 -0
  6. data/.claude/commands/rubocop.md +22 -0
  7. data/.claude/commands/service-ai-setup.md +168 -0
  8. data/.claude/commands/test.md +28 -0
  9. data/.claude/commands/yard.md +46 -0
  10. data/CHANGELOG.md +50 -15
  11. data/CLAUDE.md +240 -0
  12. data/README.md +154 -221
  13. data/Rakefile +19 -3
  14. data/docs/_index.md +50 -0
  15. data/docs/ai/_index.md +56 -0
  16. data/docs/ai/antipatterns.md +166 -0
  17. data/docs/ai/api.md +251 -0
  18. data/docs/ai/architecture.md +92 -0
  19. data/docs/ai/errors.md +158 -0
  20. data/docs/ai/faq_external.md +133 -0
  21. data/docs/ai/faq_internal.md +86 -0
  22. data/docs/ai/glossary.md +45 -0
  23. data/docs/concepts.md +140 -0
  24. data/docs/howto/controller.md +194 -0
  25. data/docs/howto/middleware_client.md +119 -0
  26. data/docs/howto/middleware_consumer.md +127 -0
  27. data/docs/howto/rails.md +214 -0
  28. data/docs/howto/resource.md +200 -0
  29. data/docs/howto/routing.md +133 -0
  30. data/docs/howto/testing.md +259 -0
  31. data/docs/howto/tracing.md +119 -0
  32. data/lib/bug_bunny/client.rb +45 -21
  33. data/lib/bug_bunny/configuration.rb +63 -0
  34. data/lib/bug_bunny/consumer.rb +51 -37
  35. data/lib/bug_bunny/consumer_middleware.rb +14 -5
  36. data/lib/bug_bunny/controller.rb +39 -18
  37. data/lib/bug_bunny/exception.rb +5 -1
  38. data/lib/bug_bunny/middleware/raise_error.rb +3 -3
  39. data/lib/bug_bunny/observability.rb +28 -6
  40. data/lib/bug_bunny/producer.rb +11 -13
  41. data/lib/bug_bunny/railtie.rb +8 -7
  42. data/lib/bug_bunny/request.rb +3 -11
  43. data/lib/bug_bunny/resource.rb +81 -41
  44. data/lib/bug_bunny/routing/route.rb +6 -1
  45. data/lib/bug_bunny/routing/route_set.rb +60 -22
  46. data/lib/bug_bunny/session.rb +18 -11
  47. data/lib/bug_bunny/version.rb +1 -1
  48. data/lib/bug_bunny.rb +4 -2
  49. data/lib/generators/bug_bunny/install/install_generator.rb +45 -5
  50. data/lib/tasks/bug_bunny.rake +50 -0
  51. data/plan_test.txt +63 -0
  52. data/skills-lock.json +10 -0
  53. data/spec/integration/client_spec.rb +117 -0
  54. data/spec/integration/consumer_middleware_spec.rb +86 -0
  55. data/spec/integration/controller_spec.rb +140 -0
  56. data/spec/integration/error_handling_spec.rb +57 -0
  57. data/spec/integration/infrastructure_spec.rb +52 -0
  58. data/spec/integration/resource_spec.rb +113 -0
  59. data/spec/spec_helper.rb +70 -0
  60. data/spec/support/bunny_mocks.rb +18 -0
  61. data/spec/support/integration_helper.rb +87 -0
  62. data/spec/unit/client_session_pool_spec.rb +159 -0
  63. data/spec/unit/configuration_spec.rb +164 -0
  64. data/spec/unit/consumer_middleware_spec.rb +129 -0
  65. data/spec/unit/consumer_spec.rb +90 -0
  66. data/spec/unit/controller_after_action_spec.rb +155 -0
  67. data/spec/unit/observability_spec.rb +167 -0
  68. data/spec/unit/resource_attributes_spec.rb +69 -0
  69. data/spec/unit/session_spec.rb +98 -0
  70. metadata +50 -3
  71. data/sig/bug_bunny.rbs +0 -4
@@ -0,0 +1,174 @@
1
+ Generate or update the complete AI documentation suite for this gem.
2
+
3
+ This skill is invoked automatically by `/release`. It can also be run standalone to update docs without a full release.
4
+
5
+ BugBunny's `docs/ai/` is the **golden example** of the expected output quality. When in doubt, read it.
6
+
7
+ ---
8
+
9
+ ## Step 1 — Discover the current state
10
+
11
+ Read in order:
12
+ 1. `lib/bug_bunny/version.rb` (or equivalent) — current version
13
+ 2. `docs/_index.md` — if it exists, it lists all files to update and their purpose
14
+ 3. `docs/ai/_index.md` — if it exists, it has the current profile (minimal/full) and file list
15
+ 4. `gemspec` — gem name, summary, description, dependencies
16
+ 5. `CLAUDE.md` — architecture, components, patterns, extension hooks
17
+
18
+ If `docs/ai/` does not exist yet, this is a **first-time generation**. Create from scratch.
19
+ If it exists, **update only the sections affected by the changes in this release**.
20
+
21
+ ---
22
+
23
+ ## Step 2 — Determine the profile
24
+
25
+ **Full profile** when any of these apply:
26
+ - Gem is public (has a homepage or published to RubyGems)
27
+ - Gem has multiple audiences (internal maintainers + external integrators)
28
+ - Gem has a non-trivial public API (multiple classes, errors, configuration)
29
+
30
+ **Minimal profile** when all of these apply:
31
+ - Gem is internal-only
32
+ - Single audience
33
+ - Simple API (one entry point, few methods)
34
+
35
+ Full profile files: `_index.md`, `glossary.md`, `architecture.md`, `api.md`, `faq_internal.md`, `faq_external.md`, `antipatterns.md`, `errors.md`
36
+ Minimal profile files: `_index.md`, `api.md`, `errors.md`
37
+
38
+ ---
39
+
40
+ ## Step 3 — Analyze the codebase
41
+
42
+ Read the following to generate accurate content:
43
+ - All files under `lib/` — public API, class responsibilities, method signatures
44
+ - `spec/` or `test/` — usage patterns, edge cases, what errors are expected
45
+ - `CHANGELOG.md` — what changed in this version (for updating existing docs)
46
+ - `docs/howto/` — existing human docs to stay consistent with
47
+
48
+ ---
49
+
50
+ ## Step 4 — Generate or update each file
51
+
52
+ Apply these rules to every file:
53
+
54
+ **RAG optimization rules (mandatory):**
55
+ 1. Each section ≤ 400 tokens — chunks must be self-contained
56
+ 2. Each section self-contained — do not assume context from previous sections
57
+ 3. `faq_*.md` always in strict Q&A format — H3 with the question, answer ≤ 150 words
58
+ 4. `glossary.md` one entry per term — term in bold, definition in 1-3 lines
59
+ 5. `errors.md` one entry per error — name, cause, how to reproduce, how to resolve
60
+ 6. No introductory prose — go straight to content
61
+
62
+ ### `_index.md`
63
+
64
+ Frontmatter manifest. Update `version:` to the new version. Keep `profile:`, `kind:`, `audiences:` stable unless the gem changed fundamentally. List every file under `files:` with its audience.
65
+
66
+ Reference: `docs/ai/_index.md` in BugBunny.
67
+
68
+ ### `glossary.md`
69
+
70
+ Domain terms specific to this gem. Include:
71
+ - Core abstractions introduced by the gem
72
+ - Terms a developer needs to understand to use the gem correctly
73
+ - Terms that have a non-obvious meaning in this context
74
+
75
+ Do NOT include generic Ruby or framework terms unless the gem redefines them.
76
+
77
+ Reference: `docs/ai/glossary.md` in BugBunny.
78
+
79
+ ### `architecture.md`
80
+
81
+ Internal-facing. Include:
82
+ - Component map (ASCII diagram if useful)
83
+ - How the components interact at runtime
84
+ - Key design decisions and why (not just what)
85
+ - Thread safety considerations if relevant
86
+ - Caching or lifecycle patterns
87
+
88
+ Reference: `docs/ai/architecture.md` in BugBunny.
89
+
90
+ ### `api.md`
91
+
92
+ External-facing. Include:
93
+ - Configuration block with all options, types, defaults, and constraints
94
+ - Every public class with its public methods: signature, parameters, return type, description
95
+ - Code examples for each major operation
96
+ - Class-level configuration options (`.with`, class attributes, etc.)
97
+
98
+ Reference: `docs/ai/api.md` in BugBunny.
99
+
100
+ ### `faq_internal.md`
101
+
102
+ Q&A for the gem maintainer. Cover:
103
+ - Non-obvious implementation decisions ("why X instead of Y?")
104
+ - Thread safety and concurrency considerations
105
+ - How to extend or hook into the gem
106
+ - Common mistakes when modifying the gem internals
107
+
108
+ Each Q&A: H3 for the question, answer ≤ 150 words, no preamble.
109
+
110
+ Reference: `docs/ai/faq_internal.md` in BugBunny.
111
+
112
+ ### `faq_external.md`
113
+
114
+ Q&A for the developer integrating the gem. Cover:
115
+ - Setup and configuration questions
116
+ - How to perform the most common operations
117
+ - Error handling patterns
118
+ - Testing patterns
119
+ - Performance and tuning questions
120
+
121
+ Each Q&A: H3 for the question, answer ≤ 150 words, no preamble.
122
+
123
+ Reference: `docs/ai/faq_external.md` in BugBunny.
124
+
125
+ ### `antipatterns.md`
126
+
127
+ What NOT to do. For each antipattern:
128
+ 1. Name it clearly
129
+ 2. Show the wrong code
130
+ 3. Explain why it's wrong (not just "it's bad")
131
+ 4. Show the correct alternative
132
+
133
+ Reference: `docs/ai/antipatterns.md` in BugBunny.
134
+
135
+ ### `errors.md`
136
+
137
+ All exceptions the gem raises. For each:
138
+ - Class name and inheritance
139
+ - Cause (what triggers it)
140
+ - How to reproduce it (minimal example)
141
+ - How to resolve it
142
+
143
+ Reference: `docs/ai/errors.md` in BugBunny.
144
+
145
+ ---
146
+
147
+ ## Step 5 — Update docs/howto/ and docs/concepts.md
148
+
149
+ Read `docs/_index.md` (human documentation section) to know which files exist.
150
+ Update only the sections affected by the changes in this release.
151
+ Do not rewrite files that were not affected by the changes.
152
+
153
+ ---
154
+
155
+ ## Step 6 — Update README.md
156
+
157
+ Generate or update README.md after `docs/howto/` is already updated.
158
+ README structure:
159
+ 1. One-line description
160
+ 2. Installation (`gem 'gem_name'` in Gemfile)
161
+ 3. Quick start — two minimal code examples (publisher side + consumer/server side if applicable)
162
+ 4. Features list for the current version
163
+ 5. Links to `docs/` for deeper guides
164
+
165
+ Keep it under 150 lines. README is the entry point — `docs/` is the depth.
166
+
167
+ ---
168
+
169
+ ## Step 7 — Show diff and wait for approval
170
+
171
+ Show the complete diff of all generated/updated files.
172
+ Wait for developer approval before proceeding.
173
+ The developer may adjust content before confirming.
174
+ Do NOT proceed to version bump or CHANGELOG until approved.
@@ -0,0 +1,53 @@
1
+ Create a Pull Request for BugBunny via GitHub CLI. Usage: /pr
2
+
3
+ Creá un PR desde la rama actual hacia `main` usando `gh`.
4
+
5
+ ## Pasos
6
+
7
+ 1. **Correr tests** — si fallan, detener todo:
8
+ ```bash
9
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8
10
+ bundle exec rspec
11
+ ```
12
+ 2. **autocorregir rubocop** - si fallan, detener todo
13
+ ```bash
14
+ bundle exec rubocop -a
15
+ ```
16
+ 3. **Ejecutar `/gem-ai-setup`** — genera/actualiza `docs/howto/`, `docs/ai/` y `README.md`.
17
+ Esperar aprobación del developer antes de continuar.
18
+ 4. Verificá que hay commits en la rama que no están en main: `git log main..HEAD --oneline`
19
+ 5. Revisá todos los cambios del PR: `git diff main...HEAD`
20
+ 6. Determiná el tipo de cambio (feature, bugfix, refactor, docs, chore)
21
+ 7. Creá el PR con `gh pr create`:
22
+
23
+ ```bash
24
+ gh pr create --title "tipo: descripción breve" --body "$(cat <<'EOF'
25
+ ## Summary
26
+ - Bullet points de los cambios principales
27
+
28
+ ## Test plan
29
+ - [ ] Tests existentes pasan (`/test`)
30
+ - [ ] RuboCop sin offenses (`/rubocop`)
31
+ - [ ] YARD documentado en métodos nuevos/modificados
32
+
33
+ ## Notes
34
+ Contexto adicional si es necesario.
35
+
36
+ 🤖 Generated with [Claude Code](https://claude.com/claude-code)
37
+ EOF
38
+ )"
39
+ ```
40
+
41
+ ## Convenciones de título
42
+
43
+ - `feat: descripción` — feature nueva
44
+ - `fix: descripción` — bugfix
45
+ - `chore: descripción` — mantenimiento, deps, config
46
+ - `docs: descripción` — solo documentación
47
+ - `refactor: descripción` — refactor sin cambio de comportamiento
48
+
49
+ ## Importante
50
+
51
+ - El remote SSH está roto — si el PR requiere push previo, usar HTTPS temporalmente
52
+ - Mostrar la URL del PR creado al usuario
53
+ - No crear el PR sin confirmación del usuario
@@ -0,0 +1,52 @@
1
+ Release BugBunny gem. Usage: /release [patch|minor|major]
2
+
3
+ Ejecutá el flujo completo de release para BugBunny. El argumento determina el tipo de bump:
4
+ - `patch` → bugfix (4.6.1 → 4.6.2)
5
+ - `minor` → feature nueva (4.6.1 → 4.7.0)
6
+ - `major` → breaking change (4.6.1 → 5.0.0)
7
+
8
+ ## Pasos
9
+
10
+ 1. **Leer versión actual** de `lib/bug_bunny/version.rb`
11
+ 2. **Calcular nueva versión** según el tipo de bump
12
+ 3. **Correr tests** — si fallan, detener todo:
13
+ ```bash
14
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8
15
+ bundle exec rspec
16
+ ```
17
+ 4. **autocorregir rubocop** - si fallan, detener todo
18
+ ```bash
19
+ bundle exec rubocop -a
20
+ ```
21
+ 5. **Ejecutar `/gem-ai-setup`** — genera/actualiza `docs/howto/`, `docs/ai/` y `README.md`.
22
+ Esperar aprobación del developer antes de continuar.
23
+ 6. **Actualizar `lib/bug_bunny/version.rb`** con la nueva versión
24
+ 7. **Agregar entrada al tope de `CHANGELOG.md`** con formato:
25
+ ```
26
+ ## [X.Y.Z] - YYYY-MM-DD
27
+ ### ✨ New Features / 🐛 Bug Fixes / 💥 Breaking Changes
28
+ * Descripción de los cambios
29
+ ```
30
+ 8. **Mostrar el diff completo** al usuario y pedir confirmación antes de continuar
31
+ 9. **Commit** con mensaje: `feat|fix|chore: descripción breve vX.Y.Z`
32
+ 10. **Merge a main** desde `/Users/gabriel/src/gems/bug_bunny`: `git merge --ff-only <branch>`
33
+ 11. **Push via HTTPS**:
34
+ ```bash
35
+ git remote set-url origin https://github.com/gedera/bug_bunny.git
36
+ git push origin main
37
+ git remote set-url origin git@github.com:gedera/bug_bunny.git
38
+ ```
39
+ 12. **Tag y push**:
40
+ ```bash
41
+ git tag vX.Y.Z
42
+ git remote set-url origin https://github.com/gedera/bug_bunny.git
43
+ git push origin vX.Y.Z
44
+ git remote set-url origin git@github.com:gedera/bug_bunny.git
45
+ ```
46
+
47
+ ## Importante
48
+
49
+ - Nunca commitear ni pushear sin confirmación explícita del usuario
50
+ - El worktree de main está en `/Users/gabriel/src/gems/bug_bunny`
51
+ - SSH está roto — siempre usar HTTPS para push y restaurar SSH después
52
+ - Sourcear chruby antes de cualquier comando Ruby: `source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8`
@@ -0,0 +1,22 @@
1
+ Run RuboCop for BugBunny. Usage: /rubocop [--fix]
2
+
3
+ Ejecutá RuboCop con rubocop-rails-omakase sobre el código modificado.
4
+
5
+ ## Comandos
6
+
7
+ Sin argumentos — solo reporte:
8
+ ```bash
9
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec rubocop
10
+ ```
11
+
12
+ Con `--fix` — autocorrect seguro:
13
+ ```bash
14
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec rubocop -a
15
+ ```
16
+
17
+ ## Reglas importantes
18
+
19
+ - **Solo corregir código nuevo o modificado en el PR actual** — nunca tocar código existente no relacionado
20
+ - Si hay offenses que requieren intervención manual (no autocorregibles), reportalos con línea y descripción
21
+ - rubocop-rails-omakase tiene opiniones fuertes sobre estilo — seguirlas sin discutir
22
+ - Si hay un offense legítimo que debe ignorarse, usar `# rubocop:disable Cop/Name` en la línea específica con un comentario explicativo
@@ -0,0 +1,168 @@
1
+ Generate or update the complete AI documentation suite for this microservice.
2
+
3
+ This skill is invoked automatically by `/pr`. It can also be run standalone.
4
+
5
+ The same quality standard as BugBunny's `docs/ai/` applies here — self-contained chunks, RAG-optimized, no introductory prose.
6
+
7
+ ---
8
+
9
+ ## Step 1 — Discover the current state
10
+
11
+ Read in order:
12
+ 1. `docs/_index.md` — if it exists, lists all files and their purpose
13
+ 2. `docs/ai/_index.md` — if it exists, current profile and file list
14
+ 3. `CLAUDE.md` — service purpose, architecture, dependencies
15
+ 4. `config/services.yml` — declared dependencies (other services this one talks to)
16
+ 5. `config/routes.rb` or `config/initializers/bug_bunny_routes.rb` — what this service exposes
17
+
18
+ If `docs/ai/` does not exist yet, this is a **first-time generation**. Create from scratch.
19
+ If it exists, **update only the sections affected by the changes in this PR**.
20
+
21
+ ---
22
+
23
+ ## Step 2 — Profile
24
+
25
+ Microservices always use the **full profile** with `contracts.md` instead of `api.md`:
26
+
27
+ ```
28
+ docs/ai/
29
+ _index.md
30
+ glossary.md
31
+ architecture.md
32
+ contracts.md ← what this service exposes (queues, endpoints, events)
33
+ faq_internal.md
34
+ faq_external.md
35
+ antipatterns.md
36
+ errors.md
37
+ ```
38
+
39
+ ---
40
+
41
+ ## Step 3 — Analyze the codebase
42
+
43
+ Read:
44
+ - `app/` — controllers, models, workers, services
45
+ - `config/` — routes, initializers, services.yml
46
+ - `lib/` — custom libraries
47
+ - `spec/` — usage patterns and edge cases
48
+ - `CHANGELOG.md` or git log — what changed in this PR
49
+
50
+ ---
51
+
52
+ ## Step 4 — Generate or update each file
53
+
54
+ Apply the same RAG optimization rules as `gem-ai-setup`:
55
+ 1. Each section ≤ 400 tokens, self-contained
56
+ 2. `faq_*.md` strict Q&A format, H3 question, answer ≤ 150 words
57
+ 3. `glossary.md` one entry per term, 1-3 lines
58
+ 4. `errors.md` one entry per error, cause + reproduction + resolution
59
+ 5. No introductory prose
60
+
61
+ ### `_index.md`
62
+
63
+ Frontmatter manifest. Use `kind: microservice` and `transports:` listing all transports used (bug_bunny, http, etc.). List every file with its audience.
64
+
65
+ ```yaml
66
+ ---
67
+ type: knowledge_base
68
+ kind: microservice
69
+ name: service_name
70
+ version: main # microservices don't have semver — use branch or date
71
+ profile: full
72
+ language: ruby
73
+ audiences:
74
+ - internal
75
+ - external
76
+ transports:
77
+ - bug_bunny # list actual transports used
78
+ - http
79
+ files:
80
+ - path: glossary.md
81
+ audience: [internal, external]
82
+ - path: architecture.md
83
+ audience: [internal]
84
+ - path: contracts.md
85
+ audience: [external]
86
+ ...
87
+ ---
88
+ ```
89
+
90
+ ### `glossary.md`
91
+
92
+ Domain terms specific to this service's business domain and technical patterns.
93
+
94
+ ### `architecture.md`
95
+
96
+ Internal-facing. Include:
97
+ - Service responsibility (one paragraph)
98
+ - Component map
99
+ - Data flows for the main operations
100
+ - External dependencies and how they're used
101
+ - Background jobs and their triggers
102
+
103
+ ### `contracts.md`
104
+
105
+ External-facing. The complete contract this service exposes. Include:
106
+
107
+ **BugBunny queues (if applicable):**
108
+ - Queue name, exchange, routing key, exchange type
109
+ - For each route: method, path, request format, response format, possible errors
110
+ - Example request and response payloads
111
+
112
+ **HTTP endpoints (if applicable):**
113
+ - Method, path, parameters, response format
114
+ - Authentication requirements
115
+
116
+ **Events published (if applicable):**
117
+ - Exchange, routing key, payload format
118
+
119
+ ### `faq_internal.md`
120
+
121
+ Q&A for the service developer. Cover:
122
+ - How to add a new route or endpoint
123
+ - How background jobs work and how to add one
124
+ - How to add a new service dependency
125
+ - Non-obvious architectural decisions
126
+
127
+ ### `faq_external.md`
128
+
129
+ Q&A for developers of other services that consume this one. Cover:
130
+ - How to make a request to this service
131
+ - What errors to expect and how to handle them
132
+ - How to handle retries and timeouts
133
+ - How to test integrations against this service
134
+
135
+ ### `antipatterns.md`
136
+
137
+ Common mistakes when interacting with or modifying this service.
138
+
139
+ ### `errors.md`
140
+
141
+ All error responses this service can return. For each:
142
+ - HTTP status / error code
143
+ - When it occurs
144
+ - What the response body looks like
145
+ - How the caller should handle it
146
+
147
+ ---
148
+
149
+ ## Step 5 — Update docs/howto/ and README.md
150
+
151
+ Read `docs/_index.md` to discover which human docs exist.
152
+ Update sections affected by this PR's changes.
153
+ Update `README.md` last — after `docs/howto/` is updated.
154
+
155
+ README structure for a microservice:
156
+ 1. Service purpose (one paragraph)
157
+ 2. Transports (BugBunny queue name, HTTP base URL)
158
+ 3. Quick start — how another service calls this one
159
+ 4. Links to `docs/ai/contracts.md` for full contract reference
160
+
161
+ ---
162
+
163
+ ## Step 6 — Show diff and wait for approval
164
+
165
+ Show the complete diff of all generated/updated files.
166
+ Wait for developer approval before proceeding to PR creation.
167
+ The developer may adjust content before confirming.
168
+ Do NOT create the PR until the docs are approved.
@@ -0,0 +1,28 @@
1
+ Run RSpec tests for BugBunny. Usage: /test [path]
2
+
3
+ Ejecutá la suite de tests de BugBunny con Ruby 3.3.8.
4
+
5
+ ## Comando base
6
+
7
+ ```bash
8
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec rspec
9
+ ```
10
+
11
+ Si se pasa un path como argumento, corré solo ese archivo o directorio:
12
+
13
+ ```bash
14
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec rspec $ARGUMENTS
15
+ ```
16
+
17
+ ## Después de correr los tests
18
+
19
+ - Si hay failures: analizá el error, identificá la causa raíz, proponé el fix al usuario antes de tocar código
20
+ - Si hay warnings de deprecación: reportalos al usuario
21
+ - Si todos pasan: confirmá con el conteo de ejemplos y tiempo de ejecución
22
+
23
+ ## Convenciones de RSpec en este proyecto
24
+
25
+ - Tests en `spec/`
26
+ - Sin mocks de RabbitMQ real — usar doubles de Bunny
27
+ - Describir comportamiento, no implementación
28
+ - Un `context` por escenario, `it` con descripción en español o inglés consistente con el archivo
@@ -0,0 +1,46 @@
1
+ Validate and generate YARD documentation for BugBunny. Usage: /yard
2
+
3
+ Verificá y generá la documentación YARD de la gema.
4
+
5
+ ## Comandos
6
+
7
+ Generar docs:
8
+ ```bash
9
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec yard doc
10
+ ```
11
+
12
+ Ver métodos sin documentar:
13
+ ```bash
14
+ source /opt/homebrew/opt/chruby/share/chruby/chruby.sh && chruby ruby-3.3.8 && bundle exec yard stats --list-undoc
15
+ ```
16
+
17
+ ## Estándar YARD de este proyecto
18
+
19
+ Todo método público nuevo o modificado debe tener:
20
+
21
+ ```ruby
22
+ # Descripción breve en una línea.
23
+ #
24
+ # Descripción extendida opcional si la firma no es autoexplicativa.
25
+ #
26
+ # @param nombre [Tipo] Descripción del parámetro
27
+ # @return [Tipo] Descripción del valor de retorno
28
+ # @raise [ClaseError] Condición bajo la cual se lanza
29
+ # @example
30
+ # resultado = mi_metodo(arg)
31
+ def mi_metodo(nombre)
32
+ ```
33
+
34
+ ## Tipos comunes en este proyecto
35
+
36
+ - `[String]`, `[Integer]`, `[Boolean]`, `[Hash]`, `[Array]`, `[Symbol]`
37
+ - `[Bunny::Session]`, `[Bunny::Channel]`, `[Bunny::MessageProperties]`
38
+ - `[BugBunny::Session]`, `[BugBunny::Request]`, `[BugBunny::Configuration]`
39
+ - `[Proc, nil]` para callbacks opcionales
40
+ - `[void]` para métodos sin return value relevante
41
+
42
+ ## Después de correr
43
+
44
+ - Reportá los métodos públicos sin documentar
45
+ - No documentar métodos privados (YARD los ignora por defecto con `private`)
46
+ - No documentar métodos triviales (`attr_reader`, `attr_accessor`) salvo que necesiten contexto
data/CHANGELOG.md CHANGED
@@ -1,5 +1,40 @@
1
1
  # Changelog
2
2
 
3
+ ## [4.8.0] - 2026-04-02
4
+
5
+ ### ✨ AI Documentation Standard (v4.3)
6
+ * **Gema de Referencia:** BugBunny se convierte en la implementación de referencia para el nuevo Estándar de Documentación AI.
7
+ * **Knowledge Base (Capa 1):** Implementación completa del directorio `docs/ai/` con los 8 archivos de conocimiento estructurado (Glosario, Arquitectura, API, Errores, Antipatrones, FAQs) optimizados para RAG ( chunks ≤ 400 tokens).
8
+ * **Distribución Automática:** Nueva tarea `rake bug_bunny:sync` que permite a cualquier microservicio consumidor sincronizar y referenciar la base de conocimientos de la gema en su propio `CLAUDE.md`.
9
+ * **Generadores:** El `InstallGenerator` ahora inyecta automáticamente el bloque de configuración AI en el proyecto consumidor y crea la estructura de directorios bajo `app/bug_bunny`.
10
+ * **Metadatos:** Inclusión de `documentation_uri` en el `gemspec` para descubrimiento automático de manuales por herramientas de IA externas.
11
+
12
+ ### 🛠️ Tooling & DX
13
+ * **Comandos Enriquecidos:** `/release` y `/pr` ahora incluyen orquestación automatizada de calidad (RuboCop, Tests) y generación de documentación antes de proceder con el ciclo de Git.
14
+ * **Skill Integration:** Soporte para la skill `rabbitmq-expert` localizada en `.agents/skills/` para asistir en decisiones técnicas profundas de AMQP.
15
+
16
+ ## [4.7.0] - 2026-04-01
17
+
18
+ ### ✨ New Features
19
+ * **Routing — Namespace blocks:** Nuevo método `namespace` en el DSL de rutas para organizar controladores en módulos Ruby. Los namespaces son acumulativos y anidables: `namespace :api { namespace :v1 { resources :metrics } }` resuelve a `Api::V1::MetricsController`. El namespace de la ruta tiene precedencia sobre `config.controller_namespace`.
20
+ * **Controller — `after_action`:** Nuevo callback que se ejecuta después de la acción exitosa. No se invoca si un `before_action` haltó la cadena ni si la acción lanzó una excepción, siguiendo el comportamiento de Rails. Soporta `only:` y `except:`, y se hereda entre controladores.
21
+ * **Controller — `render` con `headers:`:** El método `render` acepta un keyword `headers:` para adjuntar headers por-respuesta sin mutar `response_headers`. `response_headers` se inicializa con `with_indifferent_access`.
22
+ * **Consumer — `shutdown`:** Nuevo método público que detiene el health check timer y cierra el canal AMQP de forma ordenada. Se invoca automáticamente vía `ensure` cuando `subscribe` termina por cualquier motivo (señal, error, fin de loop), garantizando limpieza completa de recursos.
23
+ * **Configuration — `validate!`:** `BugBunny.configure` invoca `validate!` al final del bloque. Verifica presencia de campos requeridos (`host`, `port`, `username`, `password`, `vhost`) y rangos válidos para timeouts y `channel_prefetch`. Lanza `BugBunny::ConfigurationError` con mensaje descriptivo en lugar de fallar silenciosamente al conectar.
24
+
25
+ ### ⚡ Performance & Robustness
26
+ * **Client — Session & Producer pooling:** `BugBunny::Client` ya no crea ni destruye un `Session` (canal AMQP) y un `Producer` por request. Ambos se cachean como ivars sobre el objeto conexión del pool (`@_bug_bunny_session`, `@_bug_bunny_producer`) y se reutilizan en todos los requests del mismo slot. El cacheo del `Producer` es crítico: el Producer registra un `basic_consume` en el canal para escuchar replies RPC; recrearlo sobre un canal reutilizado intentaría un segundo `basic_consume` causando un error AMQP. Thread-safe sin mutex adicional: `ConnectionPool` garantiza que cada slot es usado por un único thread a la vez.
27
+ * **Session — Double-checked locking:** El método `channel` usa un patrón de double-checked locking con `@channel_mutex` para evitar que múltiples threads creen canales simultáneamente cuando el canal cae. `close` también está protegido por el mismo mutex.
28
+ * **ConsumerMiddleware::Stack — Thread safety:** `use`, `empty?` y `call` están protegidos por un `Mutex`. `call` toma un snapshot del array bajo mutex y ejecuta la cadena fuera del lock, evitando serializar el procesamiento de mensajes durante registros concurrentes.
29
+
30
+ ### 🔍 Observability
31
+ * **`Observability::SENSITIVE_KEYS` expandido:** La lista de claves filtradas en logs crece de 5 a 11 entradas: se agregan `authorization`, `credential`, `private_key`, `csrf`, `session_id` y `passwd`. El matching pasa de comparación exacta por symbol a substring matching en lowercase con normalización de hyphens a underscores, cubriendo variantes como `X-Api-Key`, `user_password` o `accessToken`.
32
+ * **`Observability.sensitive_key?` público:** El método de detección de claves sensibles se expone como método de módulo reutilizable por componentes externos (middlewares, integraciones).
33
+
34
+ ### 🐛 Bug Fixes
35
+ * **Resource — dirty tracking híbrido:** Se corrigen los overrides `changed?` y `changed` para combinar correctamente el tracking nativo de `ActiveModel::Dirty` (atributos tipados) con el tracking manual de atributos dinámicos (`@dynamic_changes`). Anteriormente, `changed?` solo reflejaba atributos tipados. `id=` ahora registra el cambio en `@dynamic_changes` cuando `id` no está declarado como `attribute`.
36
+ * **Resource — inicialización:** `initialize` pasa `attributes` directamente a `super` en lugar del patrón `super() + assign_attributes`, delegando correctamente a `ActiveModel::Model`.
37
+
3
38
  ## [4.6.1] - 2026-03-31
4
39
 
5
40
  ### 🐛 Bug Fixes
@@ -78,33 +113,33 @@
78
113
 
79
114
  ## [4.2.0] - 2026-03-22
80
115
 
81
- ### 🔠Observability & Structured Logging
82
- * **Structured Logs (Key-Value):** Se migraron todos los logs del framework a un formato \`key=value\` estructurado, ideal para herramientas de monitoreo como Datadog o CloudWatch. Se eliminaron emojis y texto libre para mejorar el parseo automático.
83
- * **Lazy Evaluation (Debug Blocks):** Las llamadas a \`logger.debug\` ahora utilizan bloques para evitar la interpolación de strings innecesaria en producción, optimizando el uso de CPU y memoria.
116
+ ### Observability & Structured Logging
117
+ * **Structured Logs (Key-Value):** Se migraron todos los logs del framework a un formato `key=value` estructurado, ideal para herramientas de monitoreo como Datadog o CloudWatch. Se eliminaron emojis y texto libre para mejorar el parseo automático.
118
+ * **Lazy Evaluation (Debug Blocks):** Las llamadas a `logger.debug` ahora utilizan bloques para evitar la interpolación de strings innecesaria en producción, optimizando el uso de CPU y memoria.
84
119
 
85
- ### ðŸ›¡ï¸ Resilience & Connectivity
86
- * **Exponential Backoff:** El \`Consumer\` ahora implementa un algoritmo de reintento exponencial para reconectarse a RabbitMQ, evitando picos de carga durante caídas del broker.
87
- * **Max Reconnect Attempts:** Nueva configuración \`max_reconnect_attempts\` que permite que el worker falle definitivamente tras N intentos, facilitando el reinicio del Pod por parte de orquestadores como Kubernetes.
88
- * **Performance Tuning:** Se desactivaron los \`publisher_confirms\` en el canal del \`Consumer\` al responder RPCs para reducir la latencia de respuesta (round-trips innecesarios).
120
+ ### Resilience & Connectivity
121
+ * **Exponential Backoff:** El `Consumer` ahora implementa un algoritmo de reintento exponencial para reconectarse a RabbitMQ, evitando picos de carga durante caídas del broker.
122
+ * **Max Reconnect Attempts:** Nueva configuración `max_reconnect_attempts` que permite que el worker falle definitivamente tras N intentos, facilitando el reinicio del Pod por parte de orquestadores como Kubernetes.
123
+ * **Performance Tuning:** Se desactivaron los `publisher_confirms` en el canal del `Consumer` al responder RPCs para reducir la latencia de respuesta (round-trips innecesarios).
89
124
 
90
125
  ## [4.1.2] - 2026-03-22
91
126
 
92
- ### Improvements
93
- * **Controller:** Ahora lanza una excepción \`BugBunny::BadRequest\` (400) si el cuerpo de la petición contiene un JSON inválido, mejorando la depuración en el cliente.
94
- * **Resource:** Se añadió una protección a \`.with\` (\`ScopeProxy\`) para asegurar que el contexto sea de un solo uso, evitando efectos secundarios en llamadas encadenadas.
127
+ ### Improvements
128
+ * **Controller:** Ahora lanza una excepción `BugBunny::BadRequest` (400) si el cuerpo de la petición contiene un JSON inválido, mejorando la depuración en el cliente.
129
+ * **Resource:** Se añadió una protección a `.with` (`ScopeProxy`) para asegurar que el contexto sea de un solo uso, evitando efectos secundarios en llamadas encadenadas.
95
130
 
96
131
  ## [4.1.1] - 2026-03-22
97
132
 
98
133
  ### 🐛 Bug Fixes
99
- * **Consumer:** Previene memory leak al detener el `TimerTask` de health check previo antes de realizar una reconexión.
100
- * **Controller:** Corrige la mutación accidental de \`log_tags\` globales al usar una lógica de herencia no destructiva en \`compute_tags\`.
134
+ * **Consumer:** Previene memory leak al detener el `TimerTask` de health check previo antes de realizar una reconexión.
135
+ * **Controller:** Corrige la mutación accidental de `log_tags` globales al usar una lógica de herencia no destructiva en `compute_tags`.
101
136
 
102
137
  ## [4.1.0] - 2026-03-22
103
138
 
104
139
  ### 🚀 New Features & Improvements
105
- * **Faraday-style Client API:** Se introdujo el método \`Client#send\` como punto de entrada genérico, permitiendo una sintaxis más familiar y flexible.
106
- * **Flexible Delivery Modes:** Introducción del atributo \`delivery_mode\` (:rpc o :publish). Ahora es posible configurar la estrategia de envío a nivel de cliente o por cada petición individual.
107
- * **Smart Request Defaults:** Los métodos \`request\` y \`publish\` ahora delegan internamente en \`send\`, manteniendo la compatibilidad pero beneficiándose de la nueva arquitectura de peticiones.
140
+ * **Faraday-style Client API:** Se introdujo el método `Client#send` como punto de entrada genérico, permitiendo una sintaxis más familiar y flexible.
141
+ * **Flexible Delivery Modes:** Introducción del atributo `delivery_mode` (:rpc o :publish). Ahora es posible configurar la estrategia de envío a nivel de cliente o por cada petición individual.
142
+ * **Smart Request Defaults:** Los métodos `request` y `publish` ahora delegan internamente en `send`, manteniendo la compatibilidad pero beneficiándose de la nueva arquitectura de peticiones.
108
143
 
109
144
  ## [4.0.1] - 2026-03-13
110
145