rosett-ai 1.8.1 → 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 (43) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +253 -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/governance.rb +1 -0
  14. data/lib/rosett_ai/mcp/tools/compile_status_tool.rb +58 -13
  15. data/lib/rosett_ai/mcp/tools/config_compile_tool.rb +40 -7
  16. data/lib/rosett_ai/mcp/tools/optimize_tool.rb +73 -0
  17. data/lib/rosett_ai/optimize/corpus.rb +79 -0
  18. data/lib/rosett_ai/optimize/detector.rb +27 -0
  19. data/lib/rosett_ai/optimize/detectors/conflict.rb +50 -0
  20. data/lib/rosett_ai/optimize/detectors/overlap.rb +74 -0
  21. data/lib/rosett_ai/optimize/detectors/staleness.rb +61 -0
  22. data/lib/rosett_ai/optimize/detectors/token_cost.rb +44 -0
  23. data/lib/rosett_ai/optimize/finding.rb +36 -0
  24. data/lib/rosett_ai/optimize/proposal_writer.rb +54 -0
  25. data/lib/rosett_ai/optimize/report_writer.rb +72 -0
  26. data/lib/rosett_ai/optimize/runner.rb +38 -0
  27. data/lib/rosett_ai/optimize/thresholds.rb +52 -0
  28. data/lib/rosett_ai/optimize.rb +33 -0
  29. data/lib/rosett_ai/path_resolver.rb +25 -0
  30. data/lib/rosett_ai/plugins/registry.rb +45 -15
  31. data/lib/rosett_ai/provenance/entry.rb +1 -2
  32. data/lib/rosett_ai/rai_config.rb +3 -0
  33. data/lib/rosett_ai/rules/status_checker.rb +144 -0
  34. data/lib/rosett_ai/telemetry/json_lines_writer.rb +1 -1
  35. data/lib/rosett_ai/thor/cli.rb +7 -61
  36. data/lib/rosett_ai/thor/command_tree.rb +79 -0
  37. data/lib/rosett_ai/thor/tasks/compile.rb +137 -2
  38. data/lib/rosett_ai/thor/tasks/optimize.rb +103 -0
  39. data/lib/rosett_ai/thor/tasks/rules.rb +125 -0
  40. data/lib/rosett_ai/version.rb +1 -1
  41. data/lib/rosett_ai.rb +2 -0
  42. data/locales/en.yml +15 -0
  43. metadata +22 -3
@@ -126,6 +126,9 @@ module RosettAi
126
126
  desc 'adopt', 'Analyze compiled rule files for issues'
127
127
  subcommand 'adopt', RosettAi::Thor::Tasks::Adopt
128
128
 
129
+ desc 'optimize', 'Mechanical self-optimizer for the rai behaviour corpus'
130
+ subcommand 'optimize', RosettAi::Thor::Tasks::Optimize
131
+
129
132
  desc 'init', 'Initialize rosett-ai directory structure'
130
133
  subcommand 'init', RosettAi::Thor::Tasks::Init
131
134
 
@@ -186,6 +189,9 @@ module RosettAi
186
189
  desc 'hooks SUBCOMMAND', 'Install and manage git hooks'
187
190
  subcommand 'hooks', RosettAi::Thor::Tasks::Hooks
188
191
 
192
+ desc 'rules SUBCOMMAND', 'Report drift between LIVE behaviour rules and their git MIRROR'
193
+ subcommand 'rules', RosettAi::Thor::Tasks::Rules
194
+
189
195
  desc 'mcp SUBCOMMAND', 'Manage MCP servers and run security audits'
190
196
  subcommand 'mcp', RosettAi::Thor::Tasks::Mcp
191
197
 
@@ -212,67 +218,7 @@ module RosettAi
212
218
 
213
219
  RosettAi::SmartFeedback::ThorMiddleware.install(self)
214
220
 
215
- private
216
-
217
- # Partition a Thor class's entries into leaf commands and expandable groups.
218
- def tree_partition_entries(klass)
219
- groups = tree_visible_subcommands(klass).sort_by(&:first)
220
- group_set = groups.to_set(&:first)
221
- leaves = tree_leaf_commands(klass, group_set).sort_by(&:first)
222
- [leaves, groups]
223
- end
224
-
225
- # Returns leaf commands: visible commands that aren't also subcommand groups,
226
- # plus subcommand aliases that have no visible children (compile, adopt, etc.).
227
- def tree_leaf_commands(klass, group_set)
228
- all_subcmd_names = klass.subcommand_classes.keys
229
- visible = tree_visible_commands(klass).except(*all_subcmd_names)
230
- subcmd_aliases = all_subcmd_names
231
- .reject { |name| group_set.include?(name) }
232
- .select { |name| klass.commands.key?(name) }
233
- .map { |name| [name, klass.commands[name]] }
234
- visible.to_a + subcmd_aliases
235
- end
236
-
237
- def tree_render_entries(leaves, groups, indent)
238
- total = leaves.size + groups.size
239
- leaves.each_with_index { |(name, cmd), i| tree_print_leaf(name, cmd, indent, i + 1 == total) }
240
- groups.each_with_index do |(name, subclass), i|
241
- tree_print_group(name, subclass, indent, leaves.size + i + 1 == total)
242
- end
243
- end
244
-
245
- def tree_print_leaf(name, cmd, indent, last)
246
- icon = last ? "\u2514\u2500" : "\u251C\u2500"
247
- desc = cmd.description.split("\n").first || ''
248
- say "#{indent}#{icon} ", nil, false
249
- say name, :green, false
250
- say " (#{desc})" unless desc.empty?
251
- end
252
-
253
- def tree_print_group(name, klass, indent, last)
254
- icon = last ? "\u2514\u2500" : "\u251C\u2500"
255
- pipe = last ? ' ' : "\u2502 "
256
- say "#{indent}#{icon} ", nil, false
257
- say name, :cyan
258
- leaves, children = tree_partition_entries(klass)
259
- tree_render_entries(leaves, children, "#{indent}#{pipe}")
260
- end
261
-
262
- def tree_visible_commands(klass)
263
- default = klass.respond_to?(:default_task) ? klass.default_task.to_s : nil
264
- hidden = ['help', 'tree']
265
- filtered = klass.commands.reject { |name, cmd| cmd.hidden? || hidden.include?(name) || name == default }
266
- return filtered if RosettAi.context.rai_internal?
267
-
268
- filtered.except(*INTERNAL_COMMANDS)
269
- end
270
-
271
- def tree_visible_subcommands(klass)
272
- klass.subcommand_classes.select do |_, subclass|
273
- !tree_visible_commands(subclass).empty? || !tree_visible_subcommands(subclass).empty?
274
- end
275
- end
221
+ include RosettAi::Thor::CommandTree
276
222
  end
277
223
  end
278
224
  end
@@ -0,0 +1,79 @@
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 Thor
8
+ # Renders the `raictl tree` command tree: partitions a Thor class's
9
+ # commands into leaf commands and expandable subcommand groups.
10
+ #
11
+ # Included into {RosettAi::Thor::CLI} to keep tree-rendering separate
12
+ # from command registration.
13
+ #
14
+ # @author claude
15
+ module CommandTree
16
+ private
17
+
18
+ # Partition a Thor class's entries into leaf commands and expandable groups.
19
+ def tree_partition_entries(klass)
20
+ groups = tree_visible_subcommands(klass).sort_by(&:first)
21
+ group_set = groups.to_set(&:first)
22
+ leaves = tree_leaf_commands(klass, group_set).sort_by(&:first)
23
+ [leaves, groups]
24
+ end
25
+
26
+ # Returns leaf commands: visible commands that aren't also subcommand groups,
27
+ # plus subcommand aliases that have no visible children (compile, adopt, etc.).
28
+ def tree_leaf_commands(klass, group_set)
29
+ all_subcmd_names = klass.subcommand_classes.keys
30
+ visible = tree_visible_commands(klass).except(*all_subcmd_names)
31
+ subcmd_aliases = all_subcmd_names
32
+ .reject { |name| group_set.include?(name) }
33
+ .select { |name| klass.commands.key?(name) }
34
+ .map { |name| [name, klass.commands[name]] }
35
+ visible.to_a + subcmd_aliases
36
+ end
37
+
38
+ def tree_render_entries(leaves, groups, indent)
39
+ total = leaves.size + groups.size
40
+ leaves.each_with_index { |(name, cmd), i| tree_print_leaf(name, cmd, indent, i + 1 == total) }
41
+ groups.each_with_index do |(name, subclass), i|
42
+ tree_print_group(name, subclass, indent, leaves.size + i + 1 == total)
43
+ end
44
+ end
45
+
46
+ def tree_print_leaf(name, cmd, indent, last)
47
+ icon = last ? "\u2514\u2500" : "\u251C\u2500"
48
+ desc = cmd.description.split("\n").first || ''
49
+ say "#{indent}#{icon} ", nil, false
50
+ say name, :green, false
51
+ say " (#{desc})" unless desc.empty?
52
+ end
53
+
54
+ def tree_print_group(name, klass, indent, last)
55
+ icon = last ? "\u2514\u2500" : "\u251C\u2500"
56
+ pipe = last ? ' ' : "\u2502 "
57
+ say "#{indent}#{icon} ", nil, false
58
+ say name, :cyan
59
+ leaves, children = tree_partition_entries(klass)
60
+ tree_render_entries(leaves, children, "#{indent}#{pipe}")
61
+ end
62
+
63
+ def tree_visible_commands(klass)
64
+ default = klass.respond_to?(:default_task) ? klass.default_task.to_s : nil
65
+ hidden = ['help', 'tree']
66
+ filtered = klass.commands.reject { |name, cmd| cmd.hidden? || hidden.include?(name) || name == default }
67
+ return filtered if RosettAi.context.rai_internal?
68
+
69
+ filtered.except(*RosettAi::Thor::CLI::INTERNAL_COMMANDS)
70
+ end
71
+
72
+ def tree_visible_subcommands(klass)
73
+ klass.subcommand_classes.select do |_, subclass|
74
+ !tree_visible_commands(subclass).empty? || !tree_visible_subcommands(subclass).empty?
75
+ end
76
+ end
77
+ end
78
+ end
79
+ end
@@ -33,6 +33,24 @@ module RosettAi
33
33
  --scope SCOPE: Compile scope (global/project/auto)
34
34
  --strict: Treat warnings as errors
35
35
  --locales: Compile locale files to gettext/Qt formats
36
+ --lean: Also emit lean + role-scoped context bundles
37
+ --lean-dir DIR: Override the lean bundle output directory
38
+
39
+ --scope project requires a .rosett-ai/ directory in the current
40
+ directory or an ancestor (created by `raictl init --project`).
41
+ The rosett-ai source repository itself is not a consuming
42
+ project; from the source repo, use --scope global instead.
43
+
44
+ Lean bundles (--lean) carry rule id, imperative body and priority
45
+ only: `evidence` is stripped and hook-enforced rules (enforced: true)
46
+ are dropped, since a live hook already enforces them. The rules
47
+ compiled to the normal output directory remain the full,
48
+ evidence-carrying reference artifact.
49
+
50
+ One bundle is emitted per session role (worker-impl, worker-research,
51
+ orchestrator, interactive) plus role-all.md, the shared baseline every
52
+ role inherits. Role bundles are SELF-CONTAINED — a session loads
53
+ exactly one of them, never a role bundle plus role-all.md.
36
54
 
37
55
  Exit codes: 1 if validation fails in --strict mode
38
56
 
@@ -45,6 +63,8 @@ module RosettAi
45
63
  raictl compile --engine generic --strict
46
64
  raictl compile --vendor
47
65
  raictl compile --locales
66
+ raictl compile --lean --verbose
67
+ raictl compile --lean --simulate
48
68
 
49
69
  Related commands: raictl behaviour validate, rai adopt
50
70
  LONGDESC
@@ -85,6 +105,14 @@ module RosettAi
85
105
  type: :boolean,
86
106
  default: false,
87
107
  desc: 'Compile locale files to gettext and Qt formats'
108
+ method_option :lean,
109
+ type: :boolean,
110
+ default: false,
111
+ desc: 'Also emit lean and role-scoped context bundles'
112
+ method_option :lean_dir,
113
+ type: :string,
114
+ default: nil,
115
+ desc: 'Output directory for lean bundles (default: ~/.claude/rules-lean)'
88
116
 
89
117
  # Generate the compiled output.
90
118
  # @return [void]
@@ -112,6 +140,7 @@ module RosettAi
112
140
  remove_orphans(compiler, compiled)
113
141
  write_lockfile(compiler, compiled) if options[:vendor] && !options[:simulate]
114
142
  print_summary(results)
143
+ emit_lean_bundles(compiler, compiled) if options[:lean]
115
144
  end
116
145
 
117
146
  private
@@ -167,7 +196,7 @@ module RosettAi
167
196
  when 'global'
168
197
  :global
169
198
  when 'project'
170
- raise RosettAi::CompileError, t('compile.scope_project_no_project') unless RosettAi.context.project?
199
+ raise RosettAi::CompileError, scope_project_error unless RosettAi.context.project?
171
200
 
172
201
  :project
173
202
  else # 'auto'
@@ -176,6 +205,22 @@ module RosettAi
176
205
  end
177
206
  end
178
207
 
208
+ # Picks the --scope project error message. Hints at --scope global
209
+ # when the CWD looks like the rosett-ai source tree itself, since
210
+ # that case can't ever satisfy the .rosett-ai/ project marker check
211
+ # above (the source repo is not a consuming project).
212
+ def scope_project_error
213
+ return t('compile.scope_project_source_repo_hint') if source_repo_cwd?
214
+
215
+ t('compile.scope_project_no_project')
216
+ end
217
+
218
+ # @return [Boolean] true if the CWD is the rosett-ai source tree root
219
+ def source_repo_cwd?
220
+ cwd = Pathname.new(ENV.fetch('RAI_ORIGINAL_PWD', Dir.pwd))
221
+ cwd.join('lib', 'rosett_ai.rb').exist? && cwd.join('rosett-ai.gemspec').exist?
222
+ end
223
+
179
224
  def check_xdg_migration
180
225
  return if RosettAi.context.rai_internal?
181
226
 
@@ -422,12 +467,102 @@ module RosettAi
422
467
  end
423
468
 
424
469
  def write_lockfile(compiler, compiled)
425
- lockfile_path = RosettAi.conf_root.join('conf', 'compile.lock.yml')
470
+ lockfile_path = RosettAi.paths.compile_lockfile_path
471
+ FileUtils.mkdir_p(lockfile_path.dirname)
426
472
  data = compiler.lockfile_data(compiled)
427
473
  File.open(lockfile_path, 'w', 0o644) { |f| f.write(data.to_yaml) }
428
474
  log_verbose(t('compile.wrote_lockfile', path: lockfile_path))
429
475
  end
430
476
 
477
+ # Emits the lean and role-scoped context bundles (C2 / C3).
478
+ # Deterministic: the emitted filename set is fixed, so any other
479
+ # lean-marked file in the output directory is stale and removed.
480
+ def emit_lean_bundles(compiler, compiled)
481
+ emitter = RosettAi::Compiler::LeanEmitter.new(behaviours: compiler.behaviour_sources)
482
+ bundles = emitter.bundles
483
+ target_dir = lean_target_dir
484
+ FileUtils.mkdir_p(target_dir) unless options[:simulate]
485
+ bundles.each { |filename, bundle| write_lean_bundle(target_dir.join(filename), bundle) }
486
+ remove_lean_orphans(target_dir, bundles.keys) unless options[:simulate]
487
+ print_lean_summary(bundles, behaviour_reference_chars(compiled), target_dir)
488
+ end
489
+
490
+ def lean_target_dir
491
+ dir = options[:lean_dir]
492
+ dir ? Pathname.new(File.expand_path(dir)) : RosettAi.paths.lean_rules_dir
493
+ end
494
+
495
+ def write_lean_bundle(path, bundle)
496
+ filename = path.basename.to_s
497
+ if options[:simulate]
498
+ puts Rainbow(t('compile.lean_would_write', filename: filename)).cyan
499
+ return
500
+ end
501
+
502
+ write_file(path, bundle.render)
503
+ log_verbose(t('compile.lean_wrote', filename: filename, chars: bundle.char_count))
504
+ end
505
+
506
+ # Deletes lean-marked files no longer in the emitted set (e.g. after a
507
+ # role is removed from the schema enum).
508
+ def remove_lean_orphans(target_dir, emitted)
509
+ Dir.glob(target_dir.join('*.md')).each do |path|
510
+ basename = File.basename(path)
511
+ next if emitted.include?(basename)
512
+ next unless lean_managed_file?(path)
513
+
514
+ File.delete(path)
515
+ log_verbose(t('compile.removed_orphan', filename: basename))
516
+ end
517
+ end
518
+
519
+ def lean_managed_file?(path)
520
+ File.open(path, &:readline).start_with?(RosettAi::Compiler::LeanBundle::MARKER_PREFIX)
521
+ rescue EOFError
522
+ false
523
+ end
524
+
525
+ # Reference size for the delta report: the behaviour rules as rendered
526
+ # into the full output, so lean bundles are compared like with like.
527
+ def behaviour_reference_chars(compiled)
528
+ behaviour_outputs = compiled.each_value.select do |info|
529
+ info[:category] == RosettAi::Compiler::CompilationPipeline::BEHAVIOUR_CATEGORY
530
+ end
531
+ behaviour_outputs.sum { |info| info[:content].length }
532
+ end
533
+
534
+ def print_lean_summary(bundles, reference_chars, target_dir)
535
+ rows = [lean_reference_row(reference_chars)]
536
+ rows.concat(bundles.map { |filename, bundle| lean_row(filename, bundle, reference_chars) })
537
+ puts
538
+ puts ::Terminal::Table.new(
539
+ title: Rainbow(t('compile.lean_summary_title')).bright,
540
+ headings: [t('compile.lean_bundle'), t('compile.lean_rules'), t('compile.lean_chars'),
541
+ t('compile.lean_tokens'), t('compile.lean_delta')],
542
+ rows: rows,
543
+ style: { border: :unicode_round }
544
+ )
545
+ puts Rainbow(t('compile.lean_dir', path: target_dir)).green unless options[:simulate]
546
+ end
547
+
548
+ def lean_reference_row(reference_chars)
549
+ [t('compile.lean_reference'), '-', reference_chars,
550
+ RosettAi::Compiler::LeanEmitter.approximate_tokens(reference_chars), '-']
551
+ end
552
+
553
+ def lean_row(filename, bundle, reference_chars)
554
+ chars = bundle.char_count
555
+ [filename, bundle.rule_count, chars,
556
+ RosettAi::Compiler::LeanEmitter.approximate_tokens(chars),
557
+ format_lean_delta(chars, reference_chars)]
558
+ end
559
+
560
+ def format_lean_delta(chars, reference_chars)
561
+ return '-' if reference_chars.zero?
562
+
563
+ format('%+.1f%%', ((chars - reference_chars) * 100.0) / reference_chars)
564
+ end
565
+
431
566
  def print_summary(results)
432
567
  label_map = {
433
568
  created: t('compile.created'),
@@ -0,0 +1,103 @@
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
+ require 'thor'
7
+ require 'fileutils'
8
+ require 'time'
9
+
10
+ module RosettAi
11
+ module Thor
12
+ module Tasks
13
+ # `raictl optimize` — mechanical self-optimizer for the rai behaviour
14
+ # corpus. Report-only by default; `--propose` writes YAML patch files
15
+ # to $TMPDIR (or the path given via `--out`). Never auto-applies.
16
+ class Optimize < ::Thor
17
+ default_task :analyze
18
+
19
+ desc 'analyze', 'Analyze the rai behaviour corpus for overlap, staleness, conflict, and verbosity'
20
+ long_desc <<~LONGDESC
21
+ Runs four mechanical detectors against the behaviour corpus:
22
+
23
+ * overlap — pairwise Jaccard on rule-description tokens
24
+ * staleness — retired-substrate vocabulary match
25
+ * conflict — priority-inflation without cited recurrence
26
+ * token-cost — verbose rule bodies (source-byte cost)
27
+
28
+ Report-only by default. Use --propose to also emit YAML patch
29
+ files (one per behaviour) into $TMPDIR/rai-optimize-proposals/
30
+ (or --out=<dir>). Auto-apply is NOT supported: proposals are
31
+ reviewed and applied via `raictl behaviour manage`.
32
+ LONGDESC
33
+ method_option :propose,
34
+ type: :boolean, default: false,
35
+ desc: 'Also write YAML proposal patch files'
36
+ method_option :out,
37
+ type: :string,
38
+ desc: 'Report/proposal output dir (default: report to XDG reports dir, proposals to $TMPDIR)'
39
+ method_option :thresholds,
40
+ type: :string,
41
+ desc: 'Override thresholds YAML path'
42
+ method_option :behaviour_dir,
43
+ type: :string,
44
+ desc: 'Behaviour source dir (default: XDG rai_conf_dir + behaviour)'
45
+
46
+ # @return [void]
47
+ def analyze
48
+ findings = RosettAi::Optimize::Runner.new(
49
+ corpus: RosettAi::Optimize::Corpus.load(behaviour_dir),
50
+ thresholds: load_thresholds
51
+ ).run
52
+
53
+ report_path = write_report(findings)
54
+ proposals = options[:propose] ? write_proposals(findings) : []
55
+ print_summary(findings, report_path, proposals)
56
+ end
57
+
58
+ private
59
+
60
+ def behaviour_dir
61
+ options[:behaviour_dir] || RosettAi.paths.rai_conf_dir.join('behaviour').to_s
62
+ end
63
+
64
+ def load_thresholds
65
+ path = options[:thresholds] || default_thresholds_path
66
+ File.exist?(path) ? RosettAi::Optimize::Thresholds.load(path) : RosettAi::Optimize::Thresholds.defaults
67
+ end
68
+
69
+ def default_thresholds_path
70
+ File.expand_path('../../../../conf/rai-optimize/thresholds.yml', __dir__)
71
+ end
72
+
73
+ def write_report(findings)
74
+ path = options[:out] ? File.join(options[:out], report_filename) : default_report_path
75
+ RosettAi::Optimize::ReportWriter.new(findings: findings, generated_at: Time.now.utc.iso8601).write(path)
76
+ end
77
+
78
+ def default_report_path
79
+ dir = RosettAi.paths.reports_dir.to_s
80
+ FileUtils.mkdir_p(dir)
81
+ File.join(dir, report_filename)
82
+ end
83
+
84
+ def report_filename
85
+ "rai-optimize-report-#{Time.now.utc.strftime('%Y-%m-%d')}.md"
86
+ end
87
+
88
+ def write_proposals(findings)
89
+ dir = options[:out] || File.join(ENV.fetch('TMPDIR', '/tmp'), 'rai-optimize-proposals')
90
+ RosettAi::Optimize::ProposalWriter.new(findings: findings).write(dir)
91
+ end
92
+
93
+ def print_summary(findings, report_path, proposals)
94
+ puts "rai_optimize: #{findings.size} finding(s)"
95
+ puts "report: #{report_path}"
96
+ return if proposals.empty?
97
+
98
+ puts "proposals: #{proposals.size} file(s) in #{File.dirname(proposals.first)}"
99
+ end
100
+ end
101
+ end
102
+ end
103
+ end
@@ -0,0 +1,125 @@
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
+ require 'terminal-table'
7
+
8
+ module RosettAi
9
+ module Thor
10
+ module Tasks
11
+ # Thor CLI for behaviour-rule LIVE/MIRROR drift reporting.
12
+ #
13
+ # Provides the read-only status subcommand. Write paths (push/pull)
14
+ # are intentionally not implemented here — they are blocked on
15
+ # unresolved conflict-semantics design questions.
16
+ #
17
+ # @author claude
18
+ class Rules < ::Thor
19
+ # @return [Hash{Symbol => Symbol}] display color per drift state.
20
+ STATE_COLORS = {
21
+ identical: :green,
22
+ live_only: :yellow,
23
+ live_newer: :yellow,
24
+ mirror_only: :cyan,
25
+ mirror_newer: :cyan
26
+ }.freeze
27
+
28
+ desc 'status', 'Report drift between LIVE behaviour rules and their git-tracked MIRROR'
29
+ long_desc <<~LONGDESC
30
+ Compares every behaviour-rule YAML file in the LIVE source directory
31
+ (~/.config/rosett-ai/conf/behaviour/) against its counterpart in a
32
+ git-tracked MIRROR repository, by content hash.
33
+
34
+ Reports drift in both directions distinctly — a file present or
35
+ changed only in LIVE is not the same problem as one present or
36
+ changed only in MIRROR. Direction for files that differ on both
37
+ sides is derived from the MIRROR's git history (does LIVE's
38
+ current content match a past MIRROR commit?): it reflects which
39
+ side has moved, not which side is correct. Inspect the diff
40
+ before acting on it.
41
+
42
+ Read-only: makes no changes to either tree, and performs no
43
+ network operations.
44
+
45
+ The MIRROR path must be configured via --mirror-dir or
46
+ rules.mirror_dir in ~/.config/rosett-ai/config.yml — rosett-ai
47
+ does not assume a mirror location.
48
+
49
+ Exit codes: 0 fully in sync, 1 drift detected, 3 mirror not configured.
50
+
51
+ EXAMPLES
52
+
53
+ raictl rules status
54
+ raictl rules status --format json
55
+ raictl rules status --mirror-dir ~/git/example/rosett-ai-mirror/global
56
+ LONGDESC
57
+ method_option :format, type: :string, default: 'table', enum: ['table', 'json'], desc: 'Output format'
58
+ method_option :live_dir, type: :string, default: nil, desc: 'Override the LIVE behaviour directory'
59
+ method_option :mirror_dir, type: :string, default: nil, desc: 'Path to the git-tracked MIRROR directory'
60
+ # Report drift between the LIVE and MIRROR trees.
61
+ # @return [void]
62
+ def status
63
+ mirror_dir = resolve_mirror_dir
64
+ return exit_with_error(t('mirror_not_configured')) unless mirror_dir
65
+
66
+ entries = RosettAi::Rules::StatusChecker.new(live_dir: live_dir, mirror_dir: mirror_dir).check
67
+ render_status(entries)
68
+ exit(entries.any? { |e| e[:state] != :identical } ? 1 : 0)
69
+ end
70
+
71
+ private
72
+
73
+ def t(key, **args)
74
+ ::I18n.t("rosett_ai.rules.#{key}", **args)
75
+ end
76
+
77
+ def live_dir
78
+ options[:live_dir] || RosettAi.paths.rai_conf_dir.join('behaviour').to_s
79
+ end
80
+
81
+ def resolve_mirror_dir
82
+ options[:mirror_dir] || RosettAi.rai_config.rules_mirror_dir
83
+ end
84
+
85
+ def exit_with_error(message)
86
+ warn(Rainbow(message).red)
87
+ exit(3)
88
+ end
89
+
90
+ def render_status(entries)
91
+ if options[:format] == 'json'
92
+ say(JSON.pretty_generate(entries))
93
+ return
94
+ end
95
+
96
+ render_status_table(entries)
97
+ render_status_summary(entries)
98
+ end
99
+
100
+ def render_status_table(entries)
101
+ table = ::Terminal::Table.new(
102
+ headings: ['File', 'State'],
103
+ rows: entries.map { |e| [e[:name], colorize_state(e[:state])] }
104
+ )
105
+ say(table)
106
+ end
107
+
108
+ def colorize_state(state)
109
+ color = STATE_COLORS.fetch(state, :white)
110
+ Rainbow(state.to_s).color(color)
111
+ end
112
+
113
+ def render_status_summary(entries)
114
+ drifted = entries.reject { |e| e[:state] == :identical }
115
+
116
+ if drifted.empty?
117
+ say(t('no_drift', count: entries.size))
118
+ else
119
+ say(Rainbow(t('drift_detected', count: drifted.size)).red)
120
+ end
121
+ end
122
+ end
123
+ end
124
+ end
125
+ end
@@ -5,5 +5,5 @@
5
5
 
6
6
  module RosettAi
7
7
  # @return [String] Current version of the rosett-ai gem.
8
- VERSION = '1.8.1'
8
+ VERSION = '1.11.9'
9
9
  end
data/lib/rosett_ai.rb CHANGED
@@ -77,6 +77,8 @@ module RosettAi
77
77
  class McpError < Error; end
78
78
  # Raised when Claude Code session hook installation fails.
79
79
  class SessionHooksError < Error; end
80
+ # Raised when behaviour-rule LIVE/MIRROR drift operations fail.
81
+ class RulesError < Error; end
80
82
 
81
83
  # @!endgroup
82
84
 
data/locales/en.yml CHANGED
@@ -34,6 +34,17 @@ en:
34
34
  deduplicated: "Deduplicated"
35
35
  deduplicated_detail: "Deduplicated: %{filename} (identical to global)"
36
36
  scope_project_no_project: "Cannot use --scope project: no project detected (no .rosett-ai/ directory found)"
37
+ scope_project_source_repo_hint: "Cannot use --scope project: no .rosett-ai/ directory found. This looks like the rosett-ai source repository itself, not a consuming project — did you mean --scope global?"
38
+ lean_would_write: "Would write lean bundle: %{filename}"
39
+ lean_wrote: "Wrote lean bundle: %{filename} (%{chars} chars)"
40
+ lean_summary_title: "Lean Context Bundles"
41
+ lean_bundle: "Bundle"
42
+ lean_rules: "Rules"
43
+ lean_chars: "Chars"
44
+ lean_tokens: "Tokens (approx)"
45
+ lean_delta: "Delta vs full"
46
+ lean_reference: "full behaviour rules (reference)"
47
+ lean_dir: "Lean bundles written to %{path}"
37
48
  config:
38
49
  scope_not_found: "Scope file not found: %{path}. Valid scopes: %{scopes}"
39
50
  no_scopes: "No scope files found in conf/claude_code/"
@@ -534,6 +545,10 @@ en:
534
545
  detected_managers: "Detected hook managers: %{managers}"
535
546
  install_summary: "Installed %{count} hook(s)."
536
547
  uninstall_summary: "Removed %{count} hook(s)."
548
+ rules:
549
+ mirror_not_configured: "MIRROR directory not configured. Set --mirror-dir or rules.mirror_dir in ~/.config/rosett-ai/config.yml."
550
+ no_drift: "No drift detected — LIVE and MIRROR are in sync (%{count} file(s))."
551
+ drift_detected: "%{count} file(s) with drift detected."
537
552
  mcp:
538
553
  no_servers: "No MCP servers configured."
539
554
  serve_started: "MCP server started on stdio transport."