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
@@ -0,0 +1,591 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "shellwords"
4
+ require_relative "allowlist"
5
+ require_relative "classifier"
6
+ require_relative "errors"
7
+
8
+ module Rubik
9
+ module Security
10
+ # The shell-command gate, split out of Guard (#403): verdicts on shell
11
+ # command strings — classifier orchestration, the safe-probe exemption,
12
+ # workspace-trust recognition, interactive operator approval, the
13
+ # un-bypassable catastrophic fallback regex, and the blocked-segment
14
+ # guidance evidence. Owns the live-reconfigurable probe/root/shell
15
+ # state; allowlist verdicts delegate to the injected Allowlist,
16
+ # critical-path writes to the injected PathPolicy, and every decision
17
+ # is audit-logged through the injected AuditLog.
18
+ class CommandGate
19
+ # Pipe-to-interpreter (the curl|bash RCE shape). This pattern lives in
20
+ # the UN-BYPASSABLE fallback gate: verify_command_fallback_regex! runs
21
+ # even on allowlisted and safe-probe commands, so anything it matches
22
+ # cannot be allowlisted away — keep any widening surgical. The
23
+ # intermediaries between the pipe and the interpreter are flag-less
24
+ # (sudo bash, env sh); flag-bearing forms (sudo -u root bash) are
25
+ # already blocked earlier by the AST classifier's delegation rules
26
+ # when it is healthy, so the fallback does not need to cover them.
27
+ # Word boundaries on both ends also stop substring matches like
28
+ # "mycurl ... | sh" or "| shadowtool".
29
+ PIPE_TO_INTERPRETER_PATTERN = /
30
+ \b(?:curl|wget)\b.*\|\s*
31
+ (?:(?:sudo|doas|env|nohup|nice|stdbuf|xargs)\s+)*
32
+ (?:bash|zsh|dash|ksh|fish|sh|pwsh|python\d?|ruby|perl|node|php|lua)\b
33
+ /xi
34
+
35
+ DANGEROUS_COMMAND_PATTERNS = [
36
+ Regexp.new(
37
+ 'rm\s+(?:-[a-z0-9-]+\s+)*(?:-[a-z0-9]*r[a-z0-9]*f[a-z0-9]*|-[a-z0-9]*f[a-z0-9]*r[a-z0-9]*|' \
38
+ '(?:(?:-[a-z0-9]*r[a-z0-9]*|--recursive)\s+(?:-[a-z0-9]*f[a-z0-9]*|--force))|' \
39
+ '(?:(?:-[a-z0-9]*f[a-z0-9]*|--force)\s+(?:-[a-z0-9]*r[a-z0-9]*|--recursive)))' \
40
+ '\s+(?:-[a-z0-9-]+\s+)*(?:--\s+)?/(?:\*|\.+(?![a-zA-Z0-9_-])|(?![a-zA-Z0-9_.-]))',
41
+ Regexp::IGNORECASE
42
+ ),
43
+ PIPE_TO_INTERPRETER_PATTERN,
44
+ /:\(\)\{\s*:\|:&\s*\};:/, # fork bomb
45
+ %r{\bdd\s+.*(?:if=|of=/dev/)}i,
46
+ /\bmkfs(?:\.\w+)?\b/i,
47
+ /\b(?:shutdown|reboot|poweroff|halt)\b(?:\s+.*)?/i,
48
+ /\b(?:Format-Volume|Clear-Disk|Initialize-Disk|Remove-Partition|Stop-Computer|Restart-Computer)\b/i,
49
+ /\bdiskpart\b/i,
50
+ /\brm\s+.*--no-preserve-root/i,
51
+ %r{del\s+.*/s.*[a-z]:\\}i,
52
+ %r{erase\s+.*/s.*[a-z]:\\}i,
53
+ %r{rmdir\s+.*/s.*[a-z]:\\}i,
54
+ %r{rd\s+.*/s.*[a-z]:\\}i,
55
+ /format\s+[a-z]:/i,
56
+ /Remove-Item\s+.*-Recurse.*[a-z]:\\/i,
57
+ /%0\|%0/
58
+ ].freeze
59
+
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
+ # Salt version/help probe'ları (Plan: safe-probe muafiyeti): a command
67
+ # whose ONLY arguments are these flags is read-only by construction.
68
+ SAFE_PROBE_FLAGS = ["--version", "-v", "--help", "-h"].freeze
69
+
70
+ attr_accessor :shell, :root_dir
71
+
72
+ def initialize(allowlist:, audit:, path_policy:, allow_safe_probes: true,
73
+ root_dir: nil, shell: nil)
74
+ @allowlist = allowlist
75
+ @audit = audit
76
+ @path_policy = path_policy
77
+ @allow_safe_probes = allow_safe_probes == true
78
+ @root_dir = root_dir
79
+ @shell = shell
80
+ end
81
+
82
+ def workspace_trust_candidate_allowed?(cmd_str, ast = nil)
83
+ return false if cmd_str.to_s.match?(Allowlist::RAW_ALLOWLIST_UNSAFE_PATTERN)
84
+
85
+ ast ||= begin
86
+ Rubik::Security::Classifier.classify(cmd_str.to_s)
87
+ rescue StandardError
88
+ nil
89
+ end
90
+ return false unless ast
91
+ return false if ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.any?
92
+ return false unless ast.respond_to?(:commands) && ast.commands.to_a.size == 1
93
+
94
+ cmd = ast.commands.first
95
+ return false if cmd.respond_to?(:inner_commands) && cmd.inner_commands && !cmd.inner_commands.empty?
96
+
97
+ effective_root = @root_dir || Dir.pwd
98
+ return false unless defined?(Rubik::CLI::WorkspaceTrust) && Rubik::CLI::WorkspaceTrust.trusted?(effective_root)
99
+ return false unless defined?(Rubik::Runtime::Discovery)
100
+
101
+ Rubik::Runtime::Discovery.recognized_candidate?(cmd_str, root_dir: effective_root)
102
+ end
103
+
104
+ # security.allow_safe_probes — operator-managed toggle (live-reconfigurable
105
+ # via ConfigWiring, zero restart). Default ON.
106
+ def allow_safe_probes?
107
+ @allow_safe_probes
108
+ end
109
+
110
+ def allow_safe_probes=(val)
111
+ # Accept both booleans and stringy config values ("true"/"false").
112
+ @allow_safe_probes = val == true || val.to_s.downcase == "true"
113
+ end
114
+
115
+ # True when the command's arguments are exclusively version/help flags
116
+ # (e.g. `bash --version`, `node -v`, `git --help`); no other arguments.
117
+ # Gate is the operator toggle; shape detection lives in probe_shape? so
118
+ # blocked-error annotation can label probe-shaped commands even when the
119
+ # exemption is disabled — otherwise the variant-(a) probe guidance would
120
+ # be unreachable (a probe only reaches the block path when disabled).
121
+ def safe_probe?(cmd_str)
122
+ return false unless @allow_safe_probes
123
+
124
+ probe_shape?(cmd_str)
125
+ end
126
+
127
+ def probe_shape?(cmd_str)
128
+ str = cmd_str.to_s
129
+ return false if str.match?(/[\r\n]/)
130
+
131
+ tokens = shell_tokens(str)
132
+ return false unless tokens
133
+ return false if tokens.size < 2
134
+
135
+ tokens[1..].all? { |t| SAFE_PROBE_FLAGS.include?(t) }
136
+ end
137
+
138
+ # allow_unknown: synthesis verification no longer routes through the
139
+ # shell gate (it has its own deny layers: DANGEROUS_SYNTHESIS_PATTERNS
140
+ # + AST walk), so no production caller passes true today. The flag
141
+ # remains a tested seam for future in-gate verifiers of non-shell
142
+ # source; shell-gate callers must keep the default: an UNKNOWN verdict
143
+ # means an unvetted binary, and a binary the database cannot classify
144
+ # is exactly the one that must not run without operator approval.
145
+ def verify_command_safety!(cmd, shell: nil, allow_unknown: false)
146
+ cmd_str = cmd.to_s
147
+ begin
148
+ ast = Rubik::Security::Classifier.classify(cmd_str, shell: shell)
149
+ @path_policy.check_critical_path_writes!(ast, cmd_str)
150
+ if ast.classification == :dangerous
151
+ # Safe-probe exemption (highest-priority friction fix): run the
152
+ # catastrophic fallback regex first — it never loosens.
153
+ # Strictly single, isolated command without inner commands or chains.
154
+ if isolated_single_command?(ast) && safe_probe?(cmd_str)
155
+ verify_command_fallback_regex!(cmd_str)
156
+ @audit.log_audit("safe_probe", command: cmd_str, reason: "safe_probe_exemption")
157
+ return true
158
+ end
159
+ walk_reason = dangerous_reason(ast.commands)
160
+ # Expression-level elevation marks no single command dangerous —
161
+ # the per-command walk bottoms out at its sentinel while the
162
+ # composed evidence travels on the ExpressionResult itself.
163
+ expression_reason = walk_reason == "dangerous_ast" ? expression_level_reason(ast) : nil
164
+ return true if operator_allowlist_pass?(ast, cmd_str)
165
+
166
+ block_dangerous_command!(ast, cmd_str, reason: expression_reason || walk_reason, expression_reason: expression_reason)
167
+ end
168
+
169
+ # UNKNOWN is fail-closed, not pass-through: the matcher rates every
170
+ # database-less binary unknown/high, so letting it fall through to
171
+ # the catastrophic-only regex would run `socat`/`nmap`/any unlisted
172
+ # tool with zero approval while the tool copy advertises fail-closed.
173
+ # Allowlist rescue unchanged (every top-level segment must match).
174
+ # No safe-probe exemption: an unknown binary's --version still
175
+ # executes an unvetted binary — the allowlist is the valve.
176
+ if ast.classification == :unknown && !allow_unknown
177
+ return true if operator_allowlist_pass?(ast, cmd_str)
178
+
179
+ # Workspace Trust Discovery Recognition Gate:
180
+ if workspace_trust_candidate_allowed?(cmd_str, ast)
181
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
182
+ verify_command_fallback_regex!(cmd_str)
183
+ return true
184
+ end
185
+
186
+ # Interactive operator approval gate (Antigravity-style single keypress)
187
+ return true if operator_interactive_approval?(cmd_str, shell)
188
+
189
+ block_unknown_command!(cmd_str)
190
+ end
191
+
192
+ # Ambiguous parse (tree-sitter syntax errors) is a classification
193
+ # failure, not a pass: the walk cannot vouch for the whole
194
+ # expression, so a safe-looking partial verdict must not fall
195
+ # through to the catastrophic-only regex gate. The allowlist stays
196
+ # the valve because a real AST exists — every segment is checked
197
+ # against the operator entries.
198
+ if !allow_unknown && ast.parse_warnings.to_a.any?
199
+ return true if operator_allowlist_pass?(ast, cmd_str)
200
+
201
+ block_ambiguous_parse!(ast, cmd_str)
202
+ end
203
+
204
+ return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
205
+ rescue BlockedWriteError
206
+ raise
207
+ rescue StandardError => e
208
+ # Unconditional warn + audit trail: a classifier crash is a
209
+ # security-observable downgrade nobody should need RUBIK_DEBUG to
210
+ # notice. The shell gate fails closed — an exception must never
211
+ # mint execution permission; the operator allowlist is the one
212
+ # sanctioned valve. The allow_unknown seam (no production caller
213
+ # today) keeps flowing into its own deny layers
214
+ # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
215
+ if allow_unknown
216
+ warn "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}"
217
+ @audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
218
+ decision: "synthesis_layers")
219
+ else
220
+ warn "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}"
221
+ block_on_classifier_failure!(cmd_str, e)
222
+ end
223
+ end
224
+
225
+ verify_command_fallback_regex!(cmd_str)
226
+ end
227
+
228
+ def verify_command_fallback_regex!(cmd_str)
229
+ return true unless DANGEROUS_COMMAND_PATTERNS.any? { |p| cmd_str.match?(p) }
230
+
231
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "dangerous_pattern")
232
+ raise BlockedWriteError.new(
233
+ "Dangerous command execution blocked: #{cmd_str}",
234
+ kind: :dangerous_pattern,
235
+ blocked_command: cmd_str,
236
+ rule_name: "dangerous_pattern"
237
+ )
238
+ end
239
+
240
+ private
241
+
242
+ # Shellword tokenization for probe-shape detection; nil when the string
243
+ # has none (unbalanced quotes). The caller fails closed on nil rather
244
+ # than guessing with whitespace splitting — a quote-corrupted command
245
+ # (rm "--version) must not shape as a read-only probe.
246
+ def shell_tokens(str)
247
+ Shellwords.split(str)
248
+ rescue ArgumentError
249
+ nil
250
+ end
251
+
252
+ # Single home for the operator allowlist valve, evaluated fail-closed:
253
+ # a bug in the gate itself must deny, never pass, and must stay loud on
254
+ # $stderr — a security-observable downgrade nobody should need
255
+ # RUBIK_DEBUG to notice. The catastrophic fallback regex still runs
256
+ # after every allowlisted pass; allowlisting never bypasses it.
257
+ # raw: the classifier-crash gate authorizes against the raw command
258
+ # string because no AST exists to evaluate.
259
+ def allowlisted_fail_closed(ast, cmd_str, raw: false)
260
+ if raw
261
+ @allowlist.command_allowlisted_raw?(cmd_str)
262
+ else
263
+ @allowlist.command_allowlisted?(ast, cmd_str: cmd_str)
264
+ end
265
+ rescue StandardError => e
266
+ warn "[Guard] #{'raw ' if raw}allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
267
+ false
268
+ end
269
+
270
+ # AST fast-path check for the safe-probe exemption: strictly single,
271
+ # isolated command without inner commands or chains.
272
+ def isolated_single_command?(ast)
273
+ ast.respond_to?(:commands) && ast.commands.to_a.size == 1 &&
274
+ ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.empty? &&
275
+ (!ast.commands.first.respond_to?(:inner_commands) || ast.commands.first.inner_commands.nil? || ast.commands.first.inner_commands.empty?)
276
+ end
277
+
278
+ # Operator allowlist valve pass, shared by the dangerous / unknown /
279
+ # ambiguous-parse block paths. Fail-closed default: the entry must
280
+ # cover EVERY dangerous segment recursively; catastrophic fallback
281
+ # regex still runs afterwards — allowlisting never bypasses it.
282
+ # A bug in the gate itself must fail closed, not fall through to
283
+ # the regex-only downgrade below. Returns true only after the
284
+ # allowed_command audit and the fallback regex have run.
285
+ def operator_allowlist_pass?(ast, cmd_str)
286
+ return false unless allowlisted_fail_closed(ast, cmd_str)
287
+
288
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist")
289
+ verify_command_fallback_regex!(cmd_str)
290
+ true
291
+ end
292
+
293
+ # Report assembly for the dangerous-classification block path, 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
+ dangerous_segment_report(commands)
299
+ rescue StandardError => e
300
+ warn "[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
+
377
+ def dangerous_reason(commands)
378
+ commands.each do |c|
379
+ next unless c.classification == :dangerous
380
+
381
+ # Dangerous INNERS only: recursing into safe inners would shadow
382
+ # the command's own reason with the "dangerous_ast" sentinel —
383
+ # which must stay exclusive to expression-level elevations (the
384
+ # raise site uses it as the expression-case signal).
385
+ inner = nil
386
+ inner = dangerous_reason(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any? { |i| i.classification == :dangerous }
387
+ return inner || (c.respond_to?(:classification_reason) && c.classification_reason) || "dangerous_command"
388
+ end
389
+ "dangerous_ast"
390
+ end
391
+
392
+ # Innermost dangerous segment's rule name — surfaced in blocked-command
393
+ # guidance so the operator knows exactly which rule matched and what
394
+ # prefix to allowlist (e.g. rule: bash, rule: rm).
395
+ def dangerous_rule_name(commands)
396
+ commands.each do |c|
397
+ next unless c.classification == :dangerous
398
+
399
+ inner = dangerous_rule_name(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any?
400
+ return inner || (c.respond_to?(:matched_rule) && c.matched_rule)
401
+ end
402
+ nil
403
+ end
404
+
405
+ # Expression-level elevations (Engine#build_expression_result) are
406
+ # dangerous with no dangerous command to name — the composed evidence
407
+ # rides on the ExpressionResult itself. Presence (non-nil) is the
408
+ # expression-case signal.
409
+ def expression_level_reason(ast)
410
+ return nil unless ast.respond_to?(:classification_reason)
411
+
412
+ reason = ast.classification_reason.to_s.strip
413
+ reason.empty? ? nil : reason
414
+ end
415
+
416
+ # Structured report for wrapper/multi-segment blocked-command guidance:
417
+ # every innermost dangerous segment with its trigger, the sibling
418
+ # commands that passed, a one-line wrapper preview, and the allowlist
419
+ # entries that would actually open the gate. Plain data only —
420
+ # BlockedWriteError must stay loadable without the classifier stack.
421
+ # nil when no single command is dangerous (expression-level elevations
422
+ # keep the scalar rule_name guidance path).
423
+ def dangerous_segment_report(commands)
424
+ segments = []
425
+ safe = []
426
+ safe_top_argv = []
427
+ wrappers = []
428
+ collect_dangerous_units(commands, 0, segments, safe, safe_top_argv, wrappers)
429
+ return nil if segments.empty?
430
+
431
+ # The gate (command_allowlisted?) matches EVERY top-level command,
432
+ # safe ones included — the entry set must cover them all to be
433
+ # honest: wrapper prefix + top-level dangerous segments + top-level
434
+ # safe units.
435
+ entries = wrappers.map { |w| wrapper_allowlist_entry(w) }
436
+ entries += segments.select { |s| s[:depth].zero? }.map { |s| allowlist_entry_for_argv(s[:argv]) }
437
+ entries += safe_top_argv.map { |argv| allowlist_entry_for_argv(argv) }
438
+
439
+ {
440
+ segments: segments,
441
+ safe: safe.uniq,
442
+ wrapper_preview: wrappers.empty? ? nil : wrapper_preview(wrappers.first),
443
+ allowlist_entries: entries.uniq
444
+ }.freeze
445
+ end
446
+
447
+ # Depth-first walk over the classified command tree. A dangerous
448
+ # command whose danger comes from dangerous inners contributes those
449
+ # inner leaves instead of itself (bash -c "rm -rf /" reports the inner
450
+ # rm, not the wrapper); a dangerous leaf is a segment; non-dangerous
451
+ # leaves join the passed roll call. Top-level wrappers (dangerous only
452
+ # through their inners) are tracked separately for preview + hint;
453
+ # top-level safe units keep their argv for the gate-honest entry set.
454
+ def collect_dangerous_units(commands, depth, segments, safe, safe_top_argv, wrappers)
455
+ Array(commands).each do |c|
456
+ inners = Array(c.inner_commands)
457
+ before = segments.size
458
+ collect_dangerous_units(inners, depth + 1, segments, safe, safe_top_argv, wrappers)
459
+ added = segments.size - before
460
+
461
+ if c.classification == :dangerous
462
+ if added.positive?
463
+ wrappers << c if depth.zero?
464
+ else
465
+ segments << dangerous_segment_data(c, depth)
466
+ end
467
+ elsif inners.empty?
468
+ safe << safe_segment_name(c)
469
+ safe_top_argv << c.argv.dup if depth.zero?
470
+ end
471
+ end
472
+ end
473
+
474
+ def dangerous_segment_data(result, depth)
475
+ argv = Array(result.argv)
476
+ {
477
+ display: segment_display(display_tokens(argv, result)),
478
+ argv: argv.dup.freeze,
479
+ rule: result.matched_rule,
480
+ option: result.overriding_option,
481
+ reason: result.classification_reason,
482
+ depth: depth
483
+ }
484
+ end
485
+
486
+ # Redirect-bearing segments (delegated inners) render their effects,
487
+ # not just their argv: `echo pwned > /etc/shadow`, not `echo pwned`.
488
+ # Flat operator/target tokens keep segment_display's quoting correct;
489
+ # argv itself stays pure — allowlist entries derive from it.
490
+ def display_tokens(argv, result)
491
+ reds = result.respond_to?(:redirects) ? Array(result.redirects) : []
492
+ reds.empty? ? argv : argv + reds.flat_map { |r| [r.operator, r.target] }
493
+ end
494
+
495
+ # Subcommand-aware roll call of the units that passed ("git checkout",
496
+ # not just "git") — matches the operator's mental model of the script.
497
+ def safe_segment_name(result)
498
+ result.command.join(" ")
499
+ end
500
+
501
+ # One-line wrapper preview for the guidance first line. The delegated
502
+ # payload (the whole -c script) is the argv token that contains
503
+ # whitespace — elide it so the full script is never re-embedded in the
504
+ # message (the defect this report exists to fix).
505
+ def wrapper_preview(result)
506
+ argv = Array(result.argv)
507
+ tokens = argv.dup
508
+ tokens[-1] = "'...'" if tokens.size > 1 && tokens[-1].to_s.match?(/\s/)
509
+ preview = segment_display(tokens)
510
+ preview.length > WRAPPER_PREVIEW_CAP ? "#{preview[0, WRAPPER_PREVIEW_CAP - 1]}..." : preview
511
+ end
512
+
513
+ # Shortest top-level argv prefix that actually satisfies the gate's
514
+ # token-prefix match (command_allowlisted?): the wrapper binary up to
515
+ # and including its delegation flag for flag-value payloads
516
+ # ("bash -c", "bash -e -c"), the bare binary for rest-argv wrappers
517
+ # ("sudo", "xargs"). Deriving it from delegation_source keeps the hint
518
+ # gate-honest for flag permutations a naive first-two-tokens guess
519
+ # would miss.
520
+ def wrapper_allowlist_entry(wrapper)
521
+ argv = Array(wrapper.argv)
522
+ return argv.first.to_s if argv.size <= 1
523
+
524
+ first_inner = Array(wrapper.inner_commands).first
525
+ if first_inner&.delegation_mode.to_s == "flag_value_is_expression"
526
+ idx = argv.index(first_inner.delegation_source)
527
+ return argv[0..idx].join(" ") if idx&.positive?
528
+ end
529
+ argv.first.to_s
530
+ end
531
+
532
+ # An allowlist entry can only carry whitespace-free tokens:
533
+ # normalize_allowlist splits entries on whitespace, so an argv token
534
+ # containing spaces ("feature x") can never be matched by an entry.
535
+ # Prefix up to (excluding) the first such token.
536
+ def allowlist_entry_for_argv(argv)
537
+ prefix = []
538
+ Array(argv).each do |token|
539
+ break if token.to_s.match?(/\s/)
540
+
541
+ prefix << token
542
+ end
543
+ prefix.empty? ? Array(argv).first.to_s : prefix.join(" ")
544
+ end
545
+
546
+ # Display-only rendering: collapse newlines, single-quote tokens that
547
+ # contain whitespace, hard-cap length. Shellwords.escape would
548
+ # backslash-quote every token (noise on Windows paths) — quote
549
+ # conditionally instead.
550
+ def segment_display(argv)
551
+ text = argv.map { |t| t.to_s.tr("\r\n", " ") }
552
+ .map { |t| t.match?(/\s/) ? "'#{t}'" : t }
553
+ .join(" ")
554
+ text.length > SEGMENT_DISPLAY_CAP ? "#{text[0, SEGMENT_DISPLAY_CAP - 1]}..." : text
555
+ end
556
+
557
+ def segment_count(report)
558
+ report ? report[:segments].size : 0
559
+ end
560
+
561
+ # Classifier-crash gate for the shell path: structured block by
562
+ # default, one sanctioned rescue — an operator allowlist entry
563
+ # covering the exact single-command prefix (the same explicit
564
+ # authorization contract as the unknown-command gate). The
565
+ # catastrophic fallback regex still runs afterwards on the rescue
566
+ # path; on the block path it gets first refusal so a catastrophic
567
+ # command keeps its precise :dangerous_pattern reason.
568
+ def block_on_classifier_failure!(cmd_str, error)
569
+ allowlisted = allowlisted_fail_closed(cmd_str, cmd_str, raw: true)
570
+ @audit.log_audit("classifier_error", command: cmd_str, reason: "#{error.class}: #{error.message}",
571
+ decision: allowlisted ? "operator_allowlist" : "blocked")
572
+
573
+ if allowlisted
574
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist_classifier_error")
575
+ return
576
+ end
577
+
578
+ verify_command_fallback_regex!(cmd_str)
579
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "classifier_error")
580
+ raise BlockedWriteError.new(
581
+ "AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{cmd_str}",
582
+ kind: :classifier_error,
583
+ blocked_command: cmd_str,
584
+ rule_name: "classifier_error",
585
+ probe_like: probe_shape?(cmd_str),
586
+ segment_report: nil
587
+ )
588
+ end
589
+ end
590
+ end
591
+ end