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
@@ -0,0 +1,44 @@
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 Optimize
8
+ module Detectors
9
+ # Flags rules whose source description exceeds
10
+ # {Thresholds#verbose_bytes_min} bytes. Compile-time payload
11
+ # leanness is a separate C2/C3 concern — this detector targets
12
+ # authoring-time verbosity so authors can trim before it inflates
13
+ # every compiled artifact.
14
+ class TokenCost < Detector
15
+ # Approximation: ~4 chars/token for typical English narrative.
16
+ # Not exact — a hint for the reader, never a hard budget.
17
+ CHARS_PER_TOKEN = 4
18
+
19
+ # @return [Array<Finding>]
20
+ def call
21
+ corpus.rules.filter_map do |rule|
22
+ next if rule.source_bytes <= thresholds.verbose_bytes_min
23
+
24
+ build_finding(rule)
25
+ end
26
+ end
27
+
28
+ private
29
+
30
+ def build_finding(rule)
31
+ approx_tokens = rule.source_bytes / CHARS_PER_TOKEN
32
+ Finding.new(
33
+ detector: :token_cost,
34
+ severity: rule.source_bytes >= (thresholds.verbose_bytes_min * 2) ? :high : :medium,
35
+ behaviour: rule.behaviour,
36
+ rule_id: rule.id,
37
+ summary: "Verbose rule body: #{rule.source_bytes} bytes (~#{approx_tokens} tokens)",
38
+ details: { source_bytes: rule.source_bytes, approx_tokens: approx_tokens }
39
+ )
40
+ end
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,36 @@
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 Optimize
8
+ # Immutable value object describing one optimization finding.
9
+ #
10
+ # @!attribute [r] detector
11
+ # @return [Symbol] :overlap | :staleness | :conflict | :token_cost
12
+ # @!attribute [r] severity
13
+ # @return [Symbol] :low | :medium | :high
14
+ # @!attribute [r] behaviour
15
+ # @return [String] behaviour file basename (without .yml)
16
+ # @!attribute [r] rule_id
17
+ # @return [String, nil] rule id, or nil for behaviour-level findings
18
+ # @!attribute [r] summary
19
+ # @return [String] one-line finding summary
20
+ # @!attribute [r] details
21
+ # @return [Hash] detector-specific context (peer rule, score, terms, etc.)
22
+ Finding = Data.define(:detector, :severity, :behaviour, :rule_id, :summary, :details) do
23
+ # @return [Hash] JSON-safe representation for report / MCP output
24
+ def to_h
25
+ {
26
+ detector: detector.to_s,
27
+ severity: severity.to_s,
28
+ behaviour: behaviour,
29
+ rule_id: rule_id,
30
+ summary: summary,
31
+ details: details
32
+ }
33
+ end
34
+ end
35
+ end
36
+ end
@@ -0,0 +1,54 @@
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 'fileutils'
7
+ require 'yaml'
8
+
9
+ module RosettAi
10
+ module Optimize
11
+ # Writes proposal YAML patch files (one per behaviour) to a directory.
12
+ #
13
+ # Consumed manually by the operator (or by a future review UI). This
14
+ # writer NEVER modifies the source corpus itself — the human gate is
15
+ # mandatory (invisible-user-rules ship-breaker lesson).
16
+ class ProposalWriter
17
+ # @param findings [Array<Finding>]
18
+ def initialize(findings:)
19
+ @findings = findings
20
+ end
21
+
22
+ # Write one YAML patch file per behaviour into `dir`.
23
+ #
24
+ # @param dir [String, Pathname]
25
+ # @return [Array<String>] paths written
26
+ def write(dir)
27
+ FileUtils.mkdir_p(dir)
28
+ grouped.map do |behaviour, findings|
29
+ path = File.join(dir.to_s, "#{behaviour}.proposal.yml")
30
+ File.write(path, YAML.dump('behaviour' => behaviour, 'proposals' => proposals_for(findings)))
31
+ path
32
+ end
33
+ end
34
+
35
+ private
36
+
37
+ def grouped
38
+ @findings.group_by(&:behaviour).sort_by { |k, _| k.to_s }
39
+ end
40
+
41
+ def proposals_for(findings)
42
+ findings.map do |f|
43
+ {
44
+ 'detector' => f.detector.to_s,
45
+ 'rule_id' => f.rule_id,
46
+ 'severity' => f.severity.to_s,
47
+ 'summary' => f.summary,
48
+ 'details' => f.details
49
+ }
50
+ end
51
+ end
52
+ end
53
+ end
54
+ end
@@ -0,0 +1,72 @@
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 Optimize
8
+ # Renders {Finding} lists as Markdown reports.
9
+ #
10
+ # Report-only mode is the default output: a single Markdown file
11
+ # grouped by detector, with a summary count table at the top.
12
+ class ReportWriter
13
+ # @param findings [Array<Finding>]
14
+ # @param generated_at [String] ISO8601 timestamp for the header
15
+ def initialize(findings:, generated_at:)
16
+ @findings = findings
17
+ @generated_at = generated_at
18
+ end
19
+
20
+ # @return [String] full Markdown report
21
+ def render
22
+ sections = [header, summary_table]
23
+ grouped.each { |detector, items| sections << detector_section(detector, items) }
24
+ "#{sections.join("\n\n").rstrip}\n"
25
+ end
26
+
27
+ # Write the rendered report to `path` (creates parent dirs as needed).
28
+ #
29
+ # @param path [String, Pathname]
30
+ # @return [String] the path written
31
+ def write(path)
32
+ require 'fileutils'
33
+ FileUtils.mkdir_p(File.dirname(path))
34
+ File.write(path, render)
35
+ path.to_s
36
+ end
37
+
38
+ private
39
+
40
+ def grouped
41
+ @findings.group_by(&:detector).sort_by { |k, _| k.to_s }
42
+ end
43
+
44
+ def header
45
+ "# rai_optimize report\n\nGenerated: #{@generated_at}\n\nTotal findings: #{@findings.size}"
46
+ end
47
+
48
+ def summary_table
49
+ counts = @findings.group_by(&:detector).transform_values(&:size)
50
+ rows = counts.sort_by { |k, _| k.to_s }.map { |k, v| "| #{k} | #{v} |" }.join("\n")
51
+ <<~TABLE.strip
52
+ ## Summary
53
+
54
+ | Detector | Count |
55
+ |---|---|
56
+ #{rows.empty? ? '| _(none)_ | 0 |' : rows}
57
+ TABLE
58
+ end
59
+
60
+ def detector_section(detector, items)
61
+ rows = items.map { |f| "| #{f.severity} | #{f.behaviour} | #{f.rule_id} | #{f.summary} |" }
62
+ <<~SECTION.strip
63
+ ## #{detector}
64
+
65
+ | Severity | Behaviour | Rule | Summary |
66
+ |---|---|---|---|
67
+ #{rows.join("\n")}
68
+ SECTION
69
+ end
70
+ end
71
+ end
72
+ end
@@ -0,0 +1,38 @@
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 Optimize
8
+ # Orchestrates the four mechanical detectors and returns a flat
9
+ # Array<{Finding}> for the caller (report writer, proposal writer,
10
+ # CLI, MCP tool).
11
+ class Runner
12
+ DETECTORS = [
13
+ Detectors::Overlap,
14
+ Detectors::Staleness,
15
+ Detectors::Conflict,
16
+ Detectors::TokenCost
17
+ ].freeze
18
+
19
+ attr_reader :corpus, :thresholds
20
+
21
+ # @param corpus [Corpus]
22
+ # @param thresholds [Thresholds]
23
+ # @param detectors [Array<Class>] override for tests
24
+ def initialize(corpus:, thresholds:, detectors: DETECTORS)
25
+ @corpus = corpus
26
+ @thresholds = thresholds
27
+ @detectors = detectors
28
+ end
29
+
30
+ # @return [Array<Finding>]
31
+ def run
32
+ @detectors.flat_map do |klass|
33
+ klass.new(corpus: corpus, thresholds: thresholds).call
34
+ end
35
+ end
36
+ end
37
+ end
38
+ end
@@ -0,0 +1,52 @@
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 'yaml'
7
+
8
+ module RosettAi
9
+ module Optimize
10
+ # Detector thresholds — loaded from conf/rai-optimize/thresholds.yml or
11
+ # constructed with defaults matching the ratified design (Jaccard 0.4,
12
+ # inflated priority ≥ 80, verbose byte length > 3000).
13
+ class Thresholds
14
+ DEFAULT_JACCARD_MIN = 0.4
15
+ DEFAULT_INFLATED_PRIORITY_MIN = 80
16
+ DEFAULT_VERBOSE_BYTES_MIN = 3000
17
+
18
+ attr_reader :jaccard_min, :inflated_priority_min, :verbose_bytes_min
19
+
20
+ # @param jaccard_min [Float]
21
+ # @param inflated_priority_min [Integer]
22
+ # @param verbose_bytes_min [Integer]
23
+ def initialize(jaccard_min:, inflated_priority_min:, verbose_bytes_min:)
24
+ @jaccard_min = jaccard_min
25
+ @inflated_priority_min = inflated_priority_min
26
+ @verbose_bytes_min = verbose_bytes_min
27
+ end
28
+
29
+ # @return [Thresholds] instance with ratified design defaults
30
+ def self.defaults
31
+ new(
32
+ jaccard_min: DEFAULT_JACCARD_MIN,
33
+ inflated_priority_min: DEFAULT_INFLATED_PRIORITY_MIN,
34
+ verbose_bytes_min: DEFAULT_VERBOSE_BYTES_MIN
35
+ )
36
+ end
37
+
38
+ # Load thresholds from a YAML file; missing keys fall back to defaults.
39
+ #
40
+ # @param path [String, Pathname]
41
+ # @return [Thresholds]
42
+ def self.load(path)
43
+ raw = YAML.safe_load_file(path.to_s, permitted_classes: [Symbol]) || {}
44
+ new(
45
+ jaccard_min: raw.dig('overlap', 'jaccard_min') || DEFAULT_JACCARD_MIN,
46
+ inflated_priority_min: raw.dig('conflict', 'inflated_priority_min') || DEFAULT_INFLATED_PRIORITY_MIN,
47
+ verbose_bytes_min: raw.dig('token_cost', 'verbose_bytes_min') || DEFAULT_VERBOSE_BYTES_MIN
48
+ )
49
+ end
50
+ end
51
+ end
52
+ end
@@ -0,0 +1,33 @@
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
+ # Mechanical self-optimizer for the rai behaviour corpus.
8
+ #
9
+ # Sibling to {RosettAi::Adopter} (LLM-based analysis) — this module is
10
+ # mechanical only: token overlap, priority-inflation heuristics, staleness
11
+ # vocabulary matches, and byte-cost. No network calls, no LLM.
12
+ #
13
+ # Report-only by default; `--propose` writes YAML patch files to $TMPDIR.
14
+ # This module NEVER auto-applies changes (invisible-user-rules ship-breaker
15
+ # lesson — human gate is mandatory).
16
+ #
17
+ # @see RosettAi::Optimize::Runner
18
+ # @author hugo
19
+ # @author claude
20
+ module Optimize
21
+ # Convenience entry-point: run all detectors against a corpus dir.
22
+ #
23
+ # @param behaviour_dir [String, Pathname] behaviour YAML directory
24
+ # @param thresholds [Thresholds, nil] thresholds (defaults if nil)
25
+ # @return [Array<Finding>] flat list of findings from all detectors
26
+ def self.analyze(behaviour_dir:, thresholds: nil)
27
+ Runner.new(
28
+ corpus: Corpus.load(behaviour_dir),
29
+ thresholds: thresholds || Thresholds.defaults
30
+ ).run
31
+ end
32
+ end
33
+ end
@@ -28,6 +28,12 @@ module RosettAi
28
28
  # @return [Pathname] ~/.claude/rules/
29
29
  def rules_dir = global_dir.join('rules')
30
30
 
31
+ # Lean and role-scoped context bundle output directory. Kept separate from
32
+ # {#rules_dir} so a session loads either the full reference rules or one
33
+ # lean bundle, never both.
34
+ # @return [Pathname] ~/.claude/rules-lean/
35
+ def lean_rules_dir = global_dir.join('rules-lean')
36
+
31
37
  # Project-local configuration directory.
32
38
  # @return [Pathname] .claude/ in the user's working directory
33
39
  def local_dir = Pathname.new(user_pwd).join('.claude')
@@ -54,6 +60,17 @@ module RosettAi
54
60
  # @return [Pathname] /opt/rosett-ai/app/conf
55
61
  def packaged_conf_dir = Pathname.new('/opt/rosett-ai/app/conf')
56
62
 
63
+ # Compile lockfile path (`--vendor` mode). ENV-overridable so vendor
64
+ # writes always target the user config tree, never a packaged
65
+ # install's (possibly root-owned, read-only) conf/ directory.
66
+ # @return [Pathname] $ROSETT_AI_COMPILE_LOCK or ~/.config/rosett-ai/conf/compile.lock.yml
67
+ def compile_lockfile_path
68
+ override = ENV.fetch('ROSETT_AI_COMPILE_LOCK', nil)
69
+ return Pathname.new(override) if override
70
+
71
+ rai_conf_dir.join('compile.lock.yml')
72
+ end
73
+
57
74
  # Encrypted secrets store.
58
75
  # @return [Pathname] secrets.yml inside the rosett-ai config directory
59
76
  def secrets_file = rai_config_dir.join('secrets.yml')
@@ -70,6 +87,10 @@ module RosettAi
70
87
  # @return [Pathname] cache/content/ inside the rosett-ai config directory
71
88
  def content_cache_dir = rai_config_dir.join('cache', 'content')
72
89
 
90
+ # Generated report output directory (e.g. rai_optimize reports).
91
+ # @return [Pathname] reports/ inside the rosett-ai config directory
92
+ def reports_dir = rai_config_dir.join('reports')
93
+
73
94
  # Engine settings target paths
74
95
 
75
96
  # System-wide managed settings (enterprise).
@@ -98,6 +119,10 @@ module RosettAi
98
119
  # @return [String] ~/.claude/rules
99
120
  def rules_display_path = '~/.claude/rules'
100
121
 
122
+ # Tilde-form display path for lean bundle output.
123
+ # @return [String] ~/.claude/rules-lean
124
+ def lean_rules_display_path = '~/.claude/rules-lean'
125
+
101
126
  # The user's original working directory.
102
127
  # When running from the .deb wrapper, Dir.pwd is /opt/rosett-ai/app, so
103
128
  # RAI_ORIGINAL_PWD (set by the wrapper) preserves the real directory.
@@ -120,20 +120,40 @@ module RosettAi
120
120
 
121
121
  # Scan `/opt/rosett-ai/embedded/lib/ruby/gems/*/gems/*/lib/` for plugin
122
122
  # register.rb files. Handles Ruby ABI version mismatches between
123
- # the embedded Ruby and engine gems built with a different minor version.
123
+ # the embedded Ruby and engine gems built with a different minor version
124
+ # — both halves of the SAME `/opt/rosett-ai` installation.
125
+ #
126
+ # Gated by {embedded_install_active?} so that this never reaches into an
127
+ # unrelated `/opt/rosett-ai` installation found on the same host: a
128
+ # source checkout or CI run uses its own Ruby and its own gem home,
129
+ # never the embedded one, so it must never self-discover (and
130
+ # double-load) that installation's plugin gems.
124
131
  #
125
132
  # @param prefix [String] plugin namespace prefix (e.g. 'rosett_ai_engine')
126
133
  def discover_embedded_gems(prefix)
134
+ return unless embedded_install_active?
135
+
127
136
  embedded_gems = Pathname.new('/opt/rosett-ai/embedded/lib/ruby/gems')
128
137
  return unless embedded_gems.directory?
129
138
 
130
- Dir.glob(embedded_gems.join('*', 'gems', '*', 'lib', prefix, '*', 'register.rb').to_s).each do |path|
131
- lib_dir = File.expand_path('../../..', path)
132
- $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
133
- require path
134
- rescue LoadError => e
135
- RosettAi.logger.warn("Failed to load embedded plugin from #{path}: #{e.message}")
136
- end
139
+ pattern = embedded_gems.join('*', 'gems', '*', 'lib', prefix, '*', 'register.rb').to_s
140
+ Dir.glob(pattern).each { |path| require_plugin_file(path, source: 'embedded') }
141
+ end
142
+
143
+ # Is the Ruby process running *this code* itself the hermetic Ruby
144
+ # shipped inside the `/opt/rosett-ai` `.deb` install?
145
+ #
146
+ # The packaged wrapper (`packaging/wrapper.sh.template`) exports
147
+ # `GEM_HOME` to the embedded gem tree before exec-ing the embedded
148
+ # Ruby, so `Gem.dir` is the one reliable runtime signal: it reflects
149
+ # the active bundle actually in effect, not a hardcoded guess. (The
150
+ # embedded Ruby's own compiled-in `RbConfig::CONFIG['prefix']` is
151
+ # NOT usable here — ruby-build bakes in the packaging *staging* path,
152
+ # which does not exist at runtime; see `packaging/scripts/postinst`.)
153
+ #
154
+ # @return [Boolean]
155
+ def embedded_install_active?
156
+ Gem.dir.start_with?('/opt/rosett-ai/embedded')
137
157
  end
138
158
 
139
159
  # Scan directories listed in `RAI_ENGINE_PATH` (colon-separated)
@@ -145,15 +165,25 @@ module RosettAi
145
165
  return unless custom_path
146
166
 
147
167
  custom_path.split(':').each do |dir|
148
- Dir.glob(File.join(dir, 'lib', prefix, '*', 'register.rb')).each do |path|
149
- lib_dir = File.expand_path('../../..', path)
150
- $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
151
- require path
152
- rescue LoadError => e
153
- RosettAi.logger.warn("Failed to load custom plugin from #{path}: #{e.message}")
154
- end
168
+ pattern = File.join(dir, 'lib', prefix, '*', 'register.rb')
169
+ Dir.glob(pattern).each { |path| require_plugin_file(path, source: 'custom') }
155
170
  end
156
171
  end
172
+
173
+ # Require a discovered plugin `register.rb`, prepending its lib dir to
174
+ # `$LOAD_PATH` first. Shared by the embedded-gem-tree and custom-path
175
+ # discovery strategies; logs (rather than raises) on LoadError so one
176
+ # broken plugin never blocks discovery of the others.
177
+ #
178
+ # @param path [String] absolute path to a discovered register.rb
179
+ # @param source [String] discovery strategy name, for the warning message
180
+ def require_plugin_file(path, source:)
181
+ lib_dir = File.expand_path('../../..', path)
182
+ $LOAD_PATH.unshift(lib_dir) unless $LOAD_PATH.include?(lib_dir)
183
+ require path
184
+ rescue LoadError => e
185
+ RosettAi.logger.warn("Failed to load #{source} plugin from #{path}: #{e.message}")
186
+ end
157
187
  end
158
188
  end
159
189
  end
@@ -27,7 +27,7 @@ module RosettAi
27
27
  # @param ai_role [String] one of {ALLOWED_ROLES}
28
28
  # @param files [Array<Hash>] file-level source references
29
29
  # @param timestamp [String, nil] ISO 8601 timestamp (defaults to now)
30
- # rubocop:disable Metrics/ParameterLists -- provenance entry requires all fields
30
+ # rubocop:disable-next Metrics/ParameterLists -- provenance entry requires all fields
31
31
  def initialize(commit:, contributor:, ai_tool:, ai_role:, files: [], timestamp: nil)
32
32
  validate_role!(ai_role)
33
33
 
@@ -38,7 +38,6 @@ module RosettAi
38
38
  @files = files.freeze
39
39
  @timestamp = (timestamp || Time.now.utc.strftime('%Y-%m-%dT%H:%M:%SZ')).freeze
40
40
  end
41
- # rubocop:enable Metrics/ParameterLists
42
41
 
43
42
  # @return [Hash] serializable representation for YAML output
44
43
  def to_h
@@ -35,6 +35,9 @@ module RosettAi
35
35
  def cache_ttl_hours = @data.dig('cache', 'ttl_hours')
36
36
  def detect_on_init? = @data.dig('detect', 'on_init')
37
37
  def dbus_allow_plugin_management? = @data.dig('dbus', 'allow_plugin_management') == true
38
+ # Path to the git-tracked mirror of the LIVE behaviour directory.
39
+ # @return [String, nil]
40
+ def rules_mirror_dir = @data.dig('rules', 'mirror_dir')
38
41
 
39
42
  # Load the license key from persistent storage.
40
43
  #
@@ -0,0 +1,144 @@
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 'digest'
7
+ require 'open3'
8
+
9
+ module RosettAi
10
+ # Drift detection between the LIVE behaviour-rule source tree and its
11
+ # git-tracked MIRROR copy.
12
+ module Rules
13
+ # Compares every behaviour-rule YAML file in a LIVE directory (not
14
+ # git-tracked; the compile source) against its counterpart in a git-
15
+ # tracked MIRROR directory, by content hash.
16
+ #
17
+ # For files present on both sides with differing content, direction is
18
+ # derived from the MIRROR's own git history: if LIVE's current content
19
+ # matches a past commit of the MIRROR file, the MIRROR has moved on
20
+ # since LIVE was last in sync (:mirror_newer); otherwise LIVE holds
21
+ # content the MIRROR's history never captured (:live_newer). This
22
+ # reflects which side has moved, not which side is correct — a human
23
+ # must still inspect the diff before acting on it.
24
+ #
25
+ # Read-only: never writes to either tree, never touches the network.
26
+ #
27
+ # @author claude
28
+ class StatusChecker
29
+ # @return [Array<Symbol>] all possible per-file drift states.
30
+ STATES = [:identical, :live_only, :mirror_only, :live_newer, :mirror_newer].freeze
31
+
32
+ # Git repo-location env vars that git exports into hook subprocesses
33
+ # (pre-commit, pre-push, etc.) so the hook script can find the repo
34
+ # that invoked it. If inherited here, GIT_DIR/GIT_WORK_TREE override
35
+ # the `-C` flag below for some git subcommands (notably `log`'s
36
+ # pathspec resolution) and redirect this class's queries to whichever
37
+ # repo is running the hook, instead of the MIRROR repo it is asked to
38
+ # inspect. Clearing them keeps every subprocess call hermetic to
39
+ # @mirror_dir, regardless of what invoked this process.
40
+ GIT_ENV_OVERRIDE = {
41
+ 'GIT_DIR' => nil,
42
+ 'GIT_WORK_TREE' => nil,
43
+ 'GIT_INDEX_FILE' => nil,
44
+ 'GIT_COMMON_DIR' => nil,
45
+ 'GIT_OBJECT_DIRECTORY' => nil,
46
+ 'GIT_ALTERNATE_OBJECT_DIRECTORIES' => nil
47
+ }.freeze
48
+
49
+ # @param live_dir [String, Pathname] the LIVE behaviour-rule directory
50
+ # @param mirror_dir [String, Pathname] the git-tracked MIRROR directory
51
+ def initialize(live_dir:, mirror_dir:)
52
+ @live_dir = Pathname.new(live_dir)
53
+ @mirror_dir = Pathname.new(mirror_dir)
54
+ end
55
+
56
+ # Classify every file present in either tree.
57
+ #
58
+ # @return [Array<Hash>] one entry per file: { name:, state: }, sorted by name
59
+ def check
60
+ all_names.map { |name| { name: name, state: classify(name) } }
61
+ end
62
+
63
+ # @return [Boolean] true if any file is in a non-identical state
64
+ def drift?
65
+ check.any? { |entry| entry[:state] != :identical }
66
+ end
67
+
68
+ private
69
+
70
+ def all_names
71
+ (yml_names_in(@live_dir) + yml_names_in(@mirror_dir)).uniq.sort
72
+ end
73
+
74
+ def yml_names_in(dir)
75
+ return [] unless dir.directory?
76
+
77
+ Dir.children(dir).select { |f| f.end_with?('.yml') }
78
+ end
79
+
80
+ def classify(name)
81
+ live_path = @live_dir.join(name)
82
+ mirror_path = @mirror_dir.join(name)
83
+ live_exists = live_path.exist?
84
+ mirror_exists = mirror_path.exist?
85
+
86
+ return :live_only if live_exists && !mirror_exists
87
+ return :mirror_only if mirror_exists && !live_exists
88
+
89
+ classify_both_exist(live_path, mirror_path, name)
90
+ end
91
+
92
+ def classify_both_exist(live_path, mirror_path, name)
93
+ live_hash = content_hash(live_path)
94
+ return :identical if live_hash == content_hash(mirror_path)
95
+
96
+ mirror_history_hashes(name).include?(live_hash) ? :mirror_newer : :live_newer
97
+ end
98
+
99
+ # SHA256 blob hashes of every historical commit of the MIRROR file,
100
+ # discovered via the MIRROR directory's own git repository.
101
+ def mirror_history_hashes(name)
102
+ repo_root = mirror_repo_root
103
+ return [] unless repo_root
104
+
105
+ relative_path = @mirror_dir.relative_path_from(repo_root).join(name).to_s
106
+ mirror_log_commits(repo_root, relative_path).filter_map do |sha|
107
+ mirror_show_hash(repo_root, sha, relative_path)
108
+ end
109
+ end
110
+
111
+ def mirror_repo_root
112
+ out, status = Open3.capture2(GIT_ENV_OVERRIDE, 'git', '-C', @mirror_dir.to_s, 'rev-parse', '--show-toplevel')
113
+ return nil unless status.success?
114
+
115
+ Pathname.new(out.strip)
116
+ rescue Errno::ENOENT
117
+ # git binary not available — treat as no history rather than fail
118
+ nil
119
+ end
120
+
121
+ def mirror_log_commits(repo_root, relative_path)
122
+ out, status = Open3.capture2(
123
+ GIT_ENV_OVERRIDE, 'git', '-C', repo_root.to_s, 'log', '--format=%H', '--', relative_path
124
+ )
125
+ return [] unless status.success?
126
+
127
+ out.lines(chomp: true)
128
+ end
129
+
130
+ def mirror_show_hash(repo_root, sha, relative_path)
131
+ content, status = Open3.capture2(
132
+ GIT_ENV_OVERRIDE, 'git', '-C', repo_root.to_s, 'show', "#{sha}:#{relative_path}"
133
+ )
134
+ return nil unless status.success?
135
+
136
+ Digest::SHA256.hexdigest(content)
137
+ end
138
+
139
+ def content_hash(path)
140
+ Digest::SHA256.file(path).hexdigest
141
+ end
142
+ end
143
+ end
144
+ end
@@ -42,7 +42,7 @@ module RosettAi
42
42
  return unless @rotator.rotate_if_needed!
43
43
 
44
44
  @io.close
45
- @io = File.open(@rotator.path, 'a') # rubocop:disable Style/FileOpen -- lifecycle managed by #close
45
+ @io = File.open(@rotator.path, 'a')
46
46
  @io.sync = true
47
47
  end
48
48
  end