rubik 0.15.3 → 0.15.4

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 (58) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +45 -3
  3. data/lib/rubik/adapter/node.rb +3 -2
  4. data/lib/rubik/ast/extractor.rb +1 -1
  5. data/lib/rubik/ast/graph_extensions.rb +3 -1
  6. data/lib/rubik/ast/treesitter_extractor.rb +1 -1
  7. data/lib/rubik/buffer/manager.rb +5 -3
  8. data/lib/rubik/buffer/snapshot.rb +3 -2
  9. data/lib/rubik/concurrency/errors.rb +3 -1
  10. data/lib/rubik/config/coercion.rb +26 -0
  11. data/lib/rubik/config/env_loader.rb +1 -2
  12. data/lib/rubik/config/scoped.rb +5 -20
  13. data/lib/rubik/config/secret_policy.rb +3 -2
  14. data/lib/rubik/config/store.rb +5 -2
  15. data/lib/rubik/config.rb +7 -13
  16. data/lib/rubik/connect/models_dev.rb +13 -11
  17. data/lib/rubik/errors.rb +5 -4
  18. data/lib/rubik/event_bus.rb +0 -1
  19. data/lib/rubik/llm/client.rb +2 -1
  20. data/lib/rubik/llm/registry.rb +1 -1
  21. data/lib/rubik/lsp/client.rb +0 -9
  22. data/lib/rubik/lsp/transport.rb +2 -1
  23. data/lib/rubik/mcp/boot_run.rb +15 -14
  24. data/lib/rubik/mcp/errors.rb +3 -1
  25. data/lib/rubik/mcp/manager.rb +6 -6
  26. data/lib/rubik/orchestrator/auto_apply.rb +2 -1
  27. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +4 -1
  28. data/lib/rubik/orchestrator/subagent/profile_snapshot.rb +4 -2
  29. data/lib/rubik/orchestrator/subagent/supervisor.rb +23 -8
  30. data/lib/rubik/orchestrator/tool_circuit_breaker.rb +3 -1
  31. data/lib/rubik/orchestrator/tool_timeout.rb +3 -2
  32. data/lib/rubik/platform/process.rb +104 -82
  33. data/lib/rubik/plugin/manager.rb +0 -1
  34. data/lib/rubik/plugin/package_inventory.rb +3 -1
  35. data/lib/rubik/repl/hooks.rb +0 -1
  36. data/lib/rubik/repl/interrupt_handler.rb +5 -1
  37. data/lib/rubik/repl/lifecycle.rb +1 -1
  38. data/lib/rubik/repl/terminal_guard.rb +0 -8
  39. data/lib/rubik/runtime/context.rb +3 -2
  40. data/lib/rubik/runtime/overlay_storage.rb +3 -3
  41. data/lib/rubik/runtime/repair_probe.rb +50 -21
  42. data/lib/rubik/runtime/task_manager.rb +81 -82
  43. data/lib/rubik/sandbox/runner.rb +1 -1
  44. data/lib/rubik/security/audit_log.rb +1 -1
  45. data/lib/rubik/security/classifier/matcher/options.rb +7 -1
  46. data/lib/rubik/security/classifier/matcher.rb +8 -3
  47. data/lib/rubik/security/classifier/models.rb +8 -0
  48. data/lib/rubik/security/command_gate.rb +105 -77
  49. data/lib/rubik/security/errors.rb +3 -1
  50. data/lib/rubik/security/secret_store.rb +12 -10
  51. data/lib/rubik/session/recorder.rb +11 -6
  52. data/lib/rubik/skills/frontmatter.rb +3 -1
  53. data/lib/rubik/storage/transcript_indexer.rb +9 -3
  54. data/lib/rubik/ui/capability.rb +4 -8
  55. data/lib/rubik/ui/io_probe.rb +24 -0
  56. data/lib/rubik/ui/spinner.rb +3 -2
  57. data/lib/rubik/version.rb +1 -1
  58. metadata +3 -1
@@ -144,12 +144,7 @@ module Rubik
144
144
  parent_ctx = ctx || @context
145
145
  target_ctx = parent_ctx.is_a?(Rubik::Runtime::Context) ? parent_ctx.extend : parent_ctx
146
146
 
147
- task_id = nil
148
- @monitor.synchronize do
149
- @task_counter += 1
150
- task_id = "task-#{@task_counter}"
151
- end
152
-
147
+ task_id = next_task_id
153
148
  ring_buf = RingBuffer.new(@max_buffer_lines)
154
149
  # Deliberately not single-homed on Platform.popen_capture (issue
155
150
  # #444): that core is the synchronous drain-to-string capture shape
@@ -157,44 +152,8 @@ module Rubik
157
152
  # This spawn is the async/interactive shape — stdin stays open for
158
153
  # send_input, readers stream chomped lines into the per-task
159
154
  # RingBuffer, completion is watched by a dedicated thread.
160
- begin
161
- stdin, stdout, stderr, wait_thr = Open3.popen3(Rubik::Platform.credential_free_env, cmd_str, chdir: chdir)
162
- rescue StandardError => e
163
- rollback_failed_start(target_ctx, nil, e)
164
- raise e
165
- end
166
- # The spawn succeeded but the task is NOT yet registered, so nothing
167
- # (kill, kill_all, at_exit) can reach the child yet. Any failure in
168
- # this window must kill the spawned process directly before rolling
169
- # back the context, or the child leaks as an unmanaged orphan.
170
- begin
171
- stdin.binmode if stdin.respond_to?(:binmode)
172
- stdin.sync = true if stdin.respond_to?(:sync=)
173
-
174
- task = Task.new(
175
- id: task_id,
176
- command: cmd_str,
177
- pid: wait_thr.pid,
178
- started_at: Time.now,
179
- ended_at: nil,
180
- status: :running,
181
- exit_code: nil,
182
- ring_buffer: ring_buf,
183
- stdin_io: stdin,
184
- wait_thread: wait_thr,
185
- collector_threads: []
186
- )
187
- rescue StandardError => e
188
- begin
189
- Process.kill("KILL", wait_thr.pid)
190
- rescue StandardError
191
- nil
192
- end
193
- rollback_failed_start(target_ctx, nil, e)
194
- raise e
195
- end
196
-
197
- task.collector_threads = []
155
+ stdin, stdout, stderr, wait_thr = open_task_pipes(cmd_str, chdir, target_ctx)
156
+ task = build_running_task(task_id, cmd_str, stdin, wait_thr, ring_buf, target_ctx)
198
157
 
199
158
  # Register before the wiring below can fail: once tracked, the task
200
159
  # stays reachable by kill/kill_all/at_exit and by the rollback
@@ -205,45 +164,10 @@ module Rubik
205
164
  @monitor.synchronize { @tasks[task.id] = task }
206
165
 
207
166
  begin
208
- t_out = Thread.new do
209
- stdout.each_line do |line|
210
- ring_buf.push(line.chomp)
211
- end
212
- rescue IOError
213
- nil
214
- ensure
215
- begin; stdout.close unless stdout.closed?; rescue IOError; nil; end
216
- end
217
-
218
- t_err = Thread.new do
219
- stderr.each_line do |line|
220
- ring_buf.push(line.chomp)
221
- end
222
- rescue IOError
223
- nil
224
- ensure
225
- begin; stderr.close unless stderr.closed?; rescue IOError; nil; end
226
- end
227
-
228
- task.collector_threads = [t_out, t_err]
229
-
230
- Thread.new do
231
- status = wait_thr.value
232
- @monitor.synchronize do
233
- if task.status == :running
234
- task.exit_code = status.exitstatus
235
- task.status = status.success? ? :completed : :failed
236
- task.ended_at = Time.now
237
- end
238
- end
239
- effective_init = @init || (target_ctx.respond_to?(:get) && Rubik::Coeffects.get(target_ctx, Rubik::Coeffects::INIT))
240
- effective_init&.get(task.id)&.sync_state!
241
- begin; stdin.close unless stdin.closed?; rescue IOError; nil; end
242
- end
243
-
167
+ task.collector_threads = spawn_collector_threads(stdout, stderr, ring_buf)
168
+ spawn_completion_watcher(task, stdin, wait_thr, target_ctx)
244
169
  target_ctx.on_dispose { kill(task.id) } if target_ctx.respond_to?(:on_dispose)
245
-
246
- effective_init = @init || (target_ctx.respond_to?(:get) && Rubik::Coeffects.get(target_ctx, Rubik::Coeffects::INIT))
170
+ effective_init = resolve_init(target_ctx)
247
171
  effective_init&.register(Rubik::Kernel::ProcessUnit.new(task, task_manager: self, context: target_ctx))
248
172
  rescue StandardError => e
249
173
  rollback_failed_start(target_ctx, task.id, e)
@@ -326,6 +250,81 @@ module Rubik
326
250
 
327
251
  private
328
252
 
253
+ def next_task_id
254
+ id = nil
255
+ @monitor.synchronize do
256
+ @task_counter += 1
257
+ id = "task-#{@task_counter}"
258
+ end
259
+ id
260
+ end
261
+
262
+ # Open the child's stdio pipes; a spawn failure rolls back the fresh
263
+ # per-task context (nothing was spawned, so there is no process to
264
+ # kill) and re-raises the original error.
265
+ def open_task_pipes(cmd_str, chdir, target_ctx)
266
+ stdin, stdout, stderr, wait_thr = Open3.popen3(Rubik::Platform.credential_free_env, cmd_str, chdir: chdir)
267
+ [stdin, stdout, stderr, wait_thr]
268
+ rescue StandardError => e
269
+ rollback_failed_start(target_ctx, nil, e)
270
+ raise e
271
+ end
272
+
273
+ # The spawn succeeded but the task is NOT yet registered, so nothing
274
+ # (kill, kill_all, at_exit) can reach the child yet. Any failure in
275
+ # this window must kill the spawned process directly before rolling
276
+ # back the context, or the child leaks as an unmanaged orphan.
277
+ def build_running_task(task_id, cmd_str, stdin, wait_thr, ring_buf, target_ctx)
278
+ stdin.binmode if stdin.respond_to?(:binmode)
279
+ stdin.sync = true if stdin.respond_to?(:sync=)
280
+ Task.new(
281
+ id: task_id, command: cmd_str, pid: wait_thr.pid, started_at: Time.now,
282
+ ended_at: nil, status: :running, exit_code: nil, ring_buffer: ring_buf,
283
+ stdin_io: stdin, wait_thread: wait_thr, collector_threads: []
284
+ )
285
+ rescue StandardError => e
286
+ begin; Process.kill("KILL", wait_thr.pid); rescue StandardError; nil; end
287
+ rollback_failed_start(target_ctx, nil, e)
288
+ raise e
289
+ end
290
+
291
+ def spawn_collector_threads(stdout, stderr, ring_buf)
292
+ [collector_thread(stdout, ring_buf), collector_thread(stderr, ring_buf)]
293
+ end
294
+
295
+ def collector_thread(io, ring_buf)
296
+ Thread.new do
297
+ io.each_line do |line|
298
+ ring_buf.push(line.chomp)
299
+ end
300
+ rescue IOError
301
+ nil
302
+ ensure
303
+ begin; io.close unless io.closed?; rescue IOError; nil; end
304
+ end
305
+ end
306
+
307
+ # Watch the child to completion, finalize its status under the
308
+ # monitor, sync the kernel unit state, and close our stdin handle.
309
+ def spawn_completion_watcher(task, stdin, wait_thr, target_ctx)
310
+ Thread.new do
311
+ status = wait_thr.value
312
+ @monitor.synchronize do
313
+ if task.status == :running
314
+ task.exit_code = status.exitstatus
315
+ task.status = status.success? ? :completed : :failed
316
+ task.ended_at = Time.now
317
+ end
318
+ end
319
+ resolve_init(target_ctx)&.get(task.id)&.sync_state!
320
+ begin; stdin.close unless stdin.closed?; rescue IOError; nil; end
321
+ end
322
+ end
323
+
324
+ def resolve_init(target_ctx)
325
+ @init || (target_ctx.respond_to?(:get) && Rubik::Coeffects.get(target_ctx, Rubik::Coeffects::INIT))
326
+ end
327
+
329
328
  # Atomic rollback of a failed start (AGENTS.md §6): stop any process
330
329
  # already spawned, dispose the per-task scope, and re-raise the
331
330
  # ORIGINAL error — a rollback failure is reported (Log.warn), never
@@ -66,7 +66,7 @@ module Rubik
66
66
  begin
67
67
  cleanup.call
68
68
  rescue StandardError => e
69
- Rubik::Log.warn(:sandbox, "[WARN] Sandbox::Runner cleanup failed: #{e.message}")
69
+ Rubik::Log.warn(:sandbox, "Sandbox::Runner cleanup failed: #{e.message}")
70
70
  end
71
71
  end
72
72
  end
@@ -66,7 +66,7 @@ module Rubik
66
66
  # Unconditional: an audit trail failing silently is indistinguishable
67
67
  # from an operator's intentional disable — the one warn in the guard
68
68
  # that must not hide behind RUBIK_DEBUG.
69
- Rubik::Log.warn(:security, "[WARN] Failed to write audit log #{@audit_log_path}: #{e.message}")
69
+ Rubik::Log.warn(:security, "Failed to write audit log #{@audit_log_path}: #{e.message}")
70
70
  end
71
71
  end
72
72
  end
@@ -172,7 +172,11 @@ module Rubik
172
172
  i += 1
173
173
  end
174
174
 
175
- [known, unknown, overrides, risk_overrides, directories, delegations, positional, present_flags]
175
+ ArgvAnalysis.new(
176
+ known: known, unknown: unknown, overrides: overrides, risk_overrides: risk_overrides,
177
+ directories: directories, delegations: delegations, positional: positional,
178
+ present_flags: present_flags
179
+ )
176
180
  end
177
181
 
178
182
  def self.parse_combined(token, options, argv, idx, directories)
@@ -238,6 +242,8 @@ module Rubik
238
242
  end
239
243
  argv.size
240
244
  end
245
+
246
+ private_class_method :parse_combined, :terminator?, :extract_delegation_tokens, :skip_delegation_tokens
241
247
  end
242
248
  end
243
249
  end
@@ -72,9 +72,14 @@ module Rubik
72
72
  end
73
73
 
74
74
  # Step 4: Options
75
- _, u_opts, overrides, r_overrides, o_dirs, o_dels, rem_pos, present_flags = Options.classify_options(
76
- remaining, matched_def
77
- )
75
+ analysis = Options.classify_options(remaining, matched_def)
76
+ u_opts = analysis.unknown
77
+ overrides = analysis.overrides
78
+ r_overrides = analysis.risk_overrides
79
+ o_dirs = analysis.directories
80
+ o_dels = analysis.delegations
81
+ rem_pos = analysis.positional
82
+ present_flags = analysis.present_flags
78
83
 
79
84
  all_overrides = g_overrides + overrides
80
85
  all_risk_overrides = g_risk_overrides + r_overrides
@@ -155,6 +155,14 @@ module Rubik
155
155
  end
156
156
  end
157
157
 
158
+ # Named result of argv classification. Replaces a positional 8-tuple so
159
+ # the field order is defined once, at the seam, instead of being
160
+ # memorized by every caller.
161
+ ArgvAnalysis = Data.define(
162
+ :known, :unknown, :overrides, :risk_overrides,
163
+ :directories, :delegations, :positional, :present_flags
164
+ )
165
+
158
166
  ExpressionResult = Data.define(
159
167
  :expression, :classification, :risk, :directories,
160
168
  :write_paths, :read_paths, :commands, :redirects, :parse_warnings,
@@ -150,86 +150,21 @@ module Rubik
150
150
  begin
151
151
  ast = Rubik::Security::Classifier.classify(cmd_str, shell: shell)
152
152
  @path_policy.check_critical_path_writes!(ast, cmd_str)
153
- if ast.classification == :dangerous
154
- # Safe-probe exemption (highest-priority friction fix): run the
155
- # catastrophic fallback regex first — it never loosens.
156
- # Strictly single, isolated command without inner commands or chains.
157
- if isolated_single_command?(ast) && safe_probe?(cmd_str)
158
- verify_command_fallback_regex!(cmd_str)
159
- @audit.log_audit("safe_probe", command: cmd_str, reason: "safe_probe_exemption")
160
- return true
161
- end
162
- walk_reason = dangerous_reason(ast.commands)
163
- # Expression-level elevation marks no single command dangerous —
164
- # the per-command walk bottoms out at its sentinel while the
165
- # composed evidence travels on the ExpressionResult itself.
166
- expression_reason = walk_reason == "dangerous_ast" ? expression_level_reason(ast) : nil
167
- return true if operator_allowlist_pass?(ast, cmd_str)
168
-
169
- block_dangerous_command!(ast, cmd_str, reason: expression_reason || walk_reason, expression_reason: expression_reason)
170
- end
171
-
172
- # UNKNOWN is fail-closed, not pass-through: the matcher rates every
173
- # database-less binary unknown/high, so letting it fall through to
174
- # the catastrophic-only regex would run `socat`/`nmap`/any unlisted
175
- # tool with zero approval while the tool copy advertises fail-closed.
176
- # Allowlist rescue unchanged (every top-level segment must match).
177
- # No safe-probe exemption: an unknown binary's --version still
178
- # executes an unvetted binary — the allowlist is the valve.
179
- if ast.classification == :unknown && !allow_unknown
180
- return true if operator_allowlist_pass?(ast, cmd_str)
181
-
182
- # Workspace Trust Discovery Recognition Gate:
183
- if workspace_trust_candidate_allowed?(cmd_str, ast)
184
- @audit.log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
185
- verify_command_fallback_regex!(cmd_str)
186
- return true
187
- end
188
-
189
- # Interactive operator approval gate (Antigravity-style single keypress)
190
- return true if operator_interactive_approval?(cmd_str, shell)
191
-
192
- block_unknown_command!(cmd_str)
193
- end
194
-
195
- # Ambiguous parse (tree-sitter syntax errors) is a classification
196
- # failure, not a pass: the walk cannot vouch for the whole
197
- # expression, so a safe-looking partial verdict must not fall
198
- # through to the catastrophic-only regex gate. The allowlist stays
199
- # the valve because a real AST exists — every segment is checked
200
- # against the operator entries.
201
- if !allow_unknown && ast.parse_warnings.to_a.any?
202
- return true if operator_allowlist_pass?(ast, cmd_str)
203
-
204
- block_ambiguous_parse!(ast, cmd_str)
205
- end
206
-
207
- # Classification-based allow verdicts must not skip the un-bypassable
208
- # fallback regex: every other allow path runs it (directly or via
209
- # operator_allowlist_pass?). An under-rated database entry must not
210
- # become a silent full bypass of the final safety layer.
211
- if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
212
- verify_command_fallback_regex!(cmd_str)
213
- return true
214
- end
153
+ # Phase pipeline: each phase returns true when it has already
154
+ # produced an allow verdict (audit + fallback regex included),
155
+ # false to defer to the next phase, and raises BlockedWriteError
156
+ # for a block verdict — exactly the pre-split control flow.
157
+ return true if verify_dangerous_classification!(ast, cmd_str)
158
+
159
+ return true if verify_unknown_classification!(ast, cmd_str, shell: shell, allow_unknown: allow_unknown)
160
+
161
+ return true if verify_ambiguous_parse!(ast, cmd_str, allow_unknown: allow_unknown)
162
+
163
+ return true if verify_allow_classification!(ast, cmd_str)
215
164
  rescue BlockedWriteError
216
165
  raise
217
166
  rescue StandardError => e
218
- # Unconditional warn + audit trail: a classifier crash is a
219
- # security-observable downgrade nobody should need RUBIK_DEBUG to
220
- # notice. The shell gate fails closed — an exception must never
221
- # mint execution permission; the operator allowlist is the one
222
- # sanctioned valve. The allow_unknown seam (no production caller
223
- # today) keeps flowing into its own deny layers
224
- # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
225
- if allow_unknown
226
- Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{display_command(e.message)}")
227
- @audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
228
- decision: "synthesis_layers")
229
- else
230
- Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{display_command(e.message)}")
231
- block_on_classifier_failure!(cmd_str, e)
232
- end
167
+ handle_classifier_failure!(cmd_str, e, allow_unknown: allow_unknown)
233
168
  end
234
169
 
235
170
  verify_command_fallback_regex!(cmd_str)
@@ -249,6 +184,99 @@ module Rubik
249
184
 
250
185
  private
251
186
 
187
+ # Dangerous-classification phase of verify_command_safety!: the
188
+ # safe-probe exemption is the highest-priority friction fix — the
189
+ # catastrophic fallback regex runs first, it never loosens. True means
190
+ # an allow verdict already ran (audit + regex); a block verdict raises.
191
+ def verify_dangerous_classification!(ast, cmd_str)
192
+ return false unless ast.classification == :dangerous
193
+
194
+ # Strictly single, isolated command without inner commands or chains.
195
+ if isolated_single_command?(ast) && safe_probe?(cmd_str)
196
+ verify_command_fallback_regex!(cmd_str)
197
+ @audit.log_audit("safe_probe", command: cmd_str, reason: "safe_probe_exemption")
198
+ return true
199
+ end
200
+ walk_reason = dangerous_reason(ast.commands)
201
+ # Expression-level elevation marks no single command dangerous —
202
+ # the per-command walk bottoms out at its sentinel while the
203
+ # composed evidence travels on the ExpressionResult itself.
204
+ expression_reason = walk_reason == "dangerous_ast" ? expression_level_reason(ast) : nil
205
+ return true if operator_allowlist_pass?(ast, cmd_str)
206
+
207
+ block_dangerous_command!(ast, cmd_str, reason: expression_reason || walk_reason, expression_reason: expression_reason)
208
+ end
209
+
210
+ # Unknown-classification phase of verify_command_safety!: UNKNOWN is
211
+ # fail-closed, not pass-through — the matcher rates every database-less
212
+ # binary unknown/high, so letting it fall through to the catastrophic-only
213
+ # regex would run `socat`/`nmap`/any unlisted tool with zero approval
214
+ # while the tool copy advertises fail-closed. Allowlist rescue unchanged
215
+ # (every top-level segment must match). No safe-probe exemption: an
216
+ # unknown binary's --version still executes an unvetted binary — the
217
+ # allowlist is the valve.
218
+ def verify_unknown_classification!(ast, cmd_str, shell:, allow_unknown:)
219
+ return false if ast.classification != :unknown || allow_unknown
220
+
221
+ return true if operator_allowlist_pass?(ast, cmd_str)
222
+
223
+ # Workspace Trust Discovery Recognition Gate:
224
+ if workspace_trust_candidate_allowed?(cmd_str, ast)
225
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
226
+ verify_command_fallback_regex!(cmd_str)
227
+ return true
228
+ end
229
+
230
+ # Interactive operator approval gate (Antigravity-style single keypress)
231
+ return true if operator_interactive_approval?(cmd_str, shell)
232
+
233
+ block_unknown_command!(cmd_str)
234
+ end
235
+
236
+ # Ambiguous-parse phase of verify_command_safety!: a tree-sitter syntax
237
+ # error is a classification failure, not a pass — the walk cannot vouch
238
+ # for the whole expression, so a safe-looking partial verdict must not
239
+ # fall through to the catastrophic-only regex gate. The allowlist stays
240
+ # the valve because a real AST exists — every segment is checked
241
+ # against the operator entries.
242
+ def verify_ambiguous_parse!(ast, cmd_str, allow_unknown:)
243
+ return false if allow_unknown || ast.parse_warnings.to_a.empty?
244
+
245
+ return true if operator_allowlist_pass?(ast, cmd_str)
246
+
247
+ block_ambiguous_parse!(ast, cmd_str)
248
+ end
249
+
250
+ # Allow-classification phase of verify_command_safety!: these verdicts
251
+ # must not skip the un-bypassable fallback regex — every other allow
252
+ # path runs it (directly or via operator_allowlist_pass?). An
253
+ # under-rated database entry must not become a silent full bypass of
254
+ # the final safety layer.
255
+ def verify_allow_classification!(ast, cmd_str)
256
+ return false unless [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
257
+
258
+ verify_command_fallback_regex!(cmd_str)
259
+ true
260
+ end
261
+
262
+ # Classifier-crash phase of verify_command_safety!: unconditional warn +
263
+ # audit trail — a classifier crash is a security-observable downgrade
264
+ # nobody should need RUBIK_DEBUG to notice. The shell gate fails closed
265
+ # — an exception must never mint execution permission; the operator
266
+ # allowlist is the one sanctioned valve. The allow_unknown seam (no
267
+ # production caller today) keeps flowing into its own deny layers
268
+ # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
269
+ def handle_classifier_failure!(cmd_str, error, allow_unknown:)
270
+ if allow_unknown
271
+ Rubik::Log.warn(:security, "AST classification error on non-shell input, continuing to synthesis deny layers: #{display_command(error.message)}")
272
+ @audit.log_audit("classifier_error", command: cmd_str, reason: "#{error.class}: #{error.message}",
273
+ decision: "synthesis_layers")
274
+ else
275
+ Rubik::Log.warn(:security, "AST classification error, failing closed: #{error.class}: #{display_command(error.message)}")
276
+ block_on_classifier_failure!(cmd_str, error)
277
+ end
278
+ end
279
+
252
280
  # Human-facing rendering only; the shared helper keeps every block-error
253
281
  # raise site consistent. Raw bytes still drive execution and the audit.
254
282
  def display_command(value)
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "../errors"
4
+
3
5
  module Rubik
4
6
  module Security
5
7
  CONTROL_ESCAPES = { "\n" => "\\n", "\r" => "\\r", "\t" => "\\t", "\0" => "\\0", "\e" => "\\e" }.freeze
@@ -20,7 +22,7 @@ module Rubik
20
22
  # instead of regex-munging #message. Kept in its own file: consumers that
21
23
  # only rescue/raise the error (sandbox runner, buffer manager) must not
22
24
  # load the whole guard/classifier stack for the constant.
23
- class BlockedWriteError < StandardError
25
+ class BlockedWriteError < Rubik::Error
24
26
  attr_accessor :blocked_command, :rule_name, :probe_like, :kind, :path,
25
27
  :segment_report, :classification_reason
26
28
 
@@ -5,6 +5,8 @@ require "fileutils"
5
5
  require "open3"
6
6
  require "tempfile"
7
7
  require "tmpdir"
8
+ require_relative "../errors"
9
+ require_relative "../log"
8
10
  require_relative "../platform"
9
11
 
10
12
  module Rubik
@@ -42,7 +44,7 @@ module Rubik
42
44
  SERVICE = "rubik"
43
45
  NAME_PATTERN = /\A\w[\w.-]*\z/
44
46
 
45
- class Error < StandardError; end
47
+ class Error < Rubik::Error; end
46
48
 
47
49
  @monitor = Monitor.new
48
50
  @backend = nil
@@ -68,10 +70,11 @@ module Rubik
68
70
  return value unless reference?(value)
69
71
 
70
72
  fetch(value.delete_prefix(REFERENCE_PREFIX))
71
- rescue Error
73
+ rescue Error => e
72
74
  # A hand-edited pointer (empty name, hostile characters) must not
73
75
  # crash provider builds or REPL boot — an unresolvable reference
74
76
  # resolves to nil, and Registry warns loudly instead.
77
+ Rubik::Log.debug(:security, "secret reference unresolved (#{e.class}: #{e.message})")
75
78
  nil
76
79
  end
77
80
 
@@ -402,7 +405,8 @@ module Rubik
402
405
 
403
406
  parsed = YAML.safe_load_file(@path, permitted_classes: [], aliases: false)
404
407
  parsed.is_a?(Hash) ? parsed : {}
405
- rescue Psych::Exception
408
+ rescue Psych::Exception => e
409
+ Rubik::Log.debug(:security, "secret file store unreadable, treating as empty (#{e.class}: #{e.message})")
406
410
  {}
407
411
  end
408
412
 
@@ -419,12 +423,9 @@ module Rubik
419
423
  tmp.flush
420
424
  tmp.chmod(0o600)
421
425
  tmp.close
422
- File.rename(tmp.path, @path)
423
- rescue SystemCallError
424
- # Windows rename can still refuse an existing destination:
425
- # fall back to a short delete-then-rename window.
426
- tmp.close
427
- FileUtils.rm_f(@path)
426
+ # No delete-then-rename fallback: removing the destination first
427
+ # would open a window where the store reads as empty and, if the
428
+ # second rename failed, lose every secret with no backup.
428
429
  File.rename(tmp.path, @path)
429
430
  ensure
430
431
  tmp.close
@@ -437,7 +438,8 @@ module Rubik
437
438
  def ensure_owner_only!
438
439
  FileUtils.touch(@path) unless File.exist?(@path)
439
440
  File.chmod(0o600, @path)
440
- rescue SystemCallError
441
+ rescue SystemCallError => e
442
+ Rubik::Log.debug(:security, "could not enforce owner-only permissions on secret store (#{e.class}: #{e.message})")
441
443
  nil
442
444
  end
443
445
 
@@ -29,7 +29,7 @@ module Rubik
29
29
  begin
30
30
  FileUtils.mkdir_p(@sessions_dir)
31
31
  rescue SystemCallError => e
32
- Rubik::Log.warn(:session, "[WARN] Failed to create sessions directory #{@sessions_dir}: #{e.message}") if ENV["RUBIK_DEBUG"]
32
+ Rubik::Log.warn(:session, "Failed to create sessions directory #{@sessions_dir}: #{e.message}") if ENV["RUBIK_DEBUG"]
33
33
  end
34
34
 
35
35
  filename = session_name || "session_#{Time.now.strftime('%Y%m%d_%H%M%S')}_#{Process.pid}_#{(Time.now.to_f * 1000).to_i % 1000}.jsonl"
@@ -86,7 +86,11 @@ module Rubik
86
86
  return unless @session_file && File.exist?(@session_file)
87
87
 
88
88
  File.open(@session_file, "a", &:fsync)
89
- rescue StandardError
89
+ rescue StandardError => e
90
+ # The fsync barrier is flush's entire durability promise (a save copy
91
+ # taken afterwards must never observe a torn tail); a failed barrier
92
+ # silently voids it, so the failure can never be invisible.
93
+ Rubik::Log.warn(:session, "[Session] fsync barrier failed for #{@session_file}: #{e.class}: #{e.message}")
90
94
  nil
91
95
  end
92
96
 
@@ -103,8 +107,8 @@ module Rubik
103
107
  end
104
108
  ))
105
109
  File.delete(@session_file) if is_empty_or_only_start
106
- rescue StandardError
107
- # ignore file cleanup error
110
+ rescue StandardError => e
111
+ Rubik::Log.warn(:session, "session-file cleanup failed for #{@session_file}: #{e.class}: #{e.message}")
108
112
  end
109
113
  end
110
114
 
@@ -116,8 +120,9 @@ module Rubik
116
120
 
117
121
  begin
118
122
  push_event(JSON.parse(line))
119
- rescue JSON::ParserError
120
- # ignore malformed line
123
+ rescue JSON::ParserError => e
124
+ # The message would quote session content; log the class only.
125
+ Rubik::Log.debug(:session, "skipped malformed session line (#{e.class})")
121
126
  end
122
127
  end
123
128
  end
@@ -2,6 +2,8 @@
2
2
 
3
3
  require "yaml"
4
4
 
5
+ require_relative "../errors"
6
+
5
7
  module Rubik
6
8
  module Skills
7
9
  # Splits a SKILL.md into its YAML frontmatter mapping and markdown body.
@@ -11,7 +13,7 @@ module Rubik
11
13
  # object deserialization, keeping the open-trust model honest (a skill
12
14
  # can never instantiate Ruby objects).
13
15
  class Frontmatter
14
- class Error < StandardError; end
16
+ class Error < Rubik::Error; end
15
17
 
16
18
  # Opening fence must be the first line (spec); the non-greedy body
17
19
  # match stops at the FIRST closing fence, so "---" rules inside the
@@ -99,7 +99,7 @@ module Rubik
99
99
  return nil unless File.exist?(file)
100
100
 
101
101
  File.foreach(file, encoding: "UTF-8") do |line|
102
- row = parse_row(line)
102
+ row = parse_row(line, file: file)
103
103
  next unless row.is_a?(Hash) && row["role"] == "user"
104
104
 
105
105
  content = row["content"].to_s
@@ -111,9 +111,15 @@ module Rubik
111
111
  nil
112
112
  end
113
113
 
114
- def parse_row(line)
114
+ # Malformed JSONL rows are skipped (parse → nil), not fatal: a torn or
115
+ # hand-edited transcript must not break task extraction. The failure
116
+ # still surfaces at debug level with file context, so a recurring
117
+ # corruption pattern is diagnosable without pinning tests to private
118
+ # internals.
119
+ def parse_row(line, file: nil)
115
120
  JSON.parse(line)
116
- rescue StandardError
121
+ rescue StandardError => e
122
+ Rubik::Log.debug(:storage, "[Storage] transcript row parse failed in #{file || 'unknown file'}: #{e.class}: #{e.message.to_s.chars.first(120).join}")
117
123
  nil
118
124
  end
119
125
 
@@ -1,7 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "strings-ansi"
4
- require_relative "../repl/tee_io"
4
+ require_relative "io_probe"
5
5
 
6
6
  module Rubik
7
7
  module UI
@@ -66,14 +66,10 @@ module Rubik
66
66
  out_io.respond_to?(:tty?) && out_io.tty?
67
67
  end
68
68
 
69
- # Resolves the real terminal behind a TeeIO (first target that is a
70
- # live TTY); returns nil when every target is a capture buffer
71
- # (StringIO#tty? is defined but false), and the IO itself when it is
72
- # not a TeeIO.
69
+ # Resolves the real terminal behind a tee-style output stream
70
+ # (first target that is a live TTY); see Rubik::UI::IoProbe.
73
71
  def unwrap_tee(io)
74
- return io unless io.is_a?(Rubik::REPL::TeeIO)
75
-
76
- io.targets.compact.find(&:tty?)
72
+ IoProbe.unwrap_tee(io)
77
73
  end
78
74
 
79
75
  def clicolor_force?