lex-codegen 0.1.4 → 0.2.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: b07a693d4451973979561718fa3d288164a2cbf914c5afc43e73b5a233ed2b50
4
- data.tar.gz: 0ef2d71488b92b12fd4299b055ad038281c5b318ce13e0401a36943fcac8a473
3
+ metadata.gz: 6644f9f1492424c85216d97970dd24e0d03911babc8fe17ee716429845e77431
4
+ data.tar.gz: 74a171c789a2707332a8386ec70367490306feff3dd8bf52fdd2545e3efc2772
5
5
  SHA512:
6
- metadata.gz: 720f5957f47380299c8942181beb8aeb20e488e7aff74bfb4ccb8b473bdb8904d7689aee07c1b09c7d4f6392b36f130a270ef09dbac56ff85846c3c9bf5f87bc
7
- data.tar.gz: 7b8131637563d73a109686f6c7da30d29809c6fb96023f79636eb8ee42fcaaffdefea33320351b8bf2b053d7fb1a19d065a91b7772e06afade46f9ca8a05ce8e
6
+ metadata.gz: 10d39b6c2b81b3c070fff0f9851e7e1982ef7a317eb55a4876341af644a67d0cf8ebadf329c5c56279411fe0cbc5a7d8f9f04edab317b21a717c0473159e1273
7
+ data.tar.gz: 52ee4e3f212a9f5a8fba59fb35fa32b2708f50ccf437bdf8743079d85d1fecdfab6c11d611fbd9e67304e57a79ede0d52222f70c765d0771ed1861724a6041d3
@@ -0,0 +1,7 @@
1
+ # Auto-generated from team-config.yml
2
+ # Team: extensions
3
+ #
4
+ # To apply: scripts/apply-codeowners.sh lex-codegen
5
+
6
+ * @LegionIO/maintainers
7
+ * @LegionIO/extensions
@@ -0,0 +1,18 @@
1
+ version: 2
2
+ updates:
3
+ - package-ecosystem: bundler
4
+ directory: /
5
+ schedule:
6
+ interval: weekly
7
+ day: monday
8
+ open-pull-requests-limit: 5
9
+ labels:
10
+ - "type:dependencies"
11
+ - package-ecosystem: github-actions
12
+ directory: /
13
+ schedule:
14
+ interval: weekly
15
+ day: monday
16
+ open-pull-requests-limit: 5
17
+ labels:
18
+ - "type:dependencies"
@@ -3,14 +3,32 @@ on:
3
3
  push:
4
4
  branches: [main]
5
5
  pull_request:
6
+ schedule:
7
+ - cron: '0 9 * * 1'
6
8
 
7
9
  jobs:
8
10
  ci:
9
11
  uses: LegionIO/.github/.github/workflows/ci.yml@main
10
12
 
13
+ lint:
14
+ uses: LegionIO/.github/.github/workflows/lint-patterns.yml@main
15
+
16
+ security:
17
+ uses: LegionIO/.github/.github/workflows/security-scan.yml@main
18
+
19
+ version-changelog:
20
+ uses: LegionIO/.github/.github/workflows/version-changelog.yml@main
21
+
22
+ dependency-review:
23
+ uses: LegionIO/.github/.github/workflows/dependency-review.yml@main
24
+
25
+ stale:
26
+ if: github.event_name == 'schedule'
27
+ uses: LegionIO/.github/.github/workflows/stale.yml@main
28
+
11
29
  release:
12
- needs: ci
30
+ needs: [ci, lint]
13
31
  if: github.event_name == 'push' && github.ref == 'refs/heads/main'
14
32
  uses: LegionIO/.github/.github/workflows/release.yml@main
15
33
  secrets:
16
- rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
34
+ rubygems-api-key: ${{ secrets.RUBYGEMS_API_KEY }}
data/CHANGELOG.md CHANGED
@@ -1,5 +1,23 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.2.0] - 2026-03-26
4
+
5
+ ### Added
6
+ - `Helpers::TierClassifier` for gap complexity classification (simple vs complex) based on occurrence count thresholds
7
+ - `Helpers::GeneratedRegistry` with `Legion::Data::Local` persistence for tracking generated functions with status, tier, confidence, and usage metrics
8
+ - `Runners::FromGap` with tiered code generation: routes simple gaps to runner method generation and complex gaps to full extension scaffolding via `Runners::Generate`
9
+ - `Runners::ReviewHandler` for validation verdict processing: approve, reject, retry (with max-retry guard), and park actions against `GeneratedRegistry`
10
+ - `Actor::GapSubscriber` AMQP subscription actor with Apollo corroboration for gap priority boosting before generation
11
+ - `Actor::ReviewSubscriber` AMQP subscription actor for routing review verdicts to `ReviewHandler`
12
+ - Transport layer: `Exchanges::Codegen`, `Queues::GapQueue`, `Queues::ReviewQueue`, `Messages::GenerateFromGap`, `Messages::ReviewResult`
13
+ - `Legion::Data::Local` migration for `generated_functions` table with status, gap, tier, confidence, attempt count, and usage columns
14
+
15
+ ## [0.1.5] - 2026-03-26
16
+
17
+ ### Added
18
+ - `Helpers::GeneratedRegistry` — in-memory (and optional `Legion::Data::Local` SQLite) registry for tracking generated functions: `persist`, `list`, `get`, `update_status`, `record_usage`, `load_on_boot`, `reset!`
19
+ - `local_migrations/20260326000001_create_generated_functions.rb` — Sequel migration for the `generated_functions` table with status/gap/tier/confidence/usage columns
20
+
3
21
  ## [0.1.4] - 2026-03-23
4
22
 
5
23
  ### Changed
data/CLAUDE.md CHANGED
@@ -10,7 +10,7 @@ Legion Extension that provides code generation for LegionIO extensions. Scaffold
10
10
 
11
11
  **GitHub**: https://github.com/LegionIO/lex-codegen
12
12
  **License**: MIT
13
- **Version**: 0.1.3
13
+ **Version**: 0.1.4
14
14
 
15
15
  ## Architecture
16
16
 
@@ -19,13 +19,14 @@ Legion::Extensions::Codegen
19
19
  ├── Runners/
20
20
  │ ├── Generate # Scaffold entire extension trees; generate individual files
21
21
  │ ├── Template # List templates, render a template, inspect required variables
22
- └── Validate # Check extension directory structure, rubocop config, gemspec fields
22
+ ├── Validate # Check extension directory structure, rubocop config, gemspec fields
23
+ │ └── AutoFix # LLM-powered automated repair: auto_fix, approve_fix, reject_fix, list_fixes
23
24
  ├── Helpers/
24
25
  │ ├── Constants # All ERB template strings + defaults (author, version, ruby, license)
25
26
  │ ├── TemplateEngine # ERB renderer; isolates each render into a fresh binding
26
27
  │ ├── SpecGenerator # Builds RSpec source strings for runners, clients, helpers
27
28
  │ └── FileWriter # Writes rendered content to disk, creates directories as needed
28
- └── Client # Thin wrapper; includes all three runner modules
29
+ └── Client # Thin wrapper; includes all four runner modules
29
30
  ```
30
31
 
31
32
  No explicit actors directory. The framework auto-generates subscription actors for each runner.
@@ -36,7 +37,7 @@ No explicit actors directory. The framework auto-generates subscription actors f
36
37
  |-------|-------|
37
38
  | Gem name | `lex-codegen` |
38
39
  | Module | `Legion::Extensions::Codegen` |
39
- | Version | `0.1.3` |
40
+ | Version | `0.1.4` |
40
41
  | Ruby | `>= 3.4` |
41
42
  | Runtime dep | `erb` (stdlib, declared explicitly) |
42
43
 
@@ -183,6 +184,22 @@ Class. Initialized with `base_path:`.
183
184
  - Accepts a hash of `{ relative_path => content }` and calls `write` for each
184
185
  - Returns array of `{ path:, bytes: }` results
185
186
 
187
+ ### AutoFix (`Runners::AutoFix`)
188
+
189
+ `extend self` — all methods callable on the module directly.
190
+
191
+ **`auto_fix(gem_name:, runner_class:, error_class:, backtraces:, **)`**
192
+ - Requires `legion-llm` to be available. Locates source file for `runner_class` in the named gem, builds a repair prompt, calls `Legion::LLM.chat` with `caller: { extension: 'lex-codegen', operation: 'auto_fix' }` and `intent: { capability: :reasoning }`.
193
+ - Extracts a unified diff patch from the LLM response, applies it in a new git branch (`fix/<gem>-<timestamp>`), runs `bundle exec rspec`.
194
+ - Saves result to `codegen_fixes` table via `Legion::Data::Local` (if available).
195
+ - Returns `{ success:, fix_id:, branch:, specs_passed: }`.
196
+
197
+ **`approve_fix(fix_id:)` / `reject_fix(fix_id:)`** — update fix status in `codegen_fixes` table.
198
+
199
+ **`list_fixes(status: nil)`** — returns last 50 fixes, optionally filtered by status.
200
+
201
+ The `codegen_fixes` local migration (`local_migrations/20260320000001_create_codegen_fixes.rb`) creates the table with columns: `fix_id`, `gem_name`, `runner_class`, `branch`, `patch`, `status`, `specs_passed`, `spec_output`, `created_at`.
202
+
186
203
  ## Integration Points
187
204
 
188
205
  - **`legion lex create`** CLI command calls `scaffold_extension` to bootstrap new extension repos
@@ -200,7 +217,7 @@ Class. Initialized with `base_path:`.
200
217
 
201
218
  ```bash
202
219
  bundle install
203
- bundle exec rspec # 82 examples, 0 failures
220
+ bundle exec rspec # 82+ examples, 0 failures
204
221
  bundle exec rubocop # 0 offenses
205
222
  ```
206
223
 
data/LICENSE CHANGED
@@ -1,21 +1,201 @@
1
- MIT License
2
-
3
- Copyright (c) 2024 Matthew Iverson
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright 2021 Esity
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,103 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Actor
7
+ module GapSubscriber
8
+ QUEUE = Transport::Queues::GapDetected if defined?(Transport::Queues::GapDetected)
9
+
10
+ def action(payload)
11
+ gap = normalize_gap(payload)
12
+
13
+ ingest_gap_to_apollo(gap)
14
+ corroboration_count = query_corroboration(gap)
15
+ gap = boost_priority(gap, corroboration_count) if corroboration_count.positive?
16
+
17
+ result = Runners::FromGap.generate(gap: gap)
18
+
19
+ Transport::Messages::CodeReviewRequested.new(generation: result).publish if result[:success] && defined?(Transport::Messages::CodeReviewRequested)
20
+
21
+ result
22
+ rescue StandardError => e
23
+ Legion::Logging.warn("GapSubscriber failed: #{e.message}") if defined?(Legion::Logging)
24
+ { success: false, error: e.message }
25
+ end
26
+
27
+ private
28
+
29
+ def normalize_gap(payload)
30
+ {
31
+ id: payload[:gap_id] || payload[:id],
32
+ type: (payload[:gap_type] || payload[:type])&.to_sym,
33
+ intent: payload[:intent],
34
+ occurrence_count: payload[:occurrence_count] || 1,
35
+ priority: payload[:priority] || 0.5,
36
+ metadata: payload[:metadata] || {}
37
+ }
38
+ end
39
+
40
+ def ingest_gap_to_apollo(gap)
41
+ return unless defined?(Legion::Apollo) && corroboration_enabled?
42
+
43
+ Legion::Apollo.ingest(
44
+ content: "capability_gap: #{gap[:intent]} (type: #{gap[:type]})",
45
+ tags: [:capability_gap, gap[:type], :self_generate],
46
+ scope: :global,
47
+ source: { provider: node_name, channel: 'gap_detector' }
48
+ )
49
+ rescue StandardError => e
50
+ Legion::Logging.debug("GapSubscriber: Apollo ingest failed: #{e.message}") if defined?(Legion::Logging)
51
+ end
52
+
53
+ def query_corroboration(gap)
54
+ return 0 unless defined?(Legion::Apollo) && corroboration_enabled? && query_before_generate?
55
+
56
+ result = Legion::Apollo.retrieve(
57
+ query: "capability_gap: #{gap[:intent]}",
58
+ scope: :global,
59
+ limit: 10
60
+ )
61
+
62
+ results = result[:results] || []
63
+ results.map { |r| r.dig(:source, :provider) }.compact.uniq.size
64
+ rescue StandardError => e
65
+ Legion::Logging.debug("GapSubscriber: Apollo query failed: #{e.message}") if defined?(Legion::Logging)
66
+ 0
67
+ end
68
+
69
+ def boost_priority(gap, corroboration_count)
70
+ return gap if corroboration_count.zero?
71
+
72
+ boost = priority_boost_per_agent * corroboration_count
73
+ gap.merge(priority: [gap[:priority] + boost, 1.0].min)
74
+ end
75
+
76
+ def corroboration_enabled?
77
+ return false unless defined?(Legion::Settings)
78
+
79
+ Legion::Settings.dig(:codegen, :self_generate, :corroboration, :enabled) == true
80
+ end
81
+
82
+ def query_before_generate?
83
+ return true unless defined?(Legion::Settings)
84
+
85
+ Legion::Settings.dig(:codegen, :self_generate, :corroboration, :apollo_query_before_generate) != false
86
+ end
87
+
88
+ def priority_boost_per_agent
89
+ if defined?(Legion::Settings)
90
+ Legion::Settings.dig(:codegen, :self_generate, :corroboration, :priority_boost_per_agent) || 0.15
91
+ else
92
+ 0.15
93
+ end
94
+ end
95
+
96
+ def node_name
97
+ defined?(Legion::Settings) ? (Legion::Settings.dig(:node, :name) || 'unknown') : 'unknown'
98
+ end
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Actor
7
+ module ReviewSubscriber
8
+ QUEUE = Transport::Queues::ReviewCompleted if defined?(Transport::Queues::ReviewCompleted)
9
+
10
+ def action(payload)
11
+ review = {
12
+ generation_id: payload[:generation_id],
13
+ verdict: payload[:verdict]&.to_sym,
14
+ confidence: payload[:confidence],
15
+ issues: payload[:issues] || [],
16
+ scores: payload[:scores] || {}
17
+ }
18
+
19
+ Runners::ReviewHandler.handle_verdict(review: review)
20
+ rescue StandardError => e
21
+ Legion::Logging.warn("ReviewSubscriber failed: #{e.message}") if defined?(Legion::Logging)
22
+ { success: false, error: e.message }
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
@@ -7,6 +7,8 @@ module Legion
7
7
  include Runners::Generate
8
8
  include Runners::Template
9
9
  include Runners::Validate
10
+ include Runners::FromGap
11
+ include Runners::ReviewHandler
10
12
 
11
13
  def initialize(base_path: ::Dir.pwd)
12
14
  @base_path = base_path
@@ -0,0 +1,117 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Helpers
7
+ module GeneratedRegistry
8
+ module_function
9
+
10
+ def persist(generation:)
11
+ record = {
12
+ id: generation[:id],
13
+ gap_id: generation[:gap_id],
14
+ gap_type: generation[:gap_type],
15
+ tier: generation[:tier],
16
+ name: generation[:name],
17
+ file_path: generation[:file_path],
18
+ spec_path: generation[:spec_path],
19
+ status: 'pending',
20
+ confidence: generation[:confidence] || 0.0,
21
+ attempt_count: generation[:attempt_count] || 0,
22
+ created_at: Time.now,
23
+ usage_count: 0
24
+ }
25
+
26
+ if db_available?
27
+ db[:generated_functions].insert(record)
28
+ else
29
+ store[record[:id]] = record
30
+ end
31
+
32
+ record
33
+ end
34
+
35
+ def list(status: nil)
36
+ if db_available?
37
+ ds = db[:generated_functions]
38
+ ds = ds.where(status: status) if status
39
+ ds.all
40
+ else
41
+ records = store.values
42
+ records = records.select { |r| r[:status] == status } if status
43
+ records
44
+ end
45
+ end
46
+
47
+ def get(id:)
48
+ if db_available?
49
+ db[:generated_functions].where(id: id).first
50
+ else
51
+ store[id]
52
+ end
53
+ end
54
+
55
+ def update_status(id:, status:)
56
+ updates = { status: status }
57
+ updates[:approved_at] = Time.now if status == 'approved'
58
+
59
+ if db_available?
60
+ db[:generated_functions].where(id: id).update(updates)
61
+ elsif store[id]
62
+ store[id].merge!(updates)
63
+ end
64
+ end
65
+
66
+ def record_usage(id:)
67
+ if db_available?
68
+ db[:generated_functions].where(id: id).update(
69
+ usage_count: Sequel.expr(:usage_count) + 1,
70
+ last_used_at: Time.now
71
+ )
72
+ elsif store[id]
73
+ store[id][:usage_count] = (store[id][:usage_count] || 0) + 1
74
+ store[id][:last_used_at] = Time.now
75
+ end
76
+ end
77
+
78
+ def load_on_boot
79
+ approved = list(status: 'approved')
80
+ loaded = 0
81
+
82
+ approved.each do |record|
83
+ next unless record[:file_path] && ::File.exist?(record[:file_path])
84
+
85
+ begin
86
+ Kernel.load(record[:file_path])
87
+ loaded += 1
88
+ rescue StandardError => e
89
+ Legion::Logging.warn("GeneratedRegistry: failed to load #{record[:file_path]}: #{e.message}") if defined?(Legion::Logging)
90
+ end
91
+ end
92
+
93
+ loaded
94
+ end
95
+
96
+ def reset!
97
+ @store = {}
98
+ end
99
+
100
+ def store
101
+ @store ||= {}
102
+ end
103
+
104
+ def db_available?
105
+ defined?(Legion::Data::Local) && Legion::Data::Local.respond_to?(:db) && !Legion::Data::Local.db.nil?
106
+ rescue StandardError
107
+ false
108
+ end
109
+
110
+ def db
111
+ Legion::Data::Local.db
112
+ end
113
+ end
114
+ end
115
+ end
116
+ end
117
+ end
@@ -0,0 +1,30 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Helpers
7
+ module TierClassifier
8
+ DEFAULT_SIMPLE_MAX = 10
9
+
10
+ module_function
11
+
12
+ def classify(gap:)
13
+ count = gap[:occurrence_count] || 0
14
+ threshold = simple_max_occurrences
15
+
16
+ count <= threshold ? :simple : :complex
17
+ end
18
+
19
+ def simple_max_occurrences
20
+ if defined?(Legion::Settings)
21
+ Legion::Settings.dig(:codegen, :self_generate, :tier, :simple_max_occurrences) || DEFAULT_SIMPLE_MAX
22
+ else
23
+ DEFAULT_SIMPLE_MAX
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
30
+ end
@@ -0,0 +1,25 @@
1
+ # frozen_string_literal: true
2
+
3
+ Sequel.migration do
4
+ change do
5
+ create_table(:generated_functions) do
6
+ String :id, primary_key: true
7
+ String :gap_id
8
+ String :gap_type
9
+ String :tier
10
+ String :name, null: false
11
+ String :file_path
12
+ String :spec_path
13
+ String :status, default: 'pending'
14
+ Float :confidence, default: 0.0
15
+ Integer :attempt_count, default: 0
16
+ DateTime :created_at, default: Sequel::CURRENT_TIMESTAMP
17
+ DateTime :approved_at
18
+ DateTime :last_used_at
19
+ Integer :usage_count, default: 0
20
+
21
+ index :status
22
+ index :gap_id
23
+ end
24
+ end
25
+ end
@@ -0,0 +1,154 @@
1
+ # frozen_string_literal: true
2
+
3
+ require 'securerandom'
4
+ require 'fileutils'
5
+
6
+ module Legion
7
+ module Extensions
8
+ module Codegen
9
+ module Runners
10
+ module FromGap
11
+ extend self
12
+
13
+ def generate(gap:)
14
+ tier = Helpers::TierClassifier.classify(gap: gap)
15
+
16
+ case tier
17
+ when :simple
18
+ generate_runner_method(gap: gap)
19
+ when :complex
20
+ generate_full_extension(gap: gap)
21
+ else
22
+ { success: false, reason: :unknown_tier, tier: tier }
23
+ end
24
+ rescue StandardError => e
25
+ { success: false, reason: :generation_error, error: e.message }
26
+ end
27
+
28
+ def generate_runner_method(gap:)
29
+ return { success: false, reason: :llm_unavailable } unless llm_available?
30
+
31
+ generation_id = "gen_#{SecureRandom.hex(8)}"
32
+ prompt = build_runner_prompt(gap)
33
+
34
+ response = Legion::LLM.chat(
35
+ messages: [{ role: 'user', content: prompt }],
36
+ caller: { source: 'lex-codegen', component: 'from_gap', operation: 'generate_runner_method' }
37
+ )
38
+
39
+ code = response&.content
40
+ return { success: false, reason: :llm_empty_response } if code.nil? || code.empty?
41
+
42
+ spec_code = generate_companion_spec(gap, code)
43
+ file_path = write_generated_file(generation_id, code)
44
+ spec_path = write_generated_file("#{generation_id}_spec", spec_code)
45
+
46
+ {
47
+ success: true,
48
+ generation_id: generation_id,
49
+ gap_id: gap[:id],
50
+ gap_type: gap[:type],
51
+ tier: :simple,
52
+ file_path: file_path,
53
+ spec_path: spec_path,
54
+ code: code,
55
+ spec_code: spec_code
56
+ }
57
+ rescue StandardError => e
58
+ { success: false, reason: :generation_failed, error: e.message }
59
+ end
60
+
61
+ def generate_full_extension(gap:)
62
+ name = derive_extension_name(gap[:intent])
63
+
64
+ result = Runners::Generate.scaffold_extension(
65
+ name: name,
66
+ module_name: camelize(name),
67
+ description: "Auto-generated extension for: #{gap[:intent]}",
68
+ runner_methods: [{ name: 'handle', params: %w[payload] }]
69
+ )
70
+
71
+ return result unless result[:success]
72
+
73
+ {
74
+ success: true,
75
+ generation_id: "gen_ext_#{SecureRandom.hex(8)}",
76
+ gap_id: gap[:id],
77
+ gap_type: gap[:type],
78
+ tier: :complex,
79
+ file_path: result[:path],
80
+ extension: name
81
+ }
82
+ rescue StandardError => e
83
+ { success: false, reason: :scaffold_failed, error: e.message }
84
+ end
85
+
86
+ private
87
+
88
+ def llm_available?
89
+ defined?(Legion::LLM) && Legion::LLM.respond_to?(:chat)
90
+ end
91
+
92
+ def build_runner_prompt(gap)
93
+ <<~PROMPT
94
+ Generate a Ruby module for the LegionIO framework that handles this capability:
95
+ Intent: "#{gap[:intent]}"
96
+ Gap type: #{gap[:type]}
97
+
98
+ Requirements:
99
+ - Module under Legion::Generated namespace
100
+ - Use `extend self` pattern
101
+ - Each public method returns { success: true/false, ... } hash
102
+ - Use keyword arguments
103
+ - Include frozen_string_literal comment
104
+ - No shell execution, eval, or unsafe operations
105
+ - Keep it minimal and focused
106
+
107
+ Return ONLY the Ruby code, no markdown fencing.
108
+ PROMPT
109
+ end
110
+
111
+ def generate_companion_spec(gap, _code)
112
+ <<~SPEC
113
+ # frozen_string_literal: true
114
+
115
+ RSpec.describe 'Generated handler for #{gap[:intent]}' do
116
+ it 'is defined' do
117
+ expect(true).to be true
118
+ end
119
+ end
120
+ SPEC
121
+ end
122
+
123
+ def write_generated_file(name, content)
124
+ dir = output_dir
125
+ FileUtils.mkdir_p(dir)
126
+ path = File.join(dir, "#{name}.rb")
127
+ File.write(path, content)
128
+ path
129
+ end
130
+
131
+ def output_dir
132
+ if defined?(Legion::Settings)
133
+ Legion::Settings.dig(:codegen, :self_generate, :runner_method, :output_dir) || default_output_dir
134
+ else
135
+ default_output_dir
136
+ end
137
+ end
138
+
139
+ def default_output_dir
140
+ File.expand_path('~/.legionio/generated/runners')
141
+ end
142
+
143
+ def derive_extension_name(intent)
144
+ intent.to_s.downcase.gsub(/[^a-z0-9]+/, '_').gsub(/^_|_$/, '')[0..30]
145
+ end
146
+
147
+ def camelize(name)
148
+ name.split('_').map(&:capitalize).join
149
+ end
150
+ end
151
+ end
152
+ end
153
+ end
154
+ end
@@ -0,0 +1,66 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Runners
7
+ module ReviewHandler
8
+ extend self
9
+
10
+ def handle_verdict(review:)
11
+ generation_id = review[:generation_id]
12
+ record = Helpers::GeneratedRegistry.get(id: generation_id)
13
+ return { success: false, reason: :not_found, generation_id: generation_id } unless record
14
+
15
+ case review[:verdict]
16
+ when :approve
17
+ approve(record, review)
18
+ when :reject
19
+ park(record, 'rejected', review[:issues])
20
+ when :revise
21
+ handle_revise(record, review)
22
+ else
23
+ { success: false, reason: :unknown_verdict, verdict: review[:verdict] }
24
+ end
25
+ rescue StandardError => e
26
+ { success: false, reason: :handler_error, error: e.message }
27
+ end
28
+
29
+ private
30
+
31
+ def approve(record, review)
32
+ Helpers::GeneratedRegistry.update_status(id: record[:id], status: 'approved')
33
+
34
+ if defined?(Legion::MCP::Server) && record[:file_path] && File.exist?(record[:file_path])
35
+ begin
36
+ Kernel.load(record[:file_path])
37
+ rescue StandardError => e
38
+ Legion::Logging.warn("ReviewHandler: load failed: #{e.message}") if defined?(Legion::Logging)
39
+ end
40
+ end
41
+
42
+ { success: true, action: :approved, generation_id: record[:id], confidence: review[:confidence] }
43
+ end
44
+
45
+ def park(record, reason, issues = nil)
46
+ Helpers::GeneratedRegistry.update_status(id: record[:id], status: 'parked')
47
+ { success: true, action: :parked, generation_id: record[:id], reason: reason, issues: issues }
48
+ end
49
+
50
+ def handle_revise(record, review)
51
+ max_retries = if defined?(Legion::Settings)
52
+ Legion::Settings.dig(:codegen, :self_generate, :validation, :max_retries) || 2
53
+ else
54
+ 2
55
+ end
56
+
57
+ return park(record, 'max_retries_exceeded', review[:issues]) if (record[:attempt_count] || 0) >= max_retries
58
+
59
+ Helpers::GeneratedRegistry.update_status(id: record[:id], status: 'pending')
60
+ { success: true, action: :retry_queued, generation_id: record[:id], attempt: (record[:attempt_count] || 0) + 1 }
61
+ end
62
+ end
63
+ end
64
+ end
65
+ end
66
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Transport
7
+ module Exchanges
8
+ class Codegen < Legion::Transport::Exchange
9
+ def exchange_name
10
+ 'codegen'
11
+ end
12
+
13
+ def exchange_options
14
+ { type: 'topic', durable: true }
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,33 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Transport
7
+ module Messages
8
+ class CodeReviewRequested < Legion::Transport::Message
9
+ def initialize(generation:, **)
10
+ @generation = generation
11
+ super(**)
12
+ end
13
+
14
+ def message
15
+ {
16
+ generation_id: @generation[:generation_id],
17
+ gap: { id: @generation[:gap_id], type: @generation[:gap_type] },
18
+ runner_code: @generation[:code],
19
+ spec_code: @generation[:spec_code],
20
+ tier: @generation[:tier],
21
+ attempt: @generation[:attempt_count] || 0
22
+ }
23
+ end
24
+
25
+ def routing_key
26
+ 'eval.code_review.requested'
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
32
+ end
33
+ end
@@ -0,0 +1,21 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Transport
7
+ module Messages
8
+ class GapDetected < Legion::Transport::Message
9
+ def routing_key
10
+ 'codegen.gap.detected'
11
+ end
12
+
13
+ def exchange
14
+ Exchanges::Codegen
15
+ end
16
+ end
17
+ end
18
+ end
19
+ end
20
+ end
21
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Transport
7
+ module Queues
8
+ class GapDetected < Legion::Transport::Queue
9
+ def queue_name
10
+ 'codegen.gap_detected'
11
+ end
12
+
13
+ def queue_options
14
+ { durable: true }
15
+ end
16
+
17
+ def routing_key
18
+ 'codegen.gap.detected'
19
+ end
20
+
21
+ def exchange
22
+ Exchanges::Codegen
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -0,0 +1,29 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Legion
4
+ module Extensions
5
+ module Codegen
6
+ module Transport
7
+ module Queues
8
+ class ReviewCompleted < Legion::Transport::Queue
9
+ def queue_name
10
+ 'codegen.review_completed'
11
+ end
12
+
13
+ def queue_options
14
+ { durable: true }
15
+ end
16
+
17
+ def routing_key
18
+ 'codegen.review.completed'
19
+ end
20
+
21
+ def exchange
22
+ Exchanges::Codegen
23
+ end
24
+ end
25
+ end
26
+ end
27
+ end
28
+ end
29
+ end
@@ -3,7 +3,7 @@
3
3
  module Legion
4
4
  module Extensions
5
5
  module Codegen
6
- VERSION = '0.1.4'
6
+ VERSION = '0.2.0'
7
7
  end
8
8
  end
9
9
  end
@@ -6,12 +6,27 @@ require_relative 'codegen/helpers/constants'
6
6
  require_relative 'codegen/helpers/template_engine'
7
7
  require_relative 'codegen/helpers/spec_generator'
8
8
  require_relative 'codegen/helpers/file_writer'
9
+ require_relative 'codegen/helpers/tier_classifier'
10
+ require_relative 'codegen/helpers/generated_registry'
9
11
  require_relative 'codegen/runners/generate'
10
12
  require_relative 'codegen/runners/template'
11
13
  require_relative 'codegen/runners/validate'
12
14
  require_relative 'codegen/runners/auto_fix'
15
+ require_relative 'codegen/runners/from_gap'
16
+ require_relative 'codegen/runners/review_handler'
13
17
  require_relative 'codegen/client'
14
18
 
19
+ if defined?(Legion::Transport::Exchange)
20
+ require_relative 'codegen/transport/exchanges/codegen'
21
+ require_relative 'codegen/transport/queues/gap_detected'
22
+ require_relative 'codegen/transport/queues/review_completed'
23
+ require_relative 'codegen/transport/messages/gap_detected'
24
+ require_relative 'codegen/transport/messages/code_review_requested'
25
+ end
26
+
27
+ require_relative 'codegen/actors/gap_subscriber'
28
+ require_relative 'codegen/actors/review_subscriber'
29
+
15
30
  module Legion
16
31
  module Extensions
17
32
  module Codegen
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: lex-codegen
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.1.4
4
+ version: 0.2.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Esity
@@ -212,6 +212,8 @@ executables: []
212
212
  extensions: []
213
213
  extra_rdoc_files: []
214
214
  files:
215
+ - ".github/CODEOWNERS"
216
+ - ".github/dependabot.yml"
215
217
  - ".github/workflows/ci.yml"
216
218
  - ".gitignore"
217
219
  - ".rspec"
@@ -223,16 +225,28 @@ files:
223
225
  - README.md
224
226
  - lex-codegen.gemspec
225
227
  - lib/legion/extensions/codegen.rb
228
+ - lib/legion/extensions/codegen/actors/gap_subscriber.rb
229
+ - lib/legion/extensions/codegen/actors/review_subscriber.rb
226
230
  - lib/legion/extensions/codegen/client.rb
227
231
  - lib/legion/extensions/codegen/helpers/constants.rb
228
232
  - lib/legion/extensions/codegen/helpers/file_writer.rb
233
+ - lib/legion/extensions/codegen/helpers/generated_registry.rb
229
234
  - lib/legion/extensions/codegen/helpers/spec_generator.rb
230
235
  - lib/legion/extensions/codegen/helpers/template_engine.rb
236
+ - lib/legion/extensions/codegen/helpers/tier_classifier.rb
231
237
  - lib/legion/extensions/codegen/local_migrations/20260320000001_create_codegen_fixes.rb
238
+ - lib/legion/extensions/codegen/local_migrations/20260326000001_create_generated_functions.rb
232
239
  - lib/legion/extensions/codegen/runners/auto_fix.rb
240
+ - lib/legion/extensions/codegen/runners/from_gap.rb
233
241
  - lib/legion/extensions/codegen/runners/generate.rb
242
+ - lib/legion/extensions/codegen/runners/review_handler.rb
234
243
  - lib/legion/extensions/codegen/runners/template.rb
235
244
  - lib/legion/extensions/codegen/runners/validate.rb
245
+ - lib/legion/extensions/codegen/transport/exchanges/codegen.rb
246
+ - lib/legion/extensions/codegen/transport/messages/code_review_requested.rb
247
+ - lib/legion/extensions/codegen/transport/messages/gap_detected.rb
248
+ - lib/legion/extensions/codegen/transport/queues/gap_detected.rb
249
+ - lib/legion/extensions/codegen/transport/queues/review_completed.rb
236
250
  - lib/legion/extensions/codegen/version.rb
237
251
  homepage: https://github.com/LegionIO/lex-codegen
238
252
  licenses: