rubik 0.9.1 → 0.11.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 (138) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +203 -1
  4. data/lib/rubik/adapter/base.rb +2 -1
  5. data/lib/rubik/adapter/process.rb +28 -67
  6. data/lib/rubik/ast/extractor.rb +2 -1
  7. data/lib/rubik/ast/treesitter_extractor.rb +2 -1
  8. data/lib/rubik/benchmark/vakanuvis_adoption.rb +12 -4
  9. data/lib/rubik/buffer/apply_contract.rb +3 -3
  10. data/lib/rubik/buffer/apply_transaction.rb +165 -0
  11. data/lib/rubik/buffer/manager.rb +26 -120
  12. data/lib/rubik/config/deep_ops.rb +4 -1
  13. data/lib/rubik/config/defaults.rb +6 -3
  14. data/lib/rubik/config/schema.rb +8 -0
  15. data/lib/rubik/config/secret_policy.rb +198 -0
  16. data/lib/rubik/config/store.rb +2 -1
  17. data/lib/rubik/config.rb +13 -2
  18. data/lib/rubik/context/ignore_rules.rb +193 -0
  19. data/lib/rubik/context/scanner.rb +46 -161
  20. data/lib/rubik/diagnostics/collector.rb +0 -9
  21. data/lib/rubik/errors.rb +15 -0
  22. data/lib/rubik/event_bus.rb +2 -1
  23. data/lib/rubik/kernel/dispatcher.rb +12 -7
  24. data/lib/rubik/kernel/unit.rb +4 -1
  25. data/lib/rubik/llm/client.rb +6 -200
  26. data/lib/rubik/llm/connection_pool.rb +104 -0
  27. data/lib/rubik/llm/registry.rb +13 -9
  28. data/lib/rubik/llm/router.rb +2 -5
  29. data/lib/rubik/llm/sse_parser.rb +110 -0
  30. data/lib/rubik/log.rb +21 -0
  31. data/lib/rubik/lsp/circuit_breaker.rb +98 -0
  32. data/lib/rubik/lsp/client.rb +77 -273
  33. data/lib/rubik/lsp/client_provisioner.rb +49 -0
  34. data/lib/rubik/lsp/manager.rb +67 -96
  35. data/lib/rubik/lsp/transport.rb +365 -0
  36. data/lib/rubik/mcp/boot_lifecycle.rb +6 -2
  37. data/lib/rubik/mcp/boot_run.rb +190 -0
  38. data/lib/rubik/mcp/manager.rb +55 -166
  39. data/lib/rubik/mcp/transport/stdio.rb +4 -1
  40. data/lib/rubik/orchestrator/auto_apply.rb +8 -6
  41. data/lib/rubik/orchestrator/continuation_manager.rb +3 -22
  42. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +12 -1
  43. data/lib/rubik/orchestrator/goal_ledger/schema_vocabulary.rb +38 -0
  44. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +6 -1
  45. data/lib/rubik/orchestrator/goal_ledger.rb +1 -0
  46. data/lib/rubik/orchestrator/goal_session.rb +53 -39
  47. data/lib/rubik/orchestrator/loop.rb +28 -47
  48. data/lib/rubik/orchestrator/lsp_feedback.rb +1 -1
  49. data/lib/rubik/orchestrator/maestro_gate.rb +5 -7
  50. data/lib/rubik/orchestrator/provider_recovery.rb +4 -2
  51. data/lib/rubik/orchestrator/provider_resolver.rb +4 -2
  52. data/lib/rubik/orchestrator/resume_window.rb +96 -0
  53. data/lib/rubik/orchestrator/shell_deps.rb +16 -0
  54. data/lib/rubik/orchestrator/step_executor.rb +2 -1
  55. data/lib/rubik/orchestrator/stream_manager.rb +2 -1
  56. data/lib/rubik/orchestrator/subagent/deferred_spec.rb +4 -1
  57. data/lib/rubik/orchestrator/subagent/instance.rb +7 -12
  58. data/lib/rubik/orchestrator/subagent/lifecycle.rb +3 -1
  59. data/lib/rubik/orchestrator/subagent/notices.rb +2 -2
  60. data/lib/rubik/orchestrator/subagent/questioner.rb +3 -1
  61. data/lib/rubik/orchestrator/subagent/reaper.rb +3 -5
  62. data/lib/rubik/orchestrator/subagent/resilience.rb +4 -2
  63. data/lib/rubik/orchestrator/subagent/result_archive.rb +0 -4
  64. data/lib/rubik/orchestrator/subagent/run_cycle.rb +2 -7
  65. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +11 -2
  66. data/lib/rubik/orchestrator/subagent/step_runner.rb +10 -2
  67. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  68. data/lib/rubik/orchestrator/subagent/type_definition.rb +0 -4
  69. data/lib/rubik/orchestrator/tool_timeout.rb +121 -1
  70. data/lib/rubik/platform/io_drain.rb +5 -2
  71. data/lib/rubik/platform/process.rb +144 -54
  72. data/lib/rubik/platform.rb +2 -1
  73. data/lib/rubik/plugin/manager.rb +2 -1
  74. data/lib/rubik/plugin/storage.rb +8 -8
  75. data/lib/rubik/repl/commands/agent_context.rb +8 -7
  76. data/lib/rubik/repl/commands/agent_execution.rb +13 -32
  77. data/lib/rubik/repl/commands/agent_models.rb +4 -3
  78. data/lib/rubik/repl/commands/agent_providers.rb +43 -2
  79. data/lib/rubik/repl/commands/base.rb +47 -2
  80. data/lib/rubik/repl/commands/buffer.rb +5 -4
  81. data/lib/rubik/repl/commands/lsp.rb +2 -1
  82. data/lib/rubik/repl/commands/pruner.rb +2 -1
  83. data/lib/rubik/repl/commands/secrets.rb +151 -0
  84. data/lib/rubik/repl/commands/workspace.rb +60 -150
  85. data/lib/rubik/repl/commands/workspace_approval.rb +209 -0
  86. data/lib/rubik/repl/config_wiring.rb +8 -6
  87. data/lib/rubik/repl/hooks.rb +2 -1
  88. data/lib/rubik/repl/input_execution.rb +162 -79
  89. data/lib/rubik/repl/input_loop.rb +2 -1
  90. data/lib/rubik/repl/lifecycle.rb +60 -210
  91. data/lib/rubik/repl/notice_router.rb +319 -0
  92. data/lib/rubik/repl/paste_support.rb +3 -1
  93. data/lib/rubik/repl/presentation.rb +5 -3
  94. data/lib/rubik/repl/pruner/gate.rb +3 -1
  95. data/lib/rubik/repl/pruner/harness.rb +2 -1
  96. data/lib/rubik/repl/shell.rb +4 -3
  97. data/lib/rubik/repl/tee_io.rb +2 -1
  98. data/lib/rubik/repl/turn_recorder.rb +6 -5
  99. data/lib/rubik/runtime/ast_service.rb +2 -1
  100. data/lib/rubik/runtime/discovery.rb +3 -2
  101. data/lib/rubik/runtime/loop_service.rb +4 -3
  102. data/lib/rubik/runtime/manifest_store.rb +9 -1
  103. data/lib/rubik/runtime/overlay_guard.rb +127 -0
  104. data/lib/rubik/runtime/overlay_storage.rb +109 -163
  105. data/lib/rubik/runtime/task_manager.rb +64 -25
  106. data/lib/rubik/sandbox/driver/docker.rb +5 -1
  107. data/lib/rubik/sandbox/runner.rb +21 -19
  108. data/lib/rubik/security/audit_log.rb +2 -1
  109. data/lib/rubik/security/command_gate.rb +126 -243
  110. data/lib/rubik/security/guard.rb +7 -3
  111. data/lib/rubik/security/secret_store.rb +492 -0
  112. data/lib/rubik/security/segment_report.rb +161 -0
  113. data/lib/rubik/security/synthesis_gate.rb +8 -11
  114. data/lib/rubik/session/manager.rb +7 -1
  115. data/lib/rubik/session/recorder.rb +2 -1
  116. data/lib/rubik/skills/manager.rb +4 -4
  117. data/lib/rubik/storage/search.rb +49 -0
  118. data/lib/rubik/storage/store.rb +13 -20
  119. data/lib/rubik/storage/transcript_indexer.rb +3 -2
  120. data/lib/rubik/storage/vakanuvis/harness.rb +2 -3
  121. data/lib/rubik/storage/vakanuvis.rb +2 -1
  122. data/lib/rubik/tools/base.rb +22 -0
  123. data/lib/rubik/tools/builtins/files.rb +3 -15
  124. data/lib/rubik/tools/builtins/goal_ledger.rb +12 -1
  125. data/lib/rubik/tools/builtins/grep.rb +1 -6
  126. data/lib/rubik/tools/builtins/lifecycle.rb +6 -5
  127. data/lib/rubik/tools/builtins/synthesis.rb +3 -3
  128. data/lib/rubik/tools/lifecycle_rollbacks.rb +14 -1
  129. data/lib/rubik/tools/preflight_runner.rb +2 -1
  130. data/lib/rubik/tools/truncator.rb +48 -36
  131. data/lib/rubik/tools/uri_resolver.rb +3 -2
  132. data/lib/rubik/ui/banner.rb +4 -3
  133. data/lib/rubik/ui/capability.rb +1 -0
  134. data/lib/rubik/ui/spinner.rb +3 -1
  135. data/lib/rubik/ui/statusline.rb +6 -5
  136. data/lib/rubik/version.rb +1 -1
  137. data/lib/rubik.rb +4 -5
  138. metadata +20 -1
@@ -1,9 +1,11 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "shellwords"
4
+ require_relative "../log"
4
5
  require_relative "allowlist"
5
6
  require_relative "classifier"
6
7
  require_relative "errors"
8
+ require_relative "segment_report"
7
9
 
8
10
  module Rubik
9
11
  module Security
@@ -57,12 +59,6 @@ module Rubik
57
59
  /%0\|%0/
58
60
  ].freeze
59
61
 
60
- # Display caps for the blocked-segment report (guidance rendering, not
61
- # gate semantics): one segment's argv rendering and the one-line
62
- # wrapper preview never exceed these.
63
- SEGMENT_DISPLAY_CAP = 120
64
- WRAPPER_PREVIEW_CAP = 60
65
-
66
62
  # Salt version/help probe'ları (Plan: safe-probe muafiyeti): a command
67
63
  # whose ONLY arguments are these flags is read-only by construction.
68
64
  SAFE_PROBE_FLAGS = ["--version", "-v", "--help", "-h"].freeze
@@ -151,10 +147,7 @@ module Rubik
151
147
  # Safe-probe exemption (highest-priority friction fix): run the
152
148
  # catastrophic fallback regex first — it never loosens.
153
149
  # Strictly single, isolated command without inner commands or chains.
154
- single_cmd = ast.respond_to?(:commands) && ast.commands.to_a.size == 1 &&
155
- ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.empty? &&
156
- (!ast.commands.first.respond_to?(:inner_commands) || ast.commands.first.inner_commands.nil? || ast.commands.first.inner_commands.empty?)
157
- if single_cmd && safe_probe?(cmd_str)
150
+ if isolated_single_command?(ast) && safe_probe?(cmd_str)
158
151
  verify_command_fallback_regex!(cmd_str)
159
152
  @audit.log_audit("safe_probe", command: cmd_str, reason: "safe_probe_exemption")
160
153
  return true
@@ -164,40 +157,9 @@ module Rubik
164
157
  # the per-command walk bottoms out at its sentinel while the
165
158
  # composed evidence travels on the ExpressionResult itself.
166
159
  expression_reason = walk_reason == "dangerous_ast" ? expression_level_reason(ast) : nil
167
- reason = expression_reason || walk_reason
168
- # Operator allowlist gate (fail-closed default): the entry must
169
- # cover EVERY dangerous segment recursively; catastrophic fallback
170
- # regex still runs afterwards — allowlisting never bypasses it.
171
- # A bug in the gate itself must fail closed, not fall through to
172
- # the regex-only downgrade below.
173
- allowlisted = allowlisted_fail_closed(ast, cmd_str)
174
- if allowlisted
175
- @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
176
- verify_command_fallback_regex!(cmd_str)
177
- return true
178
- end
179
- # Enrichment must never be able to un-block: a bug in the report
180
- # walk downgrades to nil here, the raise below still fires.
181
- report = begin
182
- dangerous_segment_report(ast.commands)
183
- rescue StandardError => e
184
- warn "[Guard] segment report failed: #{e.class}: #{e.message}"
185
- nil
186
- end
187
- @audit.log_audit("blocked_command", command: cmd_str, reason: reason,
188
- dangerous_segments: segment_count(report))
189
- # probe_shape? (not safe_probe?): probes only reach this raise when
190
- # the exemption is disabled, so safe_probe? would be constantly
191
- # false and the variant-(a) guidance dead code.
192
- raise BlockedWriteError.new(
193
- "Dangerous command execution blocked: #{cmd_str} (reason: #{reason})",
194
- kind: :dangerous_command,
195
- blocked_command: cmd_str,
196
- rule_name: dangerous_rule_name(ast.commands) || (expression_reason ? "expression_level" : "dangerous_pattern"),
197
- probe_like: probe_shape?(cmd_str),
198
- segment_report: report,
199
- classification_reason: expression_reason
200
- )
160
+ return true if operator_allowlist_pass?(ast, cmd_str)
161
+
162
+ block_dangerous_command!(ast, cmd_str, reason: expression_reason || walk_reason, expression_reason: expression_reason)
201
163
  end
202
164
 
203
165
  # UNKNOWN is fail-closed, not pass-through: the matcher rates every
@@ -208,14 +170,7 @@ module Rubik
208
170
  # No safe-probe exemption: an unknown binary's --version still
209
171
  # executes an unvetted binary — the allowlist is the valve.
210
172
  if ast.classification == :unknown && !allow_unknown
211
- # Same fail-closed discipline as the dangerous branch: gate
212
- # trouble must never convert this block into a pass.
213
- allowlisted = allowlisted_fail_closed(ast, cmd_str)
214
- if allowlisted
215
- @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
216
- verify_command_fallback_regex!(cmd_str)
217
- return true
218
- end
173
+ return true if operator_allowlist_pass?(ast, cmd_str)
219
174
 
220
175
  # Workspace Trust Discovery Recognition Gate:
221
176
  if workspace_trust_candidate_allowed?(cmd_str, ast)
@@ -225,38 +180,9 @@ module Rubik
225
180
  end
226
181
 
227
182
  # Interactive operator approval gate (Antigravity-style single keypress)
228
- effective_shell = shell || @shell
229
- if effective_shell.respond_to?(:interactive_input?) && effective_shell.interactive_input?
230
- # Defense-in-depth: Un-bypassable catastrophic fallback regex MUST pass before prompt
231
- verify_command_fallback_regex!(cmd_str)
183
+ return true if operator_interactive_approval?(cmd_str, shell)
232
184
 
233
- theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
234
- (defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
235
-
236
- question = "Allow unclassified command execution: '#{cmd_str}'?"
237
- answer = if defined?(Rubik::UI::Approvals)
238
- Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
239
- else
240
- "n"
241
- end
242
-
243
- if ["y", "yes"].include?(answer.to_s.downcase)
244
- @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_interactive_approval")
245
- return true
246
- end
247
- end
248
-
249
- @audit.log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
250
- raise BlockedWriteError.new(
251
- "Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
252
- "command database, so its effects cannot be classified. If it is genuinely safe, the " \
253
- "operator can allowlist the exact prefix: !allow-cmd add \"<binary> [args]\"",
254
- kind: :unknown_command,
255
- blocked_command: cmd_str,
256
- rule_name: "unknown_command",
257
- probe_like: probe_shape?(cmd_str),
258
- segment_report: nil
259
- )
185
+ block_unknown_command!(cmd_str)
260
186
  end
261
187
 
262
188
  # Ambiguous parse (tree-sitter syntax errors) is a classification
@@ -266,22 +192,9 @@ module Rubik
266
192
  # the valve because a real AST exists — every segment is checked
267
193
  # against the operator entries.
268
194
  if !allow_unknown && ast.parse_warnings.to_a.any?
269
- allowlisted = allowlisted_fail_closed(ast, cmd_str)
270
- if allowlisted
271
- @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
272
- verify_command_fallback_regex!(cmd_str)
273
- return true
274
- end
275
- @audit.log_audit("blocked_command", command: cmd_str, reason: "parse_ambiguous",
276
- parse_warnings: ast.parse_warnings.to_a.size)
277
- raise BlockedWriteError.new(
278
- "Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{cmd_str}",
279
- kind: :parse_ambiguous,
280
- blocked_command: cmd_str,
281
- rule_name: "parse_ambiguous",
282
- probe_like: probe_shape?(cmd_str),
283
- segment_report: nil
284
- )
195
+ return true if operator_allowlist_pass?(ast, cmd_str)
196
+
197
+ block_ambiguous_parse!(ast, cmd_str)
285
198
  end
286
199
 
287
200
  return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
@@ -296,11 +209,11 @@ module Rubik
296
209
  # today) keeps flowing into its own deny layers
297
210
  # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
298
211
  if allow_unknown
299
- warn "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}"
212
+ Rubik::Log.warn(:security, "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}")
300
213
  @audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
301
214
  decision: "synthesis_layers")
302
215
  else
303
- warn "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}"
216
+ Rubik::Log.warn(:security, "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}")
304
217
  block_on_classifier_failure!(cmd_str, e)
305
218
  end
306
219
  end
@@ -346,10 +259,121 @@ module Rubik
346
259
  @allowlist.command_allowlisted?(ast, cmd_str: cmd_str)
347
260
  end
348
261
  rescue StandardError => e
349
- warn "[Guard] #{'raw ' if raw}allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
262
+ Rubik::Log.warn(:security, "[Guard] #{'raw ' if raw}allowlist evaluation failed, failing closed: #{e.class}: #{e.message}")
350
263
  false
351
264
  end
352
265
 
266
+ # AST fast-path check for the safe-probe exemption: strictly single,
267
+ # isolated command without inner commands or chains.
268
+ def isolated_single_command?(ast)
269
+ ast.respond_to?(:commands) && ast.commands.to_a.size == 1 &&
270
+ ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.empty? &&
271
+ (!ast.commands.first.respond_to?(:inner_commands) || ast.commands.first.inner_commands.nil? || ast.commands.first.inner_commands.empty?)
272
+ end
273
+
274
+ # Operator allowlist valve pass, shared by the dangerous / unknown /
275
+ # ambiguous-parse block paths. Fail-closed default: the entry must
276
+ # cover EVERY dangerous segment recursively; catastrophic fallback
277
+ # regex still runs afterwards — allowlisting never bypasses it.
278
+ # A bug in the gate itself must fail closed, not fall through to
279
+ # the regex-only downgrade below. Returns true only after the
280
+ # allowed_command audit and the fallback regex have run.
281
+ def operator_allowlist_pass?(ast, cmd_str)
282
+ return false unless allowlisted_fail_closed(ast, cmd_str)
283
+
284
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
285
+ verify_command_fallback_regex!(cmd_str)
286
+ true
287
+ end
288
+
289
+ # Report assembly for the dangerous-classification block path, fail-soft
290
+ # to nil: enrichment must never be able to un-block, so a bug in the
291
+ # report walk downgrades to nil here and the raise in
292
+ # block_dangerous_command! still fires.
293
+ # Report assembly delegates to Security::SegmentReport (#500), fail-soft
294
+ # to nil: enrichment must never be able to un-block, so a bug in the
295
+ # report walk downgrades to nil here and the raise in
296
+ # block_dangerous_command! still fires.
297
+ def dangerous_segment_report_or_nil(commands)
298
+ SegmentReport.build(commands)
299
+ rescue StandardError => e
300
+ Rubik::Log.warn(:security, "[Guard] segment report failed: #{e.class}: #{e.message}")
301
+ nil
302
+ end
303
+
304
+ # Dangerous-classification block path: audit the block, then raise with
305
+ # the blocked-segment guidance report attached.
306
+ def block_dangerous_command!(ast, cmd_str, reason:, expression_reason:)
307
+ report = dangerous_segment_report_or_nil(ast.commands)
308
+ @audit.log_audit("blocked_command", command: cmd_str, reason: reason,
309
+ dangerous_segments: segment_count(report))
310
+ # probe_shape? (not safe_probe?): probes only reach this raise when
311
+ # the exemption is disabled, so safe_probe? would be constantly
312
+ # false and the variant-(a) probe guidance would be dead code.
313
+ raise BlockedWriteError.new(
314
+ "Dangerous command execution blocked: #{cmd_str} (reason: #{reason})",
315
+ kind: :dangerous_command,
316
+ blocked_command: cmd_str,
317
+ rule_name: dangerous_rule_name(ast.commands) || (expression_reason ? "expression_level" : "dangerous_pattern"),
318
+ probe_like: probe_shape?(cmd_str),
319
+ segment_report: report,
320
+ classification_reason: expression_reason
321
+ )
322
+ end
323
+
324
+ # Interactive operator approval gate (Antigravity-style single keypress):
325
+ # true (audited) when the operator approves, false when there is no
326
+ # interactive input or the answer is not yes.
327
+ def operator_interactive_approval?(cmd_str, shell)
328
+ effective_shell = shell || @shell
329
+ return false unless effective_shell.respond_to?(:interactive_input?) && effective_shell.interactive_input?
330
+
331
+ # Defense-in-depth: Un-bypassable catastrophic fallback regex MUST pass before prompt
332
+ verify_command_fallback_regex!(cmd_str)
333
+
334
+ theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
335
+ (defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
336
+
337
+ question = "Allow unclassified command execution: '#{cmd_str}'?"
338
+ answer = if defined?(Rubik::UI::Approvals)
339
+ Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
340
+ else
341
+ "n"
342
+ end
343
+
344
+ return false unless ["y", "yes"].include?(answer.to_s.downcase)
345
+
346
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_interactive_approval")
347
+ true
348
+ end
349
+
350
+ def block_unknown_command!(cmd_str)
351
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
352
+ raise BlockedWriteError.new(
353
+ "Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
354
+ "command database, so its effects cannot be classified. If it is genuinely safe, the " \
355
+ "operator can allowlist the exact prefix: !allow-cmd add \"<binary> [args]\"",
356
+ kind: :unknown_command,
357
+ blocked_command: cmd_str,
358
+ rule_name: "unknown_command",
359
+ probe_like: probe_shape?(cmd_str),
360
+ segment_report: nil
361
+ )
362
+ end
363
+
364
+ def block_ambiguous_parse!(ast, cmd_str)
365
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "parse_ambiguous",
366
+ parse_warnings: ast.parse_warnings.to_a.size)
367
+ raise BlockedWriteError.new(
368
+ "Command AST could not be fully parsed (tree-sitter syntax error); execution blocked (fail-closed): #{cmd_str}",
369
+ kind: :parse_ambiguous,
370
+ blocked_command: cmd_str,
371
+ rule_name: "parse_ambiguous",
372
+ probe_like: probe_shape?(cmd_str),
373
+ segment_report: nil
374
+ )
375
+ end
376
+
353
377
  def dangerous_reason(commands)
354
378
  commands.each do |c|
355
379
  next unless c.classification == :dangerous
@@ -389,147 +413,6 @@ module Rubik
389
413
  reason.empty? ? nil : reason
390
414
  end
391
415
 
392
- # Structured report for wrapper/multi-segment blocked-command guidance:
393
- # every innermost dangerous segment with its trigger, the sibling
394
- # commands that passed, a one-line wrapper preview, and the allowlist
395
- # entries that would actually open the gate. Plain data only —
396
- # BlockedWriteError must stay loadable without the classifier stack.
397
- # nil when no single command is dangerous (expression-level elevations
398
- # keep the scalar rule_name guidance path).
399
- def dangerous_segment_report(commands)
400
- segments = []
401
- safe = []
402
- safe_top_argv = []
403
- wrappers = []
404
- collect_dangerous_units(commands, 0, segments, safe, safe_top_argv, wrappers)
405
- return nil if segments.empty?
406
-
407
- # The gate (command_allowlisted?) matches EVERY top-level command,
408
- # safe ones included — the entry set must cover them all to be
409
- # honest: wrapper prefix + top-level dangerous segments + top-level
410
- # safe units.
411
- entries = wrappers.map { |w| wrapper_allowlist_entry(w) }
412
- entries += segments.select { |s| s[:depth].zero? }.map { |s| allowlist_entry_for_argv(s[:argv]) }
413
- entries += safe_top_argv.map { |argv| allowlist_entry_for_argv(argv) }
414
-
415
- {
416
- segments: segments,
417
- safe: safe.uniq,
418
- wrapper_preview: wrappers.empty? ? nil : wrapper_preview(wrappers.first),
419
- allowlist_entries: entries.uniq
420
- }.freeze
421
- end
422
-
423
- # Depth-first walk over the classified command tree. A dangerous
424
- # command whose danger comes from dangerous inners contributes those
425
- # inner leaves instead of itself (bash -c "rm -rf /" reports the inner
426
- # rm, not the wrapper); a dangerous leaf is a segment; non-dangerous
427
- # leaves join the passed roll call. Top-level wrappers (dangerous only
428
- # through their inners) are tracked separately for preview + hint;
429
- # top-level safe units keep their argv for the gate-honest entry set.
430
- def collect_dangerous_units(commands, depth, segments, safe, safe_top_argv, wrappers)
431
- Array(commands).each do |c|
432
- inners = Array(c.inner_commands)
433
- before = segments.size
434
- collect_dangerous_units(inners, depth + 1, segments, safe, safe_top_argv, wrappers)
435
- added = segments.size - before
436
-
437
- if c.classification == :dangerous
438
- if added.positive?
439
- wrappers << c if depth.zero?
440
- else
441
- segments << dangerous_segment_data(c, depth)
442
- end
443
- elsif inners.empty?
444
- safe << safe_segment_name(c)
445
- safe_top_argv << c.argv.dup if depth.zero?
446
- end
447
- end
448
- end
449
-
450
- def dangerous_segment_data(result, depth)
451
- argv = Array(result.argv)
452
- {
453
- display: segment_display(display_tokens(argv, result)),
454
- argv: argv.dup.freeze,
455
- rule: result.matched_rule,
456
- option: result.overriding_option,
457
- reason: result.classification_reason,
458
- depth: depth
459
- }
460
- end
461
-
462
- # Redirect-bearing segments (delegated inners) render their effects,
463
- # not just their argv: `echo pwned > /etc/shadow`, not `echo pwned`.
464
- # Flat operator/target tokens keep segment_display's quoting correct;
465
- # argv itself stays pure — allowlist entries derive from it.
466
- def display_tokens(argv, result)
467
- reds = result.respond_to?(:redirects) ? Array(result.redirects) : []
468
- reds.empty? ? argv : argv + reds.flat_map { |r| [r.operator, r.target] }
469
- end
470
-
471
- # Subcommand-aware roll call of the units that passed ("git checkout",
472
- # not just "git") — matches the operator's mental model of the script.
473
- def safe_segment_name(result)
474
- result.command.join(" ")
475
- end
476
-
477
- # One-line wrapper preview for the guidance first line. The delegated
478
- # payload (the whole -c script) is the argv token that contains
479
- # whitespace — elide it so the full script is never re-embedded in the
480
- # message (the defect this report exists to fix).
481
- def wrapper_preview(result)
482
- argv = Array(result.argv)
483
- tokens = argv.dup
484
- tokens[-1] = "'...'" if tokens.size > 1 && tokens[-1].to_s.match?(/\s/)
485
- preview = segment_display(tokens)
486
- preview.length > WRAPPER_PREVIEW_CAP ? "#{preview[0, WRAPPER_PREVIEW_CAP - 1]}..." : preview
487
- end
488
-
489
- # Shortest top-level argv prefix that actually satisfies the gate's
490
- # token-prefix match (command_allowlisted?): the wrapper binary up to
491
- # and including its delegation flag for flag-value payloads
492
- # ("bash -c", "bash -e -c"), the bare binary for rest-argv wrappers
493
- # ("sudo", "xargs"). Deriving it from delegation_source keeps the hint
494
- # gate-honest for flag permutations a naive first-two-tokens guess
495
- # would miss.
496
- def wrapper_allowlist_entry(wrapper)
497
- argv = Array(wrapper.argv)
498
- return argv.first.to_s if argv.size <= 1
499
-
500
- first_inner = Array(wrapper.inner_commands).first
501
- if first_inner&.delegation_mode.to_s == "flag_value_is_expression"
502
- idx = argv.index(first_inner.delegation_source)
503
- return argv[0..idx].join(" ") if idx&.positive?
504
- end
505
- argv.first.to_s
506
- end
507
-
508
- # An allowlist entry can only carry whitespace-free tokens:
509
- # normalize_allowlist splits entries on whitespace, so an argv token
510
- # containing spaces ("feature x") can never be matched by an entry.
511
- # Prefix up to (excluding) the first such token.
512
- def allowlist_entry_for_argv(argv)
513
- prefix = []
514
- Array(argv).each do |token|
515
- break if token.to_s.match?(/\s/)
516
-
517
- prefix << token
518
- end
519
- prefix.empty? ? Array(argv).first.to_s : prefix.join(" ")
520
- end
521
-
522
- # Display-only rendering: collapse newlines, single-quote tokens that
523
- # contain whitespace, hard-cap length. Shellwords.escape would
524
- # backslash-quote every token (noise on Windows paths) — quote
525
- # conditionally instead.
526
- def segment_display(argv)
527
- text = argv.map { |t| t.to_s.tr("\r\n", " ") }
528
- .map { |t| t.match?(/\s/) ? "'#{t}'" : t }
529
- .join(" ")
530
- text.length > SEGMENT_DISPLAY_CAP ? "#{text[0, SEGMENT_DISPLAY_CAP - 1]}..." : text
531
- end
532
-
533
416
  def segment_count(report)
534
417
  report ? report[:segments].size : 0
535
418
  end
@@ -1,6 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "audit_log"
4
+ require_relative "../storage/layout"
4
5
  require_relative "allowlist"
5
6
  require_relative "command_gate"
6
7
  require_relative "path_policy"
@@ -49,6 +50,9 @@ module Rubik
49
50
  def self.for_config(config, root_dir: nil, shell: nil)
50
51
  return new if config.nil? || !config.respond_to?(:fetch)
51
52
 
53
+ # Deliberate bare fetch (not Layout.config_get): config_get folds an
54
+ # explicit nil into the default, but here an explicit nil DISABLES
55
+ # auditing — the absent/nil distinction is load-bearing.
52
56
  raw_audit = config.fetch("security.audit_log_path", default_audit_log_path)
53
57
  audit_path =
54
58
  case raw_audit
@@ -59,7 +63,7 @@ module Rubik
59
63
  # turns "!config set security.audit_log_path false" into boolean
60
64
  # false, which would otherwise reach log_audit and die in a
61
65
  # swallowed TypeError — silently dropping every audit event.
62
- warn "[Guard] security.audit_log_path has non-path value #{raw_audit.inspect}; auditing disabled"
66
+ Rubik::Log.warn(:security, "[Guard] security.audit_log_path has non-path value #{raw_audit.inspect}; auditing disabled")
63
67
  nil
64
68
  end
65
69
 
@@ -67,9 +71,9 @@ module Rubik
67
71
 
68
72
  new(
69
73
  audit_log_path: audit_path,
70
- command_allowlist: Array(config.fetch("security.command_allowlist", [])),
74
+ command_allowlist: Array(Rubik::Storage::Layout.config_get(config, "security.command_allowlist", [])),
71
75
  # Stringy "false" from persisted config must disable probes too.
72
- allow_safe_probes: config.fetch("security.allow_safe_probes", true).to_s.downcase != "false",
76
+ allow_safe_probes: Rubik::Storage::Layout.config_get(config, "security.allow_safe_probes", true).to_s.downcase != "false",
73
77
  root_dir: effective_root,
74
78
  shell: shell
75
79
  )