rubik 0.9.0 → 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (130) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +250 -43
  4. data/README.md +5 -1
  5. data/lib/rubik/adapter/base.rb +21 -1
  6. data/lib/rubik/adapter/generic.rb +0 -14
  7. data/lib/rubik/adapter/node.rb +2 -0
  8. data/lib/rubik/adapter/process.rb +28 -67
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/benchmark/vakanuvis_adoption.rb +10 -3
  11. data/lib/rubik/buffer/apply_contract.rb +3 -3
  12. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  13. data/lib/rubik/buffer/manager.rb +26 -120
  14. data/lib/rubik/cli/workspace_trust.rb +16 -0
  15. data/lib/rubik/config/deep_ops.rb +4 -1
  16. data/lib/rubik/config/defaults.rb +29 -3
  17. data/lib/rubik/config/schema.rb +8 -0
  18. data/lib/rubik/config/secret_policy.rb +197 -0
  19. data/lib/rubik/config/store.rb +14 -0
  20. data/lib/rubik/config.rb +11 -0
  21. data/lib/rubik/diagnostics/collector.rb +0 -9
  22. data/lib/rubik/errors.rb +15 -0
  23. data/lib/rubik/event_bus.rb +2 -1
  24. data/lib/rubik/kernel/dispatcher.rb +16 -11
  25. data/lib/rubik/kernel/unit.rb +4 -1
  26. data/lib/rubik/llm/registry.rb +12 -9
  27. data/lib/rubik/llm/router.rb +2 -5
  28. data/lib/rubik/log.rb +23 -1
  29. data/lib/rubik/lsp/client.rb +152 -445
  30. data/lib/rubik/lsp/document_store.rb +209 -0
  31. data/lib/rubik/lsp/manager.rb +14 -10
  32. data/lib/rubik/lsp/transport.rb +365 -0
  33. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  34. data/lib/rubik/mcp/boot_run.rb +190 -0
  35. data/lib/rubik/mcp/client.rb +4 -3
  36. data/lib/rubik/mcp/manager.rb +46 -165
  37. data/lib/rubik/mcp/transport/stdio.rb +55 -10
  38. data/lib/rubik/orchestrator/auto_apply.rb +4 -3
  39. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  40. data/lib/rubik/orchestrator/goal_session.rb +519 -0
  41. data/lib/rubik/orchestrator/loop.rb +28 -47
  42. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  43. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  44. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  45. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  46. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  47. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  48. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  49. data/lib/rubik/orchestrator/subagent/instance.rb +11 -12
  50. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  51. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  52. data/lib/rubik/orchestrator/subagent/questioner.rb +24 -7
  53. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  54. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  55. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  56. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  57. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  58. data/lib/rubik/orchestrator/subagent/step_runner.rb +11 -3
  59. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  60. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  61. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  62. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  63. data/lib/rubik/orchestrator.rb +1 -0
  64. data/lib/rubik/platform/io_drain.rb +2 -1
  65. data/lib/rubik/platform/process.rb +144 -54
  66. data/lib/rubik/platform.rb +17 -1
  67. data/lib/rubik/plugin/manager.rb +2 -1
  68. data/lib/rubik/plugin/storage.rb +20 -29
  69. data/lib/rubik/repl/commands/agent_context.rb +9 -8
  70. data/lib/rubik/repl/commands/agent_execution.rb +20 -502
  71. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  72. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  73. data/lib/rubik/repl/commands/base.rb +47 -2
  74. data/lib/rubik/repl/commands/buffer.rb +6 -5
  75. data/lib/rubik/repl/commands/lsp.rb +3 -2
  76. data/lib/rubik/repl/commands/pruner.rb +2 -1
  77. data/lib/rubik/repl/commands/secrets.rb +151 -0
  78. data/lib/rubik/repl/commands/workspace.rb +60 -150
  79. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  80. data/lib/rubik/repl/config_wiring.rb +3 -3
  81. data/lib/rubik/repl/hooks.rb +2 -1
  82. data/lib/rubik/repl/input_execution.rb +158 -76
  83. data/lib/rubik/repl/input_loop.rb +3 -2
  84. data/lib/rubik/repl/lifecycle.rb +82 -204
  85. data/lib/rubik/repl/notice_router.rb +319 -0
  86. data/lib/rubik/repl/paste_support.rb +3 -1
  87. data/lib/rubik/repl/presentation.rb +5 -3
  88. data/lib/rubik/repl/pruner/gate.rb +3 -1
  89. data/lib/rubik/repl/pruner/harness.rb +2 -1
  90. data/lib/rubik/repl/shell.rb +4 -3
  91. data/lib/rubik/repl/turn_recorder.rb +6 -5
  92. data/lib/rubik/runtime/discovery.rb +3 -2
  93. data/lib/rubik/runtime/loop_service.rb +4 -3
  94. data/lib/rubik/runtime/manifest_store.rb +124 -0
  95. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  96. data/lib/rubik/runtime/overlay_storage.rb +269 -272
  97. data/lib/rubik/runtime/task_manager.rb +71 -27
  98. data/lib/rubik/runtime.rb +1 -0
  99. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  100. data/lib/rubik/sandbox/runner.rb +16 -15
  101. data/lib/rubik/security/allowlist.rb +167 -0
  102. data/lib/rubik/security/audit_log.rb +72 -0
  103. data/lib/rubik/security/classifier/classifier.rb +8 -0
  104. data/lib/rubik/security/command_gate.rb +591 -0
  105. data/lib/rubik/security/guard.rb +94 -1077
  106. data/lib/rubik/security/path_policy.rb +117 -0
  107. data/lib/rubik/security/secret_store.rb +463 -0
  108. data/lib/rubik/security/synthesis_gate.rb +297 -0
  109. data/lib/rubik/security.rb +5 -0
  110. data/lib/rubik/session/manager.rb +7 -1
  111. data/lib/rubik/skills/manager.rb +2 -3
  112. data/lib/rubik/storage/ranking.rb +113 -0
  113. data/lib/rubik/storage/search.rb +49 -0
  114. data/lib/rubik/storage/store.rb +15 -112
  115. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  116. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  117. data/lib/rubik/tools/base.rb +22 -0
  118. data/lib/rubik/tools/builtins/files.rb +3 -15
  119. data/lib/rubik/tools/builtins/grep.rb +3 -9
  120. data/lib/rubik/tools/builtins/lifecycle.rb +96 -92
  121. data/lib/rubik/tools/builtins/synthesis.rb +3 -0
  122. data/lib/rubik/tools/lifecycle_rollbacks.rb +100 -0
  123. data/lib/rubik/tools/native_search.rb +2 -1
  124. data/lib/rubik/tools/truncator.rb +73 -36
  125. data/lib/rubik/ui/banner.rb +4 -3
  126. data/lib/rubik/ui/spinner.rb +3 -1
  127. data/lib/rubik/ui/statusline.rb +6 -5
  128. data/lib/rubik/version.rb +1 -1
  129. data/lib/rubik.rb +1 -2
  130. metadata +23 -1
@@ -3,7 +3,9 @@
3
3
  require "open3"
4
4
  require "monitor"
5
5
  require "time"
6
+ require_relative "../log"
6
7
  require_relative "../platform"
8
+ require_relative "../security/guard" unless defined?(Rubik::Security::Guard)
7
9
 
8
10
  module Rubik
9
11
  module Runtime
@@ -90,7 +92,13 @@ module Rubik
90
92
 
91
93
  @at_exit_installed = true
92
94
  at_exit do
93
- @instances.each(&:kill_all)
95
+ # Error-isolated sweep: one manager's kill_all raising must not
96
+ # leave the remaining managers uncleaned at shutdown.
97
+ @instances.each do |mgr|
98
+ mgr.kill_all
99
+ rescue StandardError => e
100
+ warn "[TaskManager] at_exit kill_all failed: #{e.class}: #{e.message}"
101
+ end
94
102
  end
95
103
  end
96
104
 
@@ -98,7 +106,11 @@ module Rubik
98
106
  @tasks = {}
99
107
  @task_counter = 0
100
108
  @monitor = Monitor.new
101
- @guard = guard
109
+ # Fail-closed fallback (house pattern): a bare construction must never
110
+ # leave the popen3 sink unguarded — a fresh Guard still blocks
111
+ # dangerous/unclassifiable commands, it only lacks the operator
112
+ # allowlist of the injected session guard.
113
+ @guard = guard || Rubik::Security::Guard.new
102
114
  @context = context
103
115
  @root_dir = File.expand_path(root_dir)
104
116
  @max_buffer_lines = max_buffer_lines
@@ -116,7 +128,7 @@ module Rubik
116
128
  cmd_str = command.to_s.strip
117
129
  raise ArgumentError, "Command cannot be empty" if cmd_str.empty?
118
130
 
119
- @guard&.verify_command_safety!(cmd_str)
131
+ @guard.verify_command_safety!(cmd_str)
120
132
 
121
133
  # Each task carries its OWN child context, never the shared runtime
122
134
  # root: Kernel::Init#reap_dead_units! disposes a dead unit's context
@@ -135,28 +147,49 @@ module Rubik
135
147
  end
136
148
 
137
149
  ring_buf = RingBuffer.new(@max_buffer_lines)
150
+ # Deliberately not single-homed on Platform.popen_capture (issue
151
+ # #444): that core is the synchronous drain-to-string capture shape
152
+ # (Timeout-wrapped, stdin closed immediately, whole-output strings).
153
+ # This spawn is the async/interactive shape — stdin stays open for
154
+ # send_input, the readers stream chomped lines into the per-task
155
+ # RingBuffer, and completion is watched by a dedicated thread with
156
+ # no Timeout — so parameterizing the sink alone cannot unify them.
138
157
  begin
139
158
  stdin, stdout, stderr, wait_thr = Open3.popen3(cmd_str, chdir: chdir)
140
159
  rescue StandardError => e
141
160
  rollback_failed_start(target_ctx, nil, e)
142
161
  raise e
143
162
  end
144
- stdin.binmode if stdin.respond_to?(:binmode)
145
- stdin.sync = true if stdin.respond_to?(:sync=)
146
-
147
- task = Task.new(
148
- id: task_id,
149
- command: cmd_str,
150
- pid: wait_thr.pid,
151
- started_at: Time.now,
152
- ended_at: nil,
153
- status: :running,
154
- exit_code: nil,
155
- ring_buffer: ring_buf,
156
- stdin_io: stdin,
157
- wait_thread: wait_thr,
158
- collector_threads: []
159
- )
163
+ # The spawn succeeded but the task is NOT yet registered, so nothing
164
+ # (kill, kill_all, at_exit) can reach the child yet. Any failure in
165
+ # this window must kill the spawned process directly before rolling
166
+ # back the context, or the child leaks as an unmanaged orphan.
167
+ begin
168
+ stdin.binmode if stdin.respond_to?(:binmode)
169
+ stdin.sync = true if stdin.respond_to?(:sync=)
170
+
171
+ task = Task.new(
172
+ id: task_id,
173
+ command: cmd_str,
174
+ pid: wait_thr.pid,
175
+ started_at: Time.now,
176
+ ended_at: nil,
177
+ status: :running,
178
+ exit_code: nil,
179
+ ring_buffer: ring_buf,
180
+ stdin_io: stdin,
181
+ wait_thread: wait_thr,
182
+ collector_threads: []
183
+ )
184
+ rescue StandardError => e
185
+ begin
186
+ Process.kill("KILL", wait_thr.pid)
187
+ rescue StandardError
188
+ nil
189
+ end
190
+ rollback_failed_start(target_ctx, nil, e)
191
+ raise e
192
+ end
160
193
 
161
194
  task.collector_threads = []
162
195
 
@@ -236,19 +269,30 @@ module Rubik
236
269
  task&.ring_buffer&.tail(tail)
237
270
  end
238
271
 
272
+ # Resolve the stdin pipe under the monitor, but write OUTSIDE it: a
273
+ # pipe write blocks once the OS pipe buffer fills, and blocking while
274
+ # holding @monitor would deadlock kill/status/logs/kill_all and the
275
+ # at_exit sweep for the whole manager. The deadline-bounded write
276
+ # (Rubik::Platform.write_until, single-homed with the other process
277
+ # IO plumbing) converts a never-reading child into a false return
278
+ # instead of a hang.
279
+ SEND_INPUT_TIMEOUT = 5.0
280
+
239
281
  def send_input(task_id, input)
240
- @monitor.synchronize do
282
+ io = @monitor.synchronize do
241
283
  task = @tasks[task_id.to_s]
242
284
  return false unless task && task.status == :running && task.stdin_io && !task.stdin_io.closed?
243
285
 
244
- text = input.to_s
245
- text += "\n" unless text.end_with?("\n")
246
- task.stdin_io.write(text)
247
- task.stdin_io.flush
248
- true
249
- rescue IOError, Errno::EPIPE
250
- false
286
+ task.stdin_io
251
287
  end
288
+
289
+ text = input.to_s
290
+ text += "\n" unless text.end_with?("\n")
291
+ Rubik::Platform.write_until(io, text, timeout: SEND_INPUT_TIMEOUT)
292
+ io.flush
293
+ true
294
+ rescue IOError, Errno::EPIPE, Errno::EINTR
295
+ false
252
296
  end
253
297
 
254
298
  def kill(task_id)
data/lib/rubik/runtime.rb CHANGED
@@ -7,6 +7,7 @@ require_relative "runtime/fiber"
7
7
  require_relative "runtime/manager"
8
8
  require_relative "runtime/service_definition"
9
9
  require_relative "runtime/service_registration"
10
+ require_relative "runtime/manifest_store"
10
11
  require_relative "runtime/overlay_storage"
11
12
  require_relative "runtime/discovery"
12
13
  require_relative "runtime/diagnostic_engine"
@@ -2,6 +2,7 @@
2
2
 
3
3
  require_relative "base"
4
4
  require_relative "../../platform"
5
+ require_relative "../../log"
5
6
  require "open3"
6
7
  require "timeout"
7
8
 
@@ -48,7 +49,10 @@ module Rubik
48
49
  error_message: "Docker sandbox error"
49
50
  )
50
51
  ensure
51
- system("docker", "rm", "-f", container_name, out: File::NULL, err: File::NULL)
52
+ # Best-effort cleanup, but a failed `docker rm -f` leaves an
53
+ # orphaned container — check the result and leave a trace.
54
+ removed = system("docker", "rm", "-f", container_name, out: File::NULL, err: File::NULL)
55
+ Rubik::Log.warn(:sandbox, "docker container '#{container_name}' could not be removed") unless removed
52
56
  end
53
57
 
54
58
  {
@@ -4,6 +4,7 @@ require_relative "driver"
4
4
  require_relative "driver/process"
5
5
  require_relative "../security/errors"
6
6
  require_relative "../platform"
7
+ require_relative "../storage/layout"
7
8
 
8
9
  module Rubik
9
10
  module Sandbox
@@ -21,10 +22,10 @@ module Rubik
21
22
  # re-verification, where an empty-allowlist guard would silently
22
23
  # re-block commands the operator allowlisted.
23
24
  @guard = guard
24
- @allow_network = allow_network || @config&.fetch("sandbox.allow_network", false) || false
25
+ @allow_network = allow_network || Rubik::Storage::Layout.config_get(@config, "sandbox.allow_network", false) || false
25
26
  @allowed_external_dirs = (
26
27
  Array(allowed_external_dirs) +
27
- Array(@config&.fetch("workspace.allowed_external_dirs", []))
28
+ Array(Rubik::Storage::Layout.config_get(@config, "workspace.allowed_external_dirs", []))
28
29
  ).map { |d| File.expand_path(d.to_s, @root_dir) }.uniq
29
30
  # Baseline captured BEFORE the first reconfigure: entries from
30
31
  # construction arguments plus the config's current value. Dirs added
@@ -63,15 +64,15 @@ module Rubik
63
64
 
64
65
  def sandbox_enabled?
65
66
  return true if @preferred_driver && !@preferred_driver.is_a?(String) && !@preferred_driver.is_a?(Symbol)
66
- return false if @config&.fetch("sandbox.driver", nil).to_s.downcase.then { |d| ["process", "none"].include?(d) }
67
+ return false if Rubik::Storage::Layout.config_get(@config, "sandbox.driver", nil).to_s.downcase.then { |d| ["process", "none"].include?(d) }
67
68
  return false if @preferred_driver.to_s.downcase.then { |d| ["process", "none"].include?(d) }
68
69
 
69
- val = @config&.fetch("sandbox.enabled", false)
70
+ val = Rubik::Storage::Layout.config_get(@config, "sandbox.enabled", false)
70
71
  val == true || val.to_s.downcase == "true"
71
72
  end
72
73
 
73
74
  def reconfigure!
74
- @allow_network = @config.fetch("sandbox.allow_network", @allow_network) if @config
75
+ @allow_network = Rubik::Storage::Layout.config_get(@config, "sandbox.allow_network", @allow_network)
75
76
  if @config && @allowed_dirs_config_touched
76
77
  # Config authoritative (user has edited the key at some scope):
77
78
  # recompute config-sourced entries from scratch so REMOVING a dir
@@ -83,7 +84,7 @@ module Rubik
83
84
  # A malformed (non-Array) value must fail CLOSED: treating it as an
84
85
  # empty config list and warning, rather than silently keeping the
85
86
  # previously-merged union (which would leave stale dirs allowed).
86
- raw_allowed = @config.fetch("workspace.allowed_external_dirs", [])
87
+ raw_allowed = Rubik::Storage::Layout.config_get(@config, "workspace.allowed_external_dirs", [])
87
88
  unless raw_allowed.is_a?(Array)
88
89
  warn "[SANDBOX] workspace.allowed_external_dirs must be an Array (got #{raw_allowed.class}); " \
89
90
  "treating as empty — the config is authoritative, so stale dirs are revoked."
@@ -101,7 +102,7 @@ module Rubik
101
102
 
102
103
  driver_opts = {
103
104
  image: @config&.fetch("sandbox.image", "rubik-sandbox:latest"),
104
- shell: @config&.fetch("sandbox.shell", "auto") || "auto",
105
+ shell: Rubik::Storage::Layout.config_get(@config, "sandbox.shell", "auto"),
105
106
  allowed_dirs: allowed_paths,
106
107
  guard: @guard
107
108
  }
@@ -111,7 +112,7 @@ module Rubik
111
112
  @driver = if @preferred_driver && !@preferred_driver.is_a?(String) && !@preferred_driver.is_a?(Symbol)
112
113
  @preferred_driver
113
114
  elsif @sandbox_enabled
114
- driver_to_use = @preferred_driver || @config&.fetch("sandbox.driver", nil) || "auto"
115
+ driver_to_use = @preferred_driver || Rubik::Storage::Layout.config_get(@config, "sandbox.driver", nil) || "auto"
115
116
  Driver.best_available(driver_to_use, driver_opts)
116
117
  end
117
118
  end
@@ -119,7 +120,7 @@ module Rubik
119
120
  def allowed_paths
120
121
  roots = [@root_dir]
121
122
  if @config
122
- extra_roots = Array(@config.fetch("workspace.additional_roots", [])).map { |r| File.expand_path(r.to_s, @root_dir) }
123
+ extra_roots = Array(Rubik::Storage::Layout.config_get(@config, "workspace.additional_roots", [])).map { |r| File.expand_path(r.to_s, @root_dir) }
123
124
  roots.concat(extra_roots)
124
125
  end
125
126
  roots.concat(@allowed_external_dirs)
@@ -157,7 +158,7 @@ module Rubik
157
158
 
158
159
  def allow_network?
159
160
  if @config
160
- cfg_val = @config.fetch("sandbox.allow_network", nil)
161
+ cfg_val = Rubik::Storage::Layout.config_get(@config, "sandbox.allow_network", nil)
161
162
  return true if cfg_val == true || cfg_val.to_s.downcase == "true"
162
163
  return false if cfg_val == false || cfg_val.to_s.downcase == "false"
163
164
 
@@ -179,15 +180,15 @@ module Rubik
179
180
 
180
181
  parsed_timeout = timeout&.to_i
181
182
  effective_timeout = (parsed_timeout&.positive? ? parsed_timeout : nil) ||
182
- (@config && @config.fetch("sandbox.timeout_seconds", 15).to_i) || 15
183
+ Rubik::Storage::Layout.config_get(@config, "sandbox.timeout_seconds", 15).to_i
183
184
  effective_timeout = 15 if effective_timeout <= 0
184
- mem_limit = @config&.fetch("sandbox.memory_limit_mb", 512) || 512
185
- cpus = @config&.fetch("sandbox.cpus", "1.0") || "1.0"
185
+ mem_limit = Rubik::Storage::Layout.config_get(@config, "sandbox.memory_limit_mb", 512)
186
+ cpus = Rubik::Storage::Layout.config_get(@config, "sandbox.cpus", "1.0")
186
187
 
187
188
  active_driver = if sandbox_enabled? && @driver
188
189
  @driver
189
190
  else
190
- @host_driver || Driver::ProcessDriver.new(shell: @config&.fetch("sandbox.shell", "auto") || "auto",
191
+ @host_driver || Driver::ProcessDriver.new(shell: Rubik::Storage::Layout.config_get(@config, "sandbox.shell", "auto"),
191
192
  guard: @guard)
192
193
  end
193
194
 
@@ -211,7 +212,7 @@ module Rubik
211
212
  end
212
213
 
213
214
  def disclose_isolation?
214
- @config.respond_to?(:fetch) ? @config.fetch("sandbox.isolation_note", true) != false : true
215
+ Rubik::Storage::Layout.config_get(@config, "sandbox.isolation_note", true) != false
215
216
  end
216
217
 
217
218
  def isolation_disclosure
@@ -0,0 +1,167 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "shellwords"
4
+ require_relative "../platform"
5
+ require_relative "classifier"
6
+
7
+ module Rubik
8
+ module Security
9
+ # Operator-controlled command allowlist (Plan: komut-allowlist-güvenlik-kapısı),
10
+ # split out of Guard (#403) as the allowlist leaf: state (@command_allowlist),
11
+ # the AST gate, the raw Shellwords gate, and every token-prefix matcher.
12
+ # Entries are token-prefixes: "node" allows every node invocation (broad);
13
+ # "node .gitnexus/run.cjs" allows only that script (narrow — preferred).
14
+ # Applied AFTER classifier verdict, BEFORE the raise, and the catastrophic
15
+ # fallback regex still runs afterwards (defense-in-depth is never skipped).
16
+ class Allowlist
17
+ # Shell metacharacters that make a raw (AST-less) token-prefix allowlist
18
+ # match dishonest: they can join, redirect, substitute, or line-split
19
+ # the string, so "the first tokens match" would not mean "the whole
20
+ # simple command matches". The classifier-crash rescue only accepts a
21
+ # single simple command; anything else fails closed.
22
+ RAW_ALLOWLIST_UNSAFE_PATTERN = /[;&|<>`$(){}\[\]\\\n\r]/
23
+
24
+ def initialize(entries = [])
25
+ @command_allowlist = normalize_allowlist(entries)
26
+ end
27
+
28
+ def command_allowlist
29
+ @command_allowlist.dup
30
+ end
31
+
32
+ def allowed_commands=(entries)
33
+ @command_allowlist = normalize_allowlist(entries)
34
+ end
35
+ alias set_allowed_commands allowed_commands=
36
+
37
+ def command_allowlisted?(ast, cmd_str: nil)
38
+ _ = cmd_str
39
+ return false if @command_allowlist.empty?
40
+ return false unless ast.respond_to?(:commands)
41
+
42
+ ast_commands = ast.commands.to_a
43
+ return false if ast_commands.empty?
44
+
45
+ # EVERY dangerous segment (recursively incl. pipeline inner commands)
46
+ # must match an entry — a single allowlisted prefix cannot rescue
47
+ # `allowlisted-cmd && rm -rf /` chains.
48
+ ast_commands.all? { |c| command_matches_allowlist?(c) }
49
+ end
50
+
51
+ # Token-prefix allowlist check for an input whose AST does not exist
52
+ # (classifier crashed). Only a single simple command qualifies: with
53
+ # shell metacharacters present the string may hold several segments
54
+ # and the gate's "every segment must match" contract cannot be
55
+ # honored — fail closed instead of over-promising the prefix match.
56
+ # Quoting is handled by Shellwords; an unparseable string (unbalanced
57
+ # quote) fails closed.
58
+ def command_allowlisted_raw?(cmd_str)
59
+ return false if @command_allowlist.empty?
60
+ return false if cmd_str.match?(RAW_ALLOWLIST_UNSAFE_PATTERN)
61
+
62
+ tokens = nil
63
+ begin
64
+ tokens = Shellwords.split(cmd_str)
65
+ rescue ArgumentError
66
+ return false
67
+ end
68
+ return false if tokens.empty?
69
+ return false if Rubik::Security::Classifier::Engine.builtin_dangerous?(tokens[0])
70
+
71
+ allowlist_match_argv?(tokens)
72
+ end
73
+
74
+ private
75
+
76
+ def normalize_allowlist(entries)
77
+ Array(entries).filter_map do |e|
78
+ tokens = e.to_s.strip.split(/\s+/).reject(&:empty?)
79
+ tokens unless tokens.empty?
80
+ end
81
+ end
82
+
83
+ def canonical_binary_path(bin)
84
+ return nil if bin.nil? || bin.to_s.empty?
85
+
86
+ str = bin.to_s
87
+ if str.include?("/") || str.include?("\\") || File.exist?(str)
88
+ Rubik::Platform.normalize_path(File.expand_path(str))
89
+ else
90
+ resolved = Rubik::Platform.which(str)
91
+ resolved ? Rubik::Platform.normalize_path(resolved) : nil
92
+ end
93
+ end
94
+
95
+ def binary_allowlist_match?(arg, token)
96
+ return true if arg == token
97
+ # Windows exe-alias fast path (#103): on a windows host "node.exe"
98
+ # IS the allowlisted "node" — a lexical alias, no filesystem probe.
99
+ # The canonical-path probe below resolves through Platform.which +
100
+ # File.file?, a second host seam the windows? stub cannot cover (a
101
+ # linux host has no node.exe on disk, so the probe fails and the
102
+ # allowlist would dead-close). On a posix host the alias is FALSE:
103
+ # node.exe is a different binary than node there.
104
+ return true if windows_executable_alias?(arg, token)
105
+
106
+ c_arg = canonical_binary_path(arg)
107
+ c_token = canonical_binary_path(token)
108
+
109
+ return true if c_arg && c_token && Rubik::Platform.path_equal?(c_arg, c_token)
110
+
111
+ false
112
+ end
113
+
114
+ # True when arg carries an executable extension from PATHEXT and its
115
+ # stem equals the token (case-insensitive — windows path semantics).
116
+ # Bare stems only: a path-form arg ("C:/x/node.exe") keeps going
117
+ # through the canonical-path probe, which resolves both sides.
118
+ def windows_executable_alias?(arg, token)
119
+ return false unless Rubik::Platform.windows?
120
+
121
+ ext = ::File.extname(arg)
122
+ return false if ext.empty? || !Rubik::Platform.pathext.include?(ext.downcase)
123
+
124
+ arg.delete_suffix(ext).casecmp?(token)
125
+ end
126
+
127
+ def command_matches_allowlist?(result)
128
+ # Missing argv (e.g. empty invocation) can never be allowlisted.
129
+ argv = result.respond_to?(:argv) ? result.argv : nil
130
+ return false if argv.nil? || argv.empty?
131
+
132
+ # Dangerous shell builtins (`source`, `.`) are never rescuable by
133
+ # allowlist: they execute arbitrary file content by design.
134
+ return false if Rubik::Security::Classifier::Engine.builtin_dangerous?(argv[0])
135
+
136
+ # W6: If this command wraps inner commands, EVERY inner command must also match allowlist
137
+ if result.respond_to?(:inner_commands) && result.inner_commands && !result.inner_commands.empty? && !result.inner_commands.all? do |inner|
138
+ command_matches_allowlist?(inner)
139
+ end
140
+ return false
141
+ end
142
+
143
+ allowlist_match_argv?(argv)
144
+ end
145
+
146
+ # The single token-prefix matching home shared by the AST path
147
+ # (#command_matches_allowlist?) and the raw Shellwords path
148
+ # (#command_allowlisted_raw?) — two callers, one contract: an entry
149
+ # matches when its tokens are a prefix of argv (position 0 through the
150
+ # binary canonical-path probe, the rest by equality).
151
+ def allowlist_match_argv?(argv)
152
+ @command_allowlist.any? do |entry|
153
+ next false if entry.length > argv.length
154
+
155
+ entry.each_with_index.all? do |token, i|
156
+ arg = argv[i]
157
+ if i.zero?
158
+ binary_allowlist_match?(arg, token)
159
+ else
160
+ arg == token
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end
166
+ end
167
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require "fileutils"
6
+ require_relative "../platform"
7
+ require_relative "redactor"
8
+
9
+ module Rubik
10
+ module Security
11
+ # The shared audit leaf of the Guard split (#403): owns the audit
12
+ # destination (@audit_log_path), secret masking, and the JSONL append.
13
+ # Every other security module (PathPolicy, CommandGate, SynthesisGate)
14
+ # receives an instance of this class and routes its log_audit calls
15
+ # through it — the audit trail has exactly one home.
16
+ class AuditLog
17
+ MASK_PATTERNS = Rubik::Security::Redactor::PATTERNS
18
+
19
+ attr_reader :audit_log_path
20
+
21
+ # Default audit location, resolved at call time (not a load-time
22
+ # constant) so Platform.home_dir stubs in tests and runtime HOME
23
+ # changes are honored. Single source shared by the constructor
24
+ # default and Guard.for_config.
25
+ def self.default_audit_log_path
26
+ File.join(Rubik::Platform.home_dir, ".rubik", "audit.log")
27
+ end
28
+
29
+ def initialize(audit_log_path = AuditLog.default_audit_log_path)
30
+ @audit_log_path = audit_log_path
31
+ end
32
+
33
+ # Live-reconfigurable audit destination (ConfigWiring applies config
34
+ # changes in place — zero restart). Same blank-means-disabled semantics
35
+ # as for_config; non-string values pass through and surface loudly in
36
+ # log_audit's unconditional warn.
37
+ def audit_log_path=(val)
38
+ @audit_log_path = val.is_a?(String) && val.strip.empty? ? nil : val
39
+ end
40
+
41
+ def mask_text(text)
42
+ Rubik::Security::Redactor.redact(text)
43
+ end
44
+
45
+ def log_audit(action, details = {})
46
+ return if @audit_log_path.nil? || @audit_log_path.to_s.strip.empty?
47
+
48
+ # Nil-safety: a nil details hash (or nil value) must never crash the
49
+ # command path — audit failure is already swallowed below.
50
+ masked_details = (details || {}).transform_values { |v| v.nil? ? "" : mask_text(v.to_s) }
51
+
52
+ entry = {
53
+ ts: Time.now.iso8601,
54
+ action: action,
55
+ details: masked_details
56
+ }
57
+
58
+ dir = File.dirname(@audit_log_path)
59
+ FileUtils.mkdir_p(dir) unless File.directory?(dir)
60
+
61
+ File.open(@audit_log_path, "a") do |f|
62
+ f.puts(JSON.dump(entry))
63
+ end
64
+ rescue StandardError => e
65
+ # Unconditional: an audit trail failing silently is indistinguishable
66
+ # from an operator's intentional disable — the one warn in the guard
67
+ # that must not hide behind RUBIK_DEBUG.
68
+ warn "[WARN] Failed to write audit log #{@audit_log_path}: #{e.message}"
69
+ end
70
+ end
71
+ end
72
+ end
@@ -37,6 +37,14 @@ module Rubik
37
37
  new(database: database, shell: shell).classify(expression)
38
38
  end
39
39
 
40
+ # Public interface predicate over the Matcher's builtin vocabulary.
41
+ # External gates (e.g. Guard's allowlist) depend on this instead of
42
+ # reaching into Matcher::BUILTIN_DANGEROUS_CMDS — a non-interface
43
+ # constant of another module.
44
+ def self.builtin_dangerous?(binary)
45
+ Matcher::BUILTIN_DANGEROUS_CMDS.include?(binary.to_s)
46
+ end
47
+
40
48
  def initialize(database: nil, shell: nil)
41
49
  @database = database || self.class.default_database
42
50
  @shell = shell