rosett-ai 1.8.0 → 1.11.9

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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +277 -0
  3. data/README.md +2 -2
  4. data/conf/schemas/rai_config_schema.json +10 -0
  5. data/lib/rosett_ai/compiler/backends/agents_md_backend.rb +10 -3
  6. data/lib/rosett_ai/compiler/backends/claude_backend.rb +11 -1
  7. data/lib/rosett_ai/compiler/compilation_pipeline.rb +25 -0
  8. data/lib/rosett_ai/compiler/lean_bundle.rb +150 -0
  9. data/lib/rosett_ai/compiler/lean_emitter.rb +76 -0
  10. data/lib/rosett_ai/desktop/gui_logger.rb +1 -1
  11. data/lib/rosett_ai/exit_codes.rb +2 -1
  12. data/lib/rosett_ai/init/mcp_registrar.rb +56 -19
  13. data/lib/rosett_ai/mcp/enforcement/hook_generator.rb +6 -2
  14. data/lib/rosett_ai/mcp/governance.rb +1 -0
  15. data/lib/rosett_ai/mcp/tools/compile_status_tool.rb +58 -13
  16. data/lib/rosett_ai/mcp/tools/config_compile_tool.rb +40 -7
  17. data/lib/rosett_ai/mcp/tools/hook_install_tool.rb +14 -0
  18. data/lib/rosett_ai/mcp/tools/optimize_tool.rb +73 -0
  19. data/lib/rosett_ai/optimize/corpus.rb +79 -0
  20. data/lib/rosett_ai/optimize/detector.rb +27 -0
  21. data/lib/rosett_ai/optimize/detectors/conflict.rb +50 -0
  22. data/lib/rosett_ai/optimize/detectors/overlap.rb +74 -0
  23. data/lib/rosett_ai/optimize/detectors/staleness.rb +61 -0
  24. data/lib/rosett_ai/optimize/detectors/token_cost.rb +44 -0
  25. data/lib/rosett_ai/optimize/finding.rb +36 -0
  26. data/lib/rosett_ai/optimize/proposal_writer.rb +54 -0
  27. data/lib/rosett_ai/optimize/report_writer.rb +72 -0
  28. data/lib/rosett_ai/optimize/runner.rb +38 -0
  29. data/lib/rosett_ai/optimize/thresholds.rb +52 -0
  30. data/lib/rosett_ai/optimize.rb +33 -0
  31. data/lib/rosett_ai/path_resolver.rb +25 -0
  32. data/lib/rosett_ai/plugins/registry.rb +45 -15
  33. data/lib/rosett_ai/provenance/entry.rb +1 -2
  34. data/lib/rosett_ai/rai_config.rb +3 -0
  35. data/lib/rosett_ai/rules/status_checker.rb +144 -0
  36. data/lib/rosett_ai/telemetry/json_lines_writer.rb +1 -1
  37. data/lib/rosett_ai/thor/cli.rb +7 -61
  38. data/lib/rosett_ai/thor/command_tree.rb +79 -0
  39. data/lib/rosett_ai/thor/tasks/compile.rb +137 -2
  40. data/lib/rosett_ai/thor/tasks/optimize.rb +103 -0
  41. data/lib/rosett_ai/thor/tasks/rules.rb +125 -0
  42. data/lib/rosett_ai/version.rb +1 -1
  43. data/lib/rosett_ai.rb +2 -0
  44. data/locales/en.yml +15 -0
  45. metadata +22 -3
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 4199d3afb89e1e5378dad08e0f989c085375643d7f48436a4786c7b7c615f646
4
- data.tar.gz: 3af391ea23387c019d6247cb8e77ca78586f5e0e9626cca37b1946d3f4dff31f
3
+ metadata.gz: 29efd46ca8a39fb0d2de3e58c1f2a5b3ef2194c3063bc61a6a79d60b1b2dc557
4
+ data.tar.gz: 0f5f50387c1a34384cd67fcbf9c0a489e8ac56472c9b83ad88a3172cc2c78067
5
5
  SHA512:
6
- metadata.gz: 0db1b2103c8b5334786442adea3cb254ff81389354a6dba39a0a38c38d41ba0f337dab6be90758b75c8ae51e6ada6e391befe8f671502ecd08634133067e1d23
7
- data.tar.gz: edb943d87180a8656fdd5a33a5d20e5cb3bf05201824fbfc581c8c13b31102ec9449d3e346bb3fe05612d63333abe89331eadb0fb116c626821d5f64b6d1eadb
6
+ metadata.gz: 05f0bad56ffc200373166a6d517bd33c30823d66acbb2e5a4db488c7320d226b093d8dbc24cdb470903cc8cdfb44f5bfb9314ba32c7ea904247b4d7c66d7bb0a
7
+ data.tar.gz: 8acd640dd8d2f6676469f06cac79703a661acdfed6c8e85e9744855b817453f0f6e7b5f5814e9efe088daaf142bb382b479c9d89cedf39663084734d5974415f
data/CHANGELOG.md CHANGED
@@ -6,6 +6,283 @@ Format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
6
6
 
7
7
  ## [Unreleased]
8
8
 
9
+ ## [1.11.9] - 2026-11-22
10
+
11
+ ### Fixed
12
+
13
+ - **security**: resolved CVE-2026-130001 (critical RCE in `mustache`,
14
+ pinned at `0.99.8` by `pleaserun`'s exact-version dependency via `fpm`)
15
+ by bumping `pleaserun` `0.0.33` -> `0.0.35` (`bundle update pleaserun
16
+ --conservative`), which relaxes its `mustache` requirement to `~> 1.1,
17
+ >= 1.1.3`; resolved to `1.1.3`. `fpm`'s own `pleaserun (~> 0.0.29)`
18
+ constraint is unaffected. `security:bundler-audit` now passes clean.
19
+ - **security**: bumped the pinned Ruby runtime from `3.4.11` to `3.4.13`
20
+ across `.ruby-version`, the CI `RUBY_VERSION`
21
+ (`.gitlab-ci-files/global/variables.yml`), and the four `ruby-*` CI
22
+ component `ruby_version` inputs (`.gitlab-ci.yml`). Resolves
23
+ CVE-2026-132825 and six further heap-overflow/double-free advisories
24
+ in Ruby's case-conversion and regexp engine. `security:ruby-audit`
25
+ now passes clean.
26
+
27
+ ## [1.11.8] - 2026-11-17
28
+
29
+ ### Fixed
30
+
31
+ - **security**: resolved 24 `bundler-audit` advisories across 6 pinned gems
32
+ (`activesupport`, `addressable`, `mcp`, `nokogiri`, `puma`, `rack`) —
33
+ `security:bundler-audit` now passes clean (WP#6265 cross-ref).
34
+ Five gems (`activesupport`, `addressable`, `nokogiri`, `puma`, `rack`)
35
+ updated via `bundle update --conservative`; their Gemfile constraints
36
+ were already open enough to reach the patched versions. The sixth,
37
+ `mcp` (0.25.0 -> 1.10.0), was blocked by a transitive cap: `rubocop
38
+ 1.85.0` depended on `mcp (~> 0.6)`. Updating `rubocop` to `1.92.3`
39
+ (still within the Gemfile's existing `~> 1.82` constraint) drops the
40
+ `mcp` dependency entirely, unblocking the direct `mcp` gem (used by
41
+ rosett-ai's own MCP server) to resolve past 1.0. Verified against the
42
+ mcp 1.x API (`MCP::Server.new`, `#resources=`, `#resources_read_handler`,
43
+ `#define_tool`, `#define_prompt`, `MCP::Tool::Response.new`) — all
44
+ call sites rosett-ai depends on are unchanged. Full `rspec` and
45
+ `rubocop` suites pass (rubocop's own version bump surfaced 15
46
+ pre-existing `Style/DirectiveScope`/`Lint/RedundantCopDisableDirective`
47
+ offenses from new cops, all autocorrected).
48
+
49
+ ## [1.11.7] - 2026-11-16
50
+
51
+ ### Fixed
52
+
53
+ - **security**: bump the pinned Ruby runtime from `3.4.8` to `3.4.11` across
54
+ `.ruby-version`, the CI `RUBY_VERSION` (`.gitlab-ci-files/global/variables.yml`),
55
+ and the four `ruby-*` CI component `ruby_version` inputs (`.gitlab-ci.yml`).
56
+ Resolves CVE-2026-41316 (Ruby ERB deserialization guard bypass) at the
57
+ runtime level. Removed the `--ignore CVE-2026-41316` flag from
58
+ `security:bundler-audit` and `security:ruby-audit` in `.gitlab-ci.yml`,
59
+ and from the `.overcommit.yml` `RubyAudit` hook — both audits now pass
60
+ with no CVE-2026-41316 ignores. `3.4.11`
61
+ satisfies the advisory's `~> 3.4.10` constraint; `3.4.10` itself is not
62
+ present in this fleet's curated `ruby-build` definitions. The separate
63
+ CVE-2026-54904 (concurrent-ruby) note in `.gitlab-ci.yml` is untouched —
64
+ it was never an active `--ignore` suppression and is out of this fix's
65
+ scope.
66
+
67
+ ## [1.11.6] - 2026-10-17
68
+
69
+ ### Fixed
70
+
71
+ - **`rai_compile_status` reported permanent, unclearable staleness** — the
72
+ verdict compared source and compiled file *mtimes* while the compiler
73
+ itself only rewrites a compiled file when its *rendered content* actually
74
+ changes. A source edit that left the rendered output unchanged (a
75
+ metadata-only field, key reordering) made the source permanently newer than
76
+ the compiled file, so no amount of recompiling could clear the stale flag.
77
+ The verdict now renders the source through the same engine backend the
78
+ compiler uses and compares checksums, reserving mtime for a cheap
79
+ pre-filter that skips rendering only when content cannot have drifted.
80
+ - **`raictl compile generate --vendor` failed with `Permission denied` on a
81
+ packaged install.** The lockfile path resolved inside
82
+ `RosettAi.conf_root`, which is the (often root-owned) install tree when no
83
+ project is detected. `compile.lock.yml` now resolves via
84
+ `PathResolver#compile_lockfile_path`, overridable with
85
+ `ROSETT_AI_COMPILE_LOCK`, defaulting to
86
+ `~/.config/rosett-ai/conf/compile.lock.yml` — never the install tree.
87
+ - **`rai_compile_status(scope:)` silently returned a zero-file all-clear for
88
+ an unmatched scope** instead of erroring, masking typos and bad input as a
89
+ clean bill of health. An explicit scope that doesn't match a category
90
+ directory now raises instead.
91
+
92
+ ## [1.11.5] - 2026-10-10
93
+
94
+ ### Fixed
95
+
96
+ - **`rai_hook_install` regression coverage gap (WP#4256)** — the emitter fix and
97
+ install-time parse gate for `HookGenerator#format_regex` shipped in v1.8.1,
98
+ but no spec asserted that `rai_hook_install` actually refuses to install a
99
+ generated hook that fails the Ruby syntax check. Added
100
+ `hook_install_tool_spec.rb` coverage: a deliberately unparseable generated
101
+ script now demonstrably returns an error response, is never written to disk,
102
+ and is never registered in `settings.json`, closing WP#4256's acceptance
103
+ criterion that the install path must show the refusal rather than merely
104
+ claim it would have failed.
105
+
106
+ ## [1.11.4] - 2026-10-10
107
+
108
+ ### Fixed
109
+
110
+ - **`Plugins::Registry#discover_embedded_gems` self-discovered plugins from
111
+ an unrelated `/opt/rosett-ai` install on the same host.** The embedded-gem
112
+ fallback (added to bridge a Ruby ABI mismatch between the hermetic Ruby
113
+ and engine gems *within the same* `.deb` installation) scanned
114
+ `/opt/rosett-ai/embedded` unconditionally, so a source checkout or CI run
115
+ sharing a workstation with an installed package double-loaded its engine
116
+ classes. Gated discovery on `Gem.dir` actually being rooted under the
117
+ embedded install, so only that installation's own Ruby ever self-discovers
118
+ its plugin tree.
119
+
120
+ ## [1.11.3] - 2026-10-10
121
+
122
+ ### Fixed
123
+
124
+ - **`audit:artifact` gitleaks false positives on vendored Ruby source.** The
125
+ packaged-artifact audit scans the extracted `.deb` relative to its install
126
+ layout; the hermetic Ruby interpreter and its vendored `bundler`/gem source
127
+ under `opt/rosett-ai/embedded/` (not this project's secret surface) were
128
+ triggering generic-pattern matches. Added a path-scoped gitleaks allowlist
129
+ entry for that tree; no rule was loosened or disabled, and the scan still
130
+ fails on a planted first-party secret.
131
+
132
+ ## [1.11.0] - 2026-10-03
133
+
134
+ ### Added
135
+
136
+ - **`raictl rules status`** — read-only drift detector between the LIVE
137
+ behaviour-rule source tree (`~/.config/rosett-ai/conf/behaviour/`) and its
138
+ git-tracked MIRROR copy. Compares every file by content hash and reports
139
+ drift in both directions (`live_only`, `mirror_only`, `live_newer`,
140
+ `mirror_newer`, `identical`); exits non-zero on any drift. MIRROR path is
141
+ configured via `--mirror-dir` or `rules.mirror_dir` in
142
+ `~/.config/rosett-ai/config.yml`. `rules push`/`rules pull` are
143
+ intentionally not implemented — they are blocked on unresolved
144
+ conflict-semantics design questions.
145
+
146
+ ## [1.11.2] - 2026-10-09
147
+
148
+ ### Fixed
149
+
150
+ - **`quality:namespace` CI job failed on this branch's own new spec
151
+ description.** The `.namespace-allowlist` additions for `LEGACY_SERVER_NAMES`
152
+ covered the implementation and the `expect(...).to include('nncc')` line,
153
+ but missed the spec description text itself
154
+ (`it 'includes the old nncc project name'`). Added the missing allowlist
155
+ entry.
156
+ - **`RosettAi::Rules::StatusChecker` misreported drift when invoked from
157
+ within any git hook.** Its git subprocess calls inherited `GIT_DIR`/
158
+ `GIT_WORK_TREE` from the invoking hook process, redirecting history
159
+ lookups to the hook's own repo instead of the MIRROR directory being
160
+ inspected (and, in the test suite, corrupting the invoking repo's own
161
+ index with stray staged fixture files). All git subprocess calls now
162
+ explicitly clear the git repo-location env vars.
163
+ - **McpRegistrar wrote MCP server config to the wrong file.** Claude Code
164
+ discovers MCP servers from `~/.claude.json`, not `~/.claude/settings.json`.
165
+ `raictl init --global` now registers rosett-ai in `~/.claude.json` and
166
+ drops any legacy `nncc`-named entry when re-registering.
167
+ - **`rai_config_compile` MCP tool leaked a raw registry exception** ("Unknown
168
+ engine plugin: claude. Available: ") whenever no engine plugin was
169
+ installed. It now returns the same actionable `apt install
170
+ rosett-ai-engine-<name>` hint the CLI already gives.
171
+
172
+ ### Changed
173
+
174
+ - `raictl compile generate --help` now documents that `--scope project`
175
+ requires a `.rosett-ai/` directory in the CWD or an ancestor, and the
176
+ error raised when it's missing hints at `--scope global` instead when the
177
+ CWD looks like the rosett-ai source tree itself.
178
+
179
+ ## [1.10.0] - 2026-09-27
180
+
181
+ ### Added
182
+
183
+ - **Lean context emitter — `raictl compile --lean`**. Emits a reduced
184
+ rule bundle carrying rule id, imperative body and priority only: the separated
185
+ `evidence` provenance is stripped and rules marked `enforced: true` are dropped,
186
+ because a live hook already enforces them and they need not consume model
187
+ context. Priority ordering is preserved. The rules written to the normal output
188
+ directory are unchanged and remain the full, evidence-carrying reference copy.
189
+ - **Role-scoped bundles**. The same run emits one bundle per session
190
+ role from each rule's `applies_to` — `role-worker-impl.md`,
191
+ `role-worker-research.md`, `role-orchestrator.md`, `role-interactive.md` — plus
192
+ `role-all.md`, the shared baseline every role inherits, and `lean-full.md`, the
193
+ unscoped set. Membership is `applies_to` contains the role or `all`; absent
194
+ `applies_to` is treated as `[all]`. Role bundles are self-contained, so a
195
+ session loads exactly one. Output goes to `~/.claude/rules-lean/`, overridable
196
+ with `--lean-dir`.
197
+ - Both transforms are deterministic compile-time filters driven purely by rule
198
+ schema metadata (`enforced`, `evidence`, `applies_to`) — no per-session
199
+ inference selects rules.
200
+ - `raictl compile --lean` reports measured character counts, approximate token
201
+ counts and the delta against the full output for every bundle.
202
+ - The `claude` and `agents_md` backends now render a rule's separated `evidence`
203
+ field, keeping their output the evidence-carrying reference once rule
204
+ provenance moves out of `description`.
205
+
206
+ ### Changed
207
+
208
+ - `PathResolver` gained `lean_rules_dir` (`~/.claude/rules-lean`), deliberately
209
+ separate from `rules_dir` so an engine never loads the full and lean forms of
210
+ the same rule.
211
+
212
+ ## [1.9.1] - 2026-09-12
213
+
214
+ ### Security
215
+
216
+ - **rubyzip upgraded to 3.6.0** (from 2.4.1) — fixes CVE-2026-85396 (GHSA-47m2-wp7j-p9vc),
217
+ a path traversal vulnerability in `Zip::Entry#extract` affecting rubyzip < 3.4.0.
218
+ `ZipCompressor#compress` and `Backup#extract_zip` required no code changes — rubyzip's
219
+ 2.4 branch was released as a bridge version supporting the 3.x calling style while
220
+ retaining 2.x positional-argument compatibility.
221
+ - `license_finder` (dev-only, licence-compliance checking) moved to its own
222
+ `Gemfile.license_finder` — its latest release (7.2.1) hard-pins `rubyzip (>= 1, < 3)`,
223
+ which blocked the runtime rubyzip upgrade above. Run via
224
+ `BUNDLE_GEMFILE=Gemfile.license_finder bundle exec license_finder` (mirrors the existing
225
+ `Gemfile.integration` pattern). No change to license_finder's own behaviour or the
226
+ compliance decisions in `doc/dependency_decisions.yml`.
227
+
228
+ ### Added
229
+
230
+ - Round-trip test coverage for the `zip` compression format (compress→extract content
231
+ verification in `compressor_spec.rb`; full `raictl backup create`/`restore` round-trip
232
+ in `backup_spec.rb`) — previously only asserted on file existence/size.
233
+
234
+ ## [1.9.0] - 2026-08-16
235
+
236
+ ### Added
237
+
238
+ - **`rai_optimize` mechanical self-optimizer** — sibling to `rai_adopt`, mechanical only
239
+ (no LLM). Runs four detectors over the behaviour corpus:
240
+ - **overlap** — pairwise Jaccard on rule-description tokens (threshold 0.4).
241
+ - **staleness** — retired-substrate vocabulary match (absorbs the scruffy staleness facet).
242
+ - **conflict** — priority-inflation heuristic: rules at priority ≥ 80 without a cited recurrence
243
+ marker or `Why:` line.
244
+ - **token-cost** — verbose rule bodies (source-byte cost above 3000 bytes).
245
+
246
+ Surfaces:
247
+ - CLI `raictl optimize [--propose] [--out DIR] [--thresholds PATH]`.
248
+ - MCP tool `mcp__rosett-ai__rai_optimize` mirroring the CLI shape.
249
+
250
+ Output modes:
251
+ - Default: report-only, Markdown to `<memory-dir>/rai-optimize-report-<date>.md`.
252
+ - `--propose`: YAML patch files (one per behaviour) to `$TMPDIR/rai-optimize-proposals/`
253
+ (or `--out=<dir>`).
254
+
255
+ Auto-apply is intentionally NOT supported — proposals must be reviewed and applied by hand
256
+ via `raictl behaviour manage` (invisible-user-rules ship-breaker lesson: the human gate is
257
+ mandatory).
258
+
259
+ Detector thresholds are configurable in `conf/rai-optimize/thresholds.yml`; the substrate
260
+ vocabulary lives in `conf/rai-optimize/substrate-vocabulary.yml`.
261
+
262
+ ## [1.8.1] - 2026-08-14
263
+
264
+ ### Fixed
265
+
266
+ - **`HookGenerator#format_regex` regex-literal syntax error** — the generator
267
+ previously emitted patterns as `/regex/` literals, which produced a Ruby
268
+ `SyntaxError` when the pattern contained a forward slash inside a character
269
+ class (e.g. `[^\/\s]`) or as a path separator (e.g. `\/tmp\/`). Ruby parses
270
+ the first unescaped `/` as the closing regex delimiter, silently breaking the
271
+ hook. Both the `pattern` and `path_scope` fields now emit `Regexp.new("...")`
272
+ calls, which are immune to delimiter conflicts. The bug affected every
273
+ generated hook since the feature was introduced; no hook had ever parsed
274
+ cleanly on the real rule set.
275
+
276
+ - **`rai_hook_install` parse gate** — `HookInstallTool#write_hook` now runs
277
+ `ruby -c` on the generated script before writing it to disk. A `SyntaxError`
278
+ in the generated hook now raises immediately with a descriptive message rather
279
+ than silently installing a broken file.
280
+
281
+ - **Regression specs** — `hook_generator_spec.rb` now includes contexts for
282
+ patterns containing `/` inside character classes and path separators, with
283
+ assertions that `RubyVM::InstructionSequence.compile` succeeds and that the
284
+ emitted form is `Regexp.new(...)` rather than a `/regex/` literal.
285
+
9
286
  ## [1.8.0] - 2026-08-13
10
287
 
11
288
  ### Added
data/README.md CHANGED
@@ -51,7 +51,7 @@ graph LR
51
51
  |-------|-------|
52
52
  | Version | <!-- rai:version -->1.3.4<!-- /rai:version --> |
53
53
  | License | GPL-3.0-only |
54
- | Ruby | 3.4.8 (rbenv) |
54
+ | Ruby | 3.4.13 (rbenv) |
55
55
  | Tests | <!-- rai:tests -->4477 RSpec specs<!-- /rai:tests --> |
56
56
  | Author | Hugo Antonio Sepulveda Manriquez |
57
57
 
@@ -329,7 +329,7 @@ rosett-ai/
329
329
  ```bash
330
330
  git clone https://gitlab.com/neatnerds/foss/rosett-ai.git
331
331
  cd rosett-ai
332
- rbenv install 3.4.8
332
+ rbenv install 3.4.13
333
333
  bundle install
334
334
  overcommit --install
335
335
  bin/raictl version
@@ -55,6 +55,16 @@
55
55
  "description": "Allow InstallPlugin/RemovePlugin D-Bus methods. Disabled by default for security."
56
56
  }
57
57
  }
58
+ },
59
+ "rules": {
60
+ "type": "object",
61
+ "additionalProperties": false,
62
+ "properties": {
63
+ "mirror_dir": {
64
+ "type": "string",
65
+ "description": "Path to the git-tracked mirror of the LIVE behaviour directory, used by 'raictl rules status'"
66
+ }
67
+ }
58
68
  }
59
69
  }
60
70
  }
@@ -60,9 +60,16 @@ module RosettAi
60
60
  return [] if rules.empty?
61
61
 
62
62
  lines = ['', '## Rules', '']
63
- rules.each do |rule|
64
- lines << "- #{rule['description'].to_s.strip}"
65
- end
63
+ rules.each { |rule| lines.concat(rule_lines(rule)) }
64
+ lines
65
+ end
66
+
67
+ # Renders one rule plus its separated `evidence` provenance, which the
68
+ # lean bundles strip.
69
+ def rule_lines(rule)
70
+ evidence = rule['evidence'].to_s.strip
71
+ lines = ["- #{rule['description'].to_s.strip}"]
72
+ lines << " - Evidence: #{evidence}" unless evidence.empty?
66
73
  lines
67
74
  end
68
75
 
@@ -71,7 +71,17 @@ module RosettAi
71
71
  else
72
72
  "### #{rule['id']}"
73
73
  end
74
- ['', heading, '', rule['description'].to_s.strip]
74
+ ['', heading, '', rule['description'].to_s.strip] + evidence_lines(rule)
75
+ end
76
+
77
+ # Renders the separated `evidence` provenance, which the lean bundles
78
+ # strip. Keeps this output the evidence-carrying reference artifact
79
+ # once rule provenance is migrated out of `description`.
80
+ def evidence_lines(rule)
81
+ evidence = rule['evidence'].to_s.strip
82
+ return [] if evidence.empty?
83
+
84
+ ['', "**Evidence:** #{evidence}"]
75
85
  end
76
86
 
77
87
  def priority_annotations?
@@ -31,6 +31,9 @@ module RosettAi
31
31
  # @return [Array] Allowed compilation scope values.
32
32
  VALID_SCOPES = [:global, :project].freeze
33
33
 
34
+ # Category holding operational rules — the source for lean bundles.
35
+ BEHAVIOUR_CATEGORY = 'behaviour'
36
+
34
37
  attr_reader :source_dir, :target_dir, :schema_dir, :backend, :scope,
35
38
  :additional_source_dirs
36
39
 
@@ -121,6 +124,20 @@ module RosettAi
121
124
  @conflict_warnings || []
122
125
  end
123
126
 
127
+ # Loads and validates every behaviour source file, returning the parsed
128
+ # data rather than rendered output.
129
+ #
130
+ # The lean and role-scoped bundle emitters need rule metadata
131
+ # (`enforced`, `applies_to`, `evidence`) that rendering discards, so they
132
+ # consume this instead of {#compile}.
133
+ #
134
+ # @return [Array<Hash>] parsed behaviour data hashes
135
+ # @raise [RosettAi::CompileError] when a source file fails validation
136
+ def behaviour_sources
137
+ files = collect_category_files(BEHAVIOUR_CATEGORY) + premium_files_for(BEHAVIOUR_CATEGORY)
138
+ files.filter_map { |file| load_validated(file) }
139
+ end
140
+
124
141
  # Validates data against the JSON Schema for the given category.
125
142
  #
126
143
  # @param category [String] configuration category name
@@ -231,6 +248,14 @@ module RosettAi
231
248
  [key, output]
232
249
  end
233
250
 
251
+ def load_validated(file)
252
+ data = load_yaml(file)
253
+ return nil unless data
254
+
255
+ validate!(BEHAVIOUR_CATEGORY, data, file)
256
+ data
257
+ end
258
+
234
259
  def validate_scope!(scope)
235
260
  return if VALID_SCOPES.include?(scope)
236
261
 
@@ -0,0 +1,150 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ # Copyright (C) 2026 Hugo Antonio Sepulveda Manriquez / NeatNerds
5
+
6
+ module RosettAi
7
+ module Compiler
8
+ # A single lean context bundle — the deterministic projection of behaviour
9
+ # rules onto (id, imperative body, priority) for one session role.
10
+ #
11
+ # The projection is mechanical: no inference decides which rules matter.
12
+ # A rule is included when all of the following hold:
13
+ #
14
+ # * it is enabled (`enabled` absent or true),
15
+ # * it is not hook-enforced (`enforced` absent or false — a live hook
16
+ # already enforces it, so it need not consume model context),
17
+ # * it is in scope for the bundle's role (`applies_to` contains the role
18
+ # or {SHARED_ROLE}; absent `applies_to` is treated as `[all]`).
19
+ #
20
+ # The `evidence` field is never rendered: provenance belongs to the full
21
+ # reference bundle, not to the context a session loads.
22
+ #
23
+ # A role bundle is SELF-CONTAINED — it already includes the shared `all`
24
+ # rules, so a loader loads exactly one bundle and never two.
25
+ class LeanBundle
26
+ # @return [String] role token every session inherits.
27
+ SHARED_ROLE = 'all'
28
+
29
+ # @return [String] prefix for generated lean-bundle marker comments.
30
+ MARKER_PREFIX = '<!-- rosett-ai-lean-managed'
31
+
32
+ # @return [String, nil] role this bundle is scoped to, nil for the
33
+ # unscoped complete lean bundle.
34
+ attr_reader :role
35
+
36
+ # @return [Array<Hash>] selected sections, one per behaviour file, each
37
+ # `{ name:, rules: }` with rules ordered by descending priority.
38
+ attr_reader :sections
39
+
40
+ # Whether a rule survives the lean projection, independent of role.
41
+ #
42
+ # @param rule [Hash] parsed rule data
43
+ # @return [Boolean] true when enabled and not hook-enforced
44
+ def self.eligible?(rule)
45
+ rule.fetch('enabled', true) && rule['enforced'] != true
46
+ end
47
+
48
+ # Session roles a rule is scoped to, defaulting to [SHARED_ROLE].
49
+ #
50
+ # @param rule [Hash] parsed rule data
51
+ # @return [Array<String>] role tokens
52
+ def self.roles_for(rule)
53
+ roles = rule['applies_to'].to_a
54
+ roles.empty? ? [SHARED_ROLE] : roles
55
+ end
56
+
57
+ # Whether a rule belongs in the bundle for the given role.
58
+ #
59
+ # @param rule [Hash] parsed rule data
60
+ # @param role [String, nil] role token, or nil for the complete bundle
61
+ # @return [Boolean]
62
+ def self.member?(rule, role)
63
+ return true if role.nil?
64
+
65
+ assigned = roles_for(rule)
66
+ assigned.include?(role) || assigned.include?(SHARED_ROLE)
67
+ end
68
+
69
+ # @param role [String, nil] role token, or nil for the complete bundle
70
+ # @param behaviours [Array<Hash>] parsed behaviour data hashes
71
+ def initialize(role:, behaviours:)
72
+ @role = role
73
+ @sections = build_sections(behaviours)
74
+ end
75
+
76
+ # @return [String] display label for this bundle's scope
77
+ def label = role || 'full'
78
+
79
+ # @return [Integer] number of rules carried by this bundle
80
+ def rule_count = sections.sum { |section| section[:rules].size }
81
+
82
+ # @return [Array<String>] rule ids qualified by behaviour name
83
+ def rule_keys
84
+ sections.flat_map { |section| section_keys(section) }
85
+ end
86
+
87
+ # Renders the bundle as Markdown. Memoized — the rendered form is
88
+ # deterministic for a given input set.
89
+ #
90
+ # @return [String] rendered bundle content
91
+ def render
92
+ @render ||= (header + sections.flat_map { |section| render_section(section) } + ['']).join("\n")
93
+ end
94
+
95
+ # @return [Integer] rendered size in characters
96
+ def char_count = render.length
97
+
98
+ private
99
+
100
+ def build_sections(behaviours)
101
+ behaviours.filter_map { |data| section_for(data) }.sort_by { |section| section[:name] }
102
+ end
103
+
104
+ def section_for(data)
105
+ rules = select_rules(data['rules'] || [])
106
+ return nil if rules.empty?
107
+
108
+ { name: data['name'].to_s, rules: rules }
109
+ end
110
+
111
+ def select_rules(rules)
112
+ eligible = rules.select { |rule| self.class.eligible?(rule) && self.class.member?(rule, role) }
113
+ eligible.sort_by { |rule| [-priority_of(rule), rule['id'].to_s] }
114
+ end
115
+
116
+ def section_keys(section)
117
+ name = section[:name]
118
+ section[:rules].map { |rule| "#{name}/#{rule['id']}" }
119
+ end
120
+
121
+ def priority_of(rule) = rule['priority'] || 50
122
+
123
+ def header
124
+ [
125
+ "#{MARKER_PREFIX} role=#{label} -->",
126
+ "<!-- Generated by rosett-ai #{RosettAi::VERSION} — lean bundle: evidence stripped, " \
127
+ 'hook-enforced rules omitted. -->',
128
+ "<!-- #{membership_note} -->",
129
+ '',
130
+ "# Lean rule bundle — #{label}"
131
+ ]
132
+ end
133
+
134
+ def membership_note
135
+ return 'Membership: every enabled rule with enforced != true, all roles.' if role.nil?
136
+
137
+ "Membership: applies_to contains \"#{role}\" or \"#{SHARED_ROLE}\". " \
138
+ 'Self-contained — load this bundle only, never together with another role bundle.'
139
+ end
140
+
141
+ def render_section(section)
142
+ ['', "## #{section[:name]}"] + section[:rules].flat_map { |rule| render_rule(rule) }
143
+ end
144
+
145
+ def render_rule(rule)
146
+ ['', "### #{rule['id']} (priority: #{priority_of(rule)})", '', rule['description'].to_s.strip]
147
+ end
148
+ end
149
+ end
150
+ end
@@ -0,0 +1,76 @@
1
+ # frozen_string_literal: true
2
+
3
+ # SPDX-License-Identifier: GPL-3.0-only
4
+ # Copyright (C) 2026 Hugo Antonio Sepulveda Manriquez / NeatNerds
5
+
6
+ module RosettAi
7
+ module Compiler
8
+ # Emits lean and role-scoped context bundles from behaviour sources.
9
+ #
10
+ # The emitter is a deterministic compile-time transform: for a given set of
11
+ # behaviour files it always produces the same fixed set of bundles, with no
12
+ # per-session inference about which rules apply. Session roles are resolved
13
+ # at compile time from each rule's `applies_to` metadata.
14
+ #
15
+ # Emitted set (fixed, so stale files are always detectable):
16
+ #
17
+ # * `lean-full.md` — every eligible rule, unscoped (C2)
18
+ # * `role-all.md` — the shared baseline every role inherits (C3)
19
+ # * `role-<role>.md` — one self-contained bundle per role in {ROLES}
20
+ #
21
+ # Each role bundle is a strict subset of `lean-full.md`.
22
+ class LeanEmitter
23
+ # @return [Array<String>] session roles emitted as their own bundle.
24
+ ROLES = ['worker-impl', 'worker-research', 'orchestrator', 'interactive'].freeze
25
+
26
+ # @return [String] filename of the unscoped complete lean bundle.
27
+ FULL_BUNDLE_FILENAME = 'lean-full.md'
28
+
29
+ # @return [Float] characters per token, a conservative English-prose
30
+ # approximation. Character counts are the authoritative measure;
31
+ # token figures derived from this constant are estimates only.
32
+ CHARS_PER_TOKEN = 4.0
33
+
34
+ # Approximate token count for a character count.
35
+ #
36
+ # @param chars [Integer] character count
37
+ # @return [Integer] approximate token count
38
+ def self.approximate_tokens(chars) = (chars / CHARS_PER_TOKEN).ceil
39
+
40
+ # @return [Array<Hash>] parsed behaviour data hashes
41
+ attr_reader :behaviours
42
+
43
+ # @param behaviours [Array<Hash>] parsed behaviour data hashes
44
+ def initialize(behaviours:)
45
+ @behaviours = behaviours
46
+ end
47
+
48
+ # The complete emitted bundle set, keyed by output filename.
49
+ #
50
+ # @return [Hash{String => LeanBundle}] filename => bundle
51
+ def bundles
52
+ @bundles ||= { FULL_BUNDLE_FILENAME => bundle_for(nil) }.merge(role_bundles)
53
+ end
54
+
55
+ # @return [Array<String>] role tokens emitted, shared baseline first
56
+ def self.emitted_roles = [LeanBundle::SHARED_ROLE] + ROLES
57
+
58
+ # @return [LeanBundle] the unscoped complete lean bundle
59
+ def full_bundle = bundles.fetch(FULL_BUNDLE_FILENAME)
60
+
61
+ # Output filename for a role bundle.
62
+ #
63
+ # @param role [String] role token
64
+ # @return [String] bundle filename
65
+ def filename_for(role) = "role-#{role}.md"
66
+
67
+ private
68
+
69
+ def role_bundles
70
+ self.class.emitted_roles.to_h { |role| [filename_for(role), bundle_for(role)] }
71
+ end
72
+
73
+ def bundle_for(role) = LeanBundle.new(role: role, behaviours: behaviours)
74
+ end
75
+ end
76
+ end
@@ -196,7 +196,7 @@ module RosettAi
196
196
  end
197
197
 
198
198
  def setup_file_logging
199
- @file_handle = File.open(@log_file, 'a') # rubocop:disable Style/FileOpen -- persistent handle, closed in #cleanup
199
+ @file_handle = File.open(@log_file, 'a')
200
200
  @file_handle.sync = true
201
201
  rescue StandardError => e
202
202
  warn "[GuiLogger] Failed to open log file: #{e.message}"
@@ -61,7 +61,8 @@ module RosettAi
61
61
  RosettAi::ProjectError => GENERAL,
62
62
  RosettAi::RetrofitError => CONFIG,
63
63
  RosettAi::GitHooksError => GENERAL,
64
- RosettAi::McpError => GENERAL
64
+ RosettAi::McpError => GENERAL,
65
+ RosettAi::RulesError => GENERAL
65
66
  }.freeze
66
67
 
67
68
  # Resolves the exit code for a given error.