rubik 0.15.1 → 0.15.3

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 (55) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +67 -2
  4. data/lib/rubik/ast/cache_store.rb +22 -4
  5. data/lib/rubik/ast/extractor.rb +1 -4
  6. data/lib/rubik/ast/ruby_extractor.rb +23 -1
  7. data/lib/rubik/ast/symbol.rb +9 -4
  8. data/lib/rubik/ast/treesitter/python_walker.rb +5 -4
  9. data/lib/rubik/ast/treesitter_extractor.rb +10 -3
  10. data/lib/rubik/buffer/diff.rb +34 -2
  11. data/lib/rubik/buffer/manager.rb +18 -15
  12. data/lib/rubik/buffer/path_validator.rb +18 -2
  13. data/lib/rubik/buffer/snapshot.rb +144 -9
  14. data/lib/rubik/concurrency/timers.rb +7 -0
  15. data/lib/rubik/config/scoped.rb +18 -7
  16. data/lib/rubik/config/secret_policy.rb +22 -1
  17. data/lib/rubik/config.rb +24 -26
  18. data/lib/rubik/context/ignore_rules.rb +7 -2
  19. data/lib/rubik/diagnostics/parser.rb +19 -8
  20. data/lib/rubik/kernel/dispatcher.rb +11 -5
  21. data/lib/rubik/llm/client.rb +24 -3
  22. data/lib/rubik/llm/connection_pool.rb +51 -30
  23. data/lib/rubik/llm/message_sanitizer.rb +20 -1
  24. data/lib/rubik/llm/sse_parser.rb +10 -1
  25. data/lib/rubik/lsp/client.rb +9 -2
  26. data/lib/rubik/lsp/manager.rb +43 -40
  27. data/lib/rubik/lsp/transport.rb +61 -1
  28. data/lib/rubik/mcp/transport/stdio.rb +143 -131
  29. data/lib/rubik/orchestrator/activity_log.rb +3 -2
  30. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  31. data/lib/rubik/orchestrator/loop.rb +11 -12
  32. data/lib/rubik/orchestrator/subagent/completion.rb +18 -8
  33. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +5 -1
  34. data/lib/rubik/platform/process.rb +74 -19
  35. data/lib/rubik/platform.rb +16 -16
  36. data/lib/rubik/plugin/manager.rb +5 -6
  37. data/lib/rubik/repl/service_catalog.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +29 -23
  39. data/lib/rubik/repl/turn_recorder.rb +35 -11
  40. data/lib/rubik/sandbox/driver/base.rb +26 -3
  41. data/lib/rubik/sandbox/driver/bubblewrap.rb +6 -11
  42. data/lib/rubik/sandbox/driver/docker.rb +1 -11
  43. data/lib/rubik/sandbox/driver/podman.rb +26 -18
  44. data/lib/rubik/sandbox/driver/process.rb +16 -35
  45. data/lib/rubik/security/blocked_guidance.rb +4 -2
  46. data/lib/rubik/security/command_gate.rb +27 -14
  47. data/lib/rubik/security/errors.rb +13 -0
  48. data/lib/rubik/security/guard.rb +11 -2
  49. data/lib/rubik/security/path_policy.rb +9 -6
  50. data/lib/rubik/storage/store.rb +31 -11
  51. data/lib/rubik/tools/builtins/exec.rb +5 -1
  52. data/lib/rubik/tools/builtins/files.rb +2 -0
  53. data/lib/rubik/tools/uri_resolver.rb +23 -3
  54. data/lib/rubik/version.rb +1 -1
  55. metadata +1 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: '08ead4917c80a160b0885ec8475ae49f868e7ddca67cff0882b2de186004e191'
4
- data.tar.gz: '05881ac194a5a4ce290edbec35a0cebe604bb1582cc4c16dedde96945c499978'
3
+ metadata.gz: eb4f40352908b9a2c44b024c067fe108055476241d23104da27b7ba81b71de53
4
+ data.tar.gz: 17ba304d921e9def01174462bf4bf910c49f8d8981dfffb74e8700c9a3996adf
5
5
  SHA512:
6
- metadata.gz: 0ba7c80941d3dfa029e68833ebed20f6a0f52f86a9650d96d911ec034b30898aac728838908220e207fa00a66761f057e5b9aec9092f1911f7aba8480b8e3091
7
- data.tar.gz: eb26e26a2ce8aea909f10b3c3589064bc3bde609e766863bc7234c521ecae9bdfc46825323aff2ddbca736dc0a8fee869f2058a2abc64613c58acc13de0c6c5d
6
+ metadata.gz: 635c505dabda41761b377274079bf9111caeaad1b8d2788748b3ec2758873360d10b15e95e08b8152c410aca6045aaae975e1eb6a0b51dfc2a176119fcb84547
7
+ data.tar.gz: 06dececc4bc5612c1382362f2d5038a40a862b016cce08b08bebd14cdd7ca09dd7cb4c8c387416581b7bddff3d04b8b527f672199299274b6b48407321cdd702
data/ATTRIBUTION.md CHANGED
@@ -121,7 +121,7 @@ SOFTWARE.
121
121
  | **`strings-ansi`** | Piotr Murach | MIT | ANSI-aware string truncation and alignment for REPL formatters. |
122
122
  | **`reline`** | Hiroshi SHIBATA & Ruby Team | Ruby License / BSD-2-Clause | Line-editing, history navigation, autocompletion hooks, and headless terminal adaptation. |
123
123
  | **`prism`** | Kevin Newton & Ruby Core Team | MIT | High-performance Ruby parsing and AST extraction ([`Rubik::AST::RubyExtractor`](lib/rubik/ast/ruby_extractor.rb)). |
124
- | **`minitest`** | Ryan Davis & seattlerb | MIT | Fast, modular test suite powering Rubik's 4,950+ unit, integration, and contract tests. |
124
+ | **`minitest`** | Ryan Davis & seattlerb | MIT | Fast, modular test suite powering Rubik's 5,090+ unit, integration, and contract tests. |
125
125
  | **`rubocop`** | Bozhidar Batsov & contributors | MIT | Static code analysis, style enforcement, and architectural hygiene gates. |
126
126
  | **`benchmark`, `logger`, `pstore`, `reline`, `fiddle`** | Ruby core / rubygems teams | Ruby License / BSD-2-Clause | Ruby stdlib gems pinned explicitly in `rubik.gemspec` as they are unbundled from the default set in Ruby 3.4/3.5. |
127
127
 
data/CHANGELOG.md CHANGED
@@ -8,6 +8,71 @@ The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
9
  ## [Unreleased]
10
10
 
11
+ ## [0.15.3] - 2026-11-24
12
+
13
+ The hardening wave: eight fix branches landed back-to-back, closing
14
+ concurrency, buffer-integrity, security and tooling regressions across the
15
+ orchestrator, storage, config redaction, AST indexing and LLM streaming.
16
+
17
+ ### Fixed
18
+
19
+ - **Concurrency (PR #641, #620/#626/#630/#636):** the priority heap invariant
20
+ is restored after re-prioritization, index writes are serialized, and spawn
21
+ guards cover the remaining race windows; stdio MCP teardown now passes
22
+ spawn-time identity so the right child is killed.
23
+ - **Buffer integrity (PR #643, #628/#629):** buffer edits preserve binary
24
+ bytes, and snapshots restore correctly after restart.
25
+ - **Security hardening (PR #646, #624/#637/#638):** every spawn path is
26
+ gated, absolute helper paths are trusted, tool inputs are hardened,
27
+ secrets are redacted in subscriber/listener error messages, rejected
28
+ message previews escape control characters, and timeout kills thread the
29
+ spawn identity through.
30
+ - **Orchestrator + REPL (PR #642, #619/#621/#635):** subagent completion is
31
+ guaranteed (no silently dropped results), recent activity is kept, notice
32
+ injection is atomic with window trim, and the terminal guard stays within
33
+ the line cap.
34
+ - **Config secrets (PR #640, #622/#623/#625):** secrets are redacted in
35
+ events, and dispatch no longer happens while holding the monitor.
36
+ - **AST indexing (PR #644, #627/#633):** parse status is reported honestly,
37
+ index/cache paths are hardened against traversal, per-entry realpath is
38
+ dropped from cache load, the first Go location parses, and binary-tagged
39
+ source is normalized (CodeQL alerts cleared).
40
+ - **Buffer streaming (PR #645, #631/#634):** stream buffers are bounded and
41
+ deadline frame body reads enforced in the LLM and LSP transports.
42
+ - **Snapshot (PR #645 wave):** startup restore is hardened against malformed
43
+ and hostile files.
44
+ - **Dev tooling (PR #647, #632/#639):** temp-root cleanup is safe, the serial
45
+ performance gate is documented with real CI signal, lock-probe timeouts
46
+ are widened for loaded CI runners, and symlinked index locks are refused
47
+ with the pool re-entry window closed (POSIX NOFOLLOW guarded for Windows).
48
+
49
+ ## [0.15.2] - 2026-11-23
50
+
51
+ The suspend-and-redact patch: output-token truncation suspends a goal
52
+ instead of failing it, container driver output joins the redaction
53
+ pipeline — and three refactors collapse duplicated spawn-env, loop-context
54
+ and LSP-delegation patterns behind single seams.
55
+
56
+ ### Fixed
57
+
58
+ - **Goals suspend instead of failing on output-token truncation (#614):**
59
+ reaching the auto-continue ceiling while producing a large report used to
60
+ fail the goal terminally. The truncation is now tagged terminal with
61
+ `:output_truncated` and routed through the existing transient-error
62
+ suspend path, so the goal is resumable with its loop, counters and ledger
63
+ preserved; the continuation buffer flushes at the terminal so a resumed
64
+ turn neither duplicates the stitched partial nor re-inherits exhausted
65
+ strikes. A charset-less provider error body is also sanitized at
66
+ `suspend_goal_turn` entry (the suspend path had the same
67
+ `Encoding::CompatibilityError` gap the fail path had).
68
+ - **Container driver output is redacted (#615):** Docker, podman and
69
+ bubblewrap drivers passed stdout/stderr/output through unredacted while
70
+ ProcessDriver always redacted — a credential printed inside a container
71
+ reached model-visible output unmasked. Result assembly now funnels through
72
+ `Base#finalize_result`; podman also gains the named container +
73
+ timeout force-remove cleanup docker already had, and redundant guard
74
+ deduplication is dropped.
75
+
11
76
  ## [0.15.1] - 2026-11-20
12
77
 
13
78
  The subagent-report-rescue patch: a report turn whose reasoning spends the
@@ -1920,7 +1985,8 @@ installation section.
1920
1985
 
1921
1986
  - Agent loop: token budget autonomy with auto-continuation, wait hints,
1922
1987
  reactive wakeups, and structured failure notices (Plan 90, 109).
1923
- - Kernel: deterministic event dispatcher, kworker queue, monotonic dmesg ring
1988
+ [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.15.3...HEAD
1989
+ [0.15.3]: https://github.com/ozgurulukir/rubik/compare/v0.15.2...v0.15.3
1924
1990
  buffer with `!dmesg` (Plans 102–104).
1925
1991
  - Tools: `ask_question` interactive dialog (Plan 92), async background task
1926
1992
  manager with `manage_task` (Plan 93), native search with rg fallback,
@@ -1958,7 +2024,6 @@ installation section.
1958
2024
  - Context: serialized index mutations, snapshot-outside-lock reconcile,
1959
2025
  streaming-first truncation.
1960
2026
 
1961
- [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.15.1...HEAD
1962
2027
  [0.15.1]: https://github.com/ozgurulukir/rubik/compare/v0.15.0...v0.15.1
1963
2028
  [0.15.0]: https://github.com/ozgurulukir/rubik/compare/v0.14.0...v0.15.0
1964
2029
  [0.14.0]: https://github.com/ozgurulukir/rubik/compare/v0.13.0...v0.14.0
@@ -80,7 +80,7 @@ module Rubik
80
80
  lang = LANGUAGE_MAP[ext] || "unknown"
81
81
 
82
82
  digest = begin
83
- Digest::SHA1.file(full_path).hexdigest
83
+ Digest::SHA256.file(full_path).hexdigest
84
84
  rescue Errno::ENOENT, Errno::EACCES
85
85
  nil
86
86
  end
@@ -150,6 +150,22 @@ module Rubik
150
150
  # Same entries as #load, paired with the persisted per-file extraction
151
151
  # status keyed by the same expanded paths (issue #147 across the cache
152
152
  # boundary: a cache-loaded file must not report "never attempted").
153
+ # A rel_path read back from cache JSON is untrusted: confine it under
154
+ # @root_dir so a tampered ".." or absolute entry cannot make the loader
155
+ # stat/hash (and key symbols by) a file outside the project root.
156
+ def confined_path(rel_path)
157
+ full = File.expand_path(rel_path, @root_dir)
158
+ prefix = @root_dir.end_with?(File::SEPARATOR) ? @root_dir : "#{@root_dir}#{File::SEPARATOR}"
159
+ return nil unless full == @root_dir || full.start_with?(prefix)
160
+
161
+ # Symlink-based escapes are deliberately out of scope here: resolving
162
+ # every entry with realpath makes warm cache loads slower than a cold
163
+ # scan and breaks the runtime capacity gate. Tracked as a follow-up.
164
+ full
165
+ rescue ArgumentError, TypeError
166
+ nil
167
+ end
168
+
153
169
  def load_with_statuses
154
170
  target_path = cache_path
155
171
  return [{}, {}] unless File.exist?(target_path)
@@ -161,7 +177,8 @@ module Rubik
161
177
  result = {}
162
178
  statuses = {}
163
179
  data["files"].each do |rel_path, cached_info|
164
- full_path = File.expand_path(rel_path, @root_dir)
180
+ full_path = confined_path(rel_path)
181
+ next unless full_path
165
182
  next unless valid_entry?(full_path, cached_info)
166
183
 
167
184
  symbols_raw = cached_info["symbols"] || []
@@ -209,7 +226,8 @@ module Rubik
209
226
  def valid_entry?(file_path, cached_info)
210
227
  return false unless cached_info.is_a?(Hash)
211
228
 
212
- full_path = File.expand_path(file_path, @root_dir)
229
+ full_path = confined_path(file_path)
230
+ return false unless full_path
213
231
  return false unless File.exist?(full_path) && File.file?(full_path)
214
232
 
215
233
  stat = File.stat(full_path)
@@ -231,7 +249,7 @@ module Rubik
231
249
  return false unless cached_digest
232
250
 
233
251
  current_digest = begin
234
- Digest::SHA1.file(full_path).hexdigest
252
+ Digest::SHA256.file(full_path).hexdigest
235
253
  rescue Errno::ENOENT, Errno::EACCES
236
254
  nil
237
255
  end
@@ -44,10 +44,7 @@ module Rubik
44
44
  ext = File.extname(file_path).downcase
45
45
 
46
46
  # 1. Ruby files: always use Prism-powered RubyExtractor first
47
- if ext == ".rb"
48
- return ExtractionResult.new(symbols: RubyExtractor.extract(file_path, content),
49
- status: :ok, source: :ruby)
50
- end
47
+ return RubyExtractor.extract_result(file_path, content) if ext == ".rb"
51
48
 
52
49
  # 2. Polyglot files: use the Tree-Sitter AST extractor if available
53
50
  if TreeSitterExtractor.available? && TreeSitterExtractor.supports?(ext)
@@ -3,6 +3,7 @@
3
3
  require_relative "symbol"
4
4
  require_relative "body_loader"
5
5
  require_relative "fallback_cleaner"
6
+ require_relative "extraction_result"
6
7
 
7
8
  module Rubik
8
9
  module AST
@@ -21,10 +22,19 @@ module Rubik
21
22
 
22
23
  include BodyLoader
23
24
 
25
+ attr_reader :parse_status, :parse_detail
26
+
24
27
  def self.extract(file_path, content = nil)
25
28
  new(file_path, content).extract
26
29
  end
27
30
 
31
+ # Real Prism verdict (issue #627): a broken parse is never a clean :ok.
32
+ def self.extract_result(file_path, content = nil)
33
+ extractor = new(file_path, content)
34
+ symbols = extractor.extract
35
+ ExtractionResult.new(symbols: symbols, status: extractor.parse_status, source: :ruby, detail: extractor.parse_detail)
36
+ end
37
+
28
38
  def initialize(file_path, content = nil, force_fallback: false)
29
39
  @file_path = file_path
30
40
  @content = content || (File.exist?(file_path) ? File.read(file_path) : "")
@@ -34,6 +44,8 @@ module Rubik
34
44
  # stubbed; it is resolved at require time).
35
45
  @use_prism = PRISM_AVAILABLE && !force_fallback
36
46
  @code_lines = nil
47
+ @parse_status = :ok
48
+ @parse_detail = nil
37
49
  end
38
50
 
39
51
  # Line array is materialized on demand: the Prism walk only needs AST
@@ -65,10 +77,20 @@ module Rubik
65
77
  private
66
78
 
67
79
  def extract_via_prism(symbols)
68
- result = Prism.parse(@content)
80
+ # valid_encoding? is true for any byte string tagged ASCII-8BIT, so a
81
+ # binary-tagged source with invalid bytes would be misreported as a
82
+ # syntax error. Reuse the shared scrubber (it re-tags BINARY first).
83
+ source = Symbol.scrub_if_invalid(@content)
84
+ result = Prism.parse(source)
69
85
  return unless result.value
70
86
 
71
87
  walk_node(result.value, nil, symbols)
88
+ return if result.success?
89
+
90
+ # Keep partial symbols as best-effort, but never report :ok: the
91
+ # graph's stale protection and cache writer both key off the status.
92
+ @parse_status = :failed
93
+ @parse_detail = "Prism reported #{result.errors.length} parse error(s)"
72
94
  end
73
95
 
74
96
  def walk_node(node, current_scope, symbols)
@@ -53,11 +53,16 @@ module Rubik
53
53
  end
54
54
 
55
55
  def self.read_source_range(file, l_start, l_end)
56
- return nil unless file && l_start && File.exist?(file)
56
+ return nil unless file && l_start && l_start >= 1 && File.exist?(file)
57
57
 
58
- lines = File.readlines(file)
59
- selected = lines[(l_start - 1)..(l_end - 1)] if l_start >= 1
60
- scrub_if_invalid(selected&.join)
58
+ selected = []
59
+ File.foreach(file).with_index(1) do |line, line_no|
60
+ next if line_no < l_start
61
+ break if line_no > l_end
62
+
63
+ selected << line
64
+ end
65
+ scrub_if_invalid(selected.join)
61
66
  rescue Errno::ENOENT, Errno::EACCES, Errno::EISDIR
62
67
  nil
63
68
  end
@@ -23,7 +23,7 @@ module Rubik
23
23
  child = node.named_child(i)
24
24
  case child.kind
25
25
  when "class_definition"
26
- walk_class(child, symbols, depth: depth + 1)
26
+ walk_class(child, symbols, depth: depth + 1, scope: current_class)
27
27
  when "function_definition"
28
28
  walk_function(child, symbols, current_class)
29
29
  when "import_statement", "import_from_statement"
@@ -34,16 +34,17 @@ module Rubik
34
34
  end
35
35
  end
36
36
 
37
- def walk_class(node, symbols, depth: 0)
37
+ def walk_class(node, symbols, depth: 0, scope: nil)
38
38
  name_node = node.child_by_field_name("name")
39
39
  return unless name_node
40
40
 
41
41
  class_name = text_for(name_node)
42
+ qualified_name = scope ? "#{scope}.#{class_name}" : class_name
42
43
  sig = text_for(node).lines.first.to_s.strip.sub(/:$/, "")
43
44
  docstring = extract_docstring(node.child_by_field_name("body"))
44
45
 
45
46
  symbols << build_symbol(
46
- name: class_name,
47
+ name: qualified_name,
47
48
  kind: :class,
48
49
  node: node,
49
50
  signature: sig,
@@ -51,7 +52,7 @@ module Rubik
51
52
  )
52
53
 
53
54
  body = node.child_by_field_name("body")
54
- walk_children(body, symbols, class_name, depth: depth + 1) if body
55
+ walk_children(body, symbols, qualified_name, depth: depth + 1) if body
55
56
  end
56
57
 
57
58
  def walk_function(node, symbols, current_class)
@@ -20,6 +20,9 @@ require_relative "treesitter/zig_walker"
20
20
  module Rubik
21
21
  module AST
22
22
  class TreeSitterExtractor
23
+ @parser_generation = 0
24
+ @generation_mutex = Mutex.new
25
+
23
26
  LANGUAGE_MAP = {
24
27
  ".py" => { parser: "python", walker: TreeSitter::PythonWalker },
25
28
  ".go" => { parser: "go", walker: TreeSitter::GoWalker },
@@ -49,12 +52,17 @@ module Rubik
49
52
  end
50
53
 
51
54
  def parser_for(lang_name)
52
- Thread.current[:rubik_ts_parsers] ||= {}
55
+ generation = @generation_mutex.synchronize { @parser_generation }
56
+ if Thread.current[:rubik_ts_parser_generation] != generation
57
+ Thread.current[:rubik_ts_parsers] = {}
58
+ Thread.current[:rubik_ts_parser_generation] = generation
59
+ end
53
60
  Thread.current[:rubik_ts_parsers][lang_name] ||= TreeSitterLanguagePack.get_parser(lang_name)
54
61
  end
55
62
 
56
63
  def clear_parsers!
57
- Thread.current[:rubik_ts_parsers]&.clear
64
+ @generation_mutex.synchronize { @parser_generation += 1 }
65
+ Thread.current[:rubik_ts_parsers] = {}
58
66
  end
59
67
 
60
68
  # Array-or-nil seam (unchanged contract for every existing caller):
@@ -78,7 +86,6 @@ module Rubik
78
86
  return ExtractionResult.new(symbols: [], status: :ok, source: :tree_sitter) if code.empty?
79
87
 
80
88
  code = code.encode("UTF-8", invalid: :replace, undef: :replace) unless code.valid_encoding?
81
-
82
89
  parser = parser_for(mapping[:parser])
83
90
  return failed_result("no parser for #{mapping[:parser]}") unless parser
84
91
 
@@ -6,9 +6,15 @@ require "diff/lcs/hunk"
6
6
  module Rubik
7
7
  module Buffer
8
8
  class Diff
9
+ # Line diffs are only meaningful for text. Binary buffers (issue #628)
10
+ # get a placeholder instead of a fake diff produced by scrubbing away
11
+ # the very bytes that differ.
9
12
  def self.unified_diff(file_path, original_content, new_content, context: 3)
10
- orig_lines = (original_content || "").lines
11
- new_lines = (new_content || "").lines
13
+ binary = binary?(original_content) || binary?(new_content)
14
+ return "Binary files a/#{file_path} and b/#{file_path} differ\n" if binary
15
+
16
+ orig_lines = text_lines(original_content)
17
+ new_lines = text_lines(new_content)
12
18
 
13
19
  return "" if orig_lines == new_lines
14
20
 
@@ -38,6 +44,32 @@ module Rubik
38
44
 
39
45
  output
40
46
  end
47
+
48
+ # Diff::LCS compares strings by encoding; binary-safe reads can hand
49
+ # it ASCII-8BIT on one side and UTF-8 on the other. Normalize to valid
50
+ # UTF-8 for DISPLAY only — hashing and apply use the untouched bytes.
51
+ def self.text_lines(content)
52
+ text = (content || "").to_s
53
+ text = text.dup.force_encoding(Encoding::UTF_8) unless text.encoding == Encoding::UTF_8
54
+ text = text.scrub("") unless text.valid_encoding?
55
+ text.lines
56
+ end
57
+
58
+ def self.binary?(content)
59
+ return false unless content.is_a?(String)
60
+
61
+ bytes = content.b
62
+ return true if bytes.include?("\x00".b)
63
+
64
+ text = bytes.dup.force_encoding(Encoding::UTF_8)
65
+ return false if text.valid_encoding?
66
+
67
+ # A lone bad byte in an otherwise textual file stays diffable
68
+ # (legacy UTF-8 recovery). Two or more signal binary content where
69
+ # scrubbing would fabricate a meaningless diff (issue #628).
70
+ bytes.bytesize - text.scrub("").bytesize > 1
71
+ end
72
+ private_class_method :text_lines, :binary?
41
73
  end
42
74
  end
43
75
  end
@@ -171,10 +171,10 @@ module Rubik
171
171
  end
172
172
 
173
173
  # Reads a file from the buffer (if dirty) or from disk. Raw bytes —
174
- # including CRLF line endings — are preserved end-to-end: a read/edit/
175
- # write cycle on a CRLF file must not rewrite every line ending to LF
176
- # (issue #544). Newline normalization is confined to conflict-detection
177
- # hashing, never to the content that is buffered or applied to disk.
174
+ # including CRLF line endings and invalid UTF-8 sequences — are
175
+ # preserved end-to-end: a read/edit/write cycle must not normalize
176
+ # line endings (issue #544) or scrub binary content (issue #628).
177
+ # Conflict-detection hashes are computed from those same raw bytes.
178
178
  #
179
179
  # @param path [String] file path relative to the root directory
180
180
  # @param reload [Boolean] force reload from disk, discarding in-memory buffer if present
@@ -194,7 +194,7 @@ module Rubik
194
194
  full_path = File.expand_path(rel_path, @root_dir)
195
195
  return nil unless File.exist?(full_path)
196
196
 
197
- return read_bytes_as_utf8(full_path)
197
+ return read_file_content(full_path)
198
198
  elsif @buffer.key?(rel_path)
199
199
  return @buffer[rel_path]
200
200
  end
@@ -202,7 +202,7 @@ module Rubik
202
202
  full_path = File.expand_path(rel_path, @root_dir)
203
203
  return nil unless File.exist?(full_path)
204
204
 
205
- content = read_bytes_as_utf8(full_path)
205
+ content = read_file_content(full_path)
206
206
  @original_hashes[rel_path] = Digest::SHA256.hexdigest(content)
207
207
  content
208
208
  end
@@ -225,7 +225,7 @@ module Rubik
225
225
  rel_path = sanitize_path(path, for_write: true)
226
226
  if reset_baseline || !@original_hashes.key?(rel_path)
227
227
  full_path = File.expand_path(rel_path, @root_dir)
228
- @original_hashes[rel_path] = (Digest::SHA256.hexdigest(read_bytes_as_utf8(full_path)) if File.exist?(full_path))
228
+ @original_hashes[rel_path] = (Digest::SHA256.hexdigest(read_file_content(full_path)) if File.exist?(full_path))
229
229
  end
230
230
 
231
231
  @buffer[rel_path] = content
@@ -326,7 +326,7 @@ module Rubik
326
326
 
327
327
  diffs = snapshot.map do |rel_path, new_content|
328
328
  full_path = File.expand_path(rel_path, @root_dir)
329
- orig_content = File.exist?(full_path) ? read_bytes_as_utf8(full_path) : ""
329
+ orig_content = File.exist?(full_path) ? read_file_content(full_path) : ""
330
330
  Diff.unified_diff(rel_path, orig_content, new_content)
331
331
  end
332
332
 
@@ -437,19 +437,22 @@ module Rubik
437
437
  full_path = File.expand_path(rel_path, @root_dir)
438
438
  return nil unless File.exist?(full_path)
439
439
 
440
- Digest::SHA256.hexdigest(read_bytes_as_utf8(full_path))
440
+ Digest::SHA256.hexdigest(read_file_content(full_path))
441
441
  rescue Errno::ENOENT, Errno::EACCES
442
442
  nil
443
443
  end
444
444
 
445
445
  private
446
446
 
447
- # Platform.read_text uses File.read (text mode), which translates
448
- # CRLF to LF on Windows and would silently break the raw-byte
449
- # newline contract (issue #544). File.binread keeps the bytes;
450
- # safe_utf8 re-tags and scrubs exactly as read_text does.
451
- def read_bytes_as_utf8(full_path)
452
- Rubik::Platform.safe_utf8(File.binread(full_path))
447
+ # File.binread keeps raw bytes (text-mode File.read would normalize
448
+ # CRLF on Windows, issue #544). Valid UTF-8 bytes are re-tagged as
449
+ # UTF-8 for the text pipeline; invalid sequences stay verbatim as
450
+ # ASCII-8BIT instead of being scrubbed away, so distinct binary files
451
+ # hash differently and apply byte-identically (issue #628).
452
+ def read_file_content(full_path)
453
+ raw = File.binread(full_path)
454
+ text = raw.dup.force_encoding(Encoding::UTF_8)
455
+ text.valid_encoding? ? text : raw
453
456
  end
454
457
  end
455
458
  end
@@ -14,9 +14,13 @@ module Rubik
14
14
  INVALID_PATH_CHARS = [",", "?", "*", '"', "<", ">", "|", "\0"].freeze
15
15
 
16
16
  class << self
17
- # Checks whether a file path is valid for writing.
17
+ # Narrow garbage-path filter, NOT a containment check: it rejects LLM
18
+ # code-fragment leakage, but deliberately accepts absolute paths so
19
+ # configured external dirs can be written. Containment lives in
20
+ # BufferManager#sanitize_path and the apply-time recheck; callers that
21
+ # take model-supplied paths should also use contained_relative?.
18
22
  #
19
- # A path is valid if it:
23
+ # A path passes this filter if it:
20
24
  # 1. Is non-nil and non-blank
21
25
  # 2. Contains no invalid characters (see INVALID_PATH_CHARS)
22
26
  # 3. Matches at least one positive pattern:
@@ -49,6 +53,18 @@ module Rubik
49
53
  false
50
54
  end
51
55
 
56
+ # Shape gate for model-supplied paths: workspace-relative, no drive
57
+ # prefix, no "~" and no ".." segment. Complements (does not replace)
58
+ # the filesystem-level containment checks.
59
+ def contained_relative?(path)
60
+ cleaned = path.to_s.strip
61
+ return false unless valid?(cleaned)
62
+ return false if cleaned.start_with?("/", "\\", "~")
63
+ return false if cleaned.match?(%r{\A[a-zA-Z]:[\\/]})
64
+
65
+ !cleaned.split(%r{[/\\]}, -1).include?("..")
66
+ end
67
+
52
68
  private
53
69
 
54
70
  def contains_invalid_chars?(cleaned)