rubik 0.9.0 → 0.9.1

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 (57) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +108 -43
  4. data/README.md +5 -1
  5. data/lib/rubik/adapter/base.rb +19 -0
  6. data/lib/rubik/adapter/generic.rb +0 -14
  7. data/lib/rubik/adapter/node.rb +2 -0
  8. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  9. data/lib/rubik/cli/workspace_trust.rb +16 -0
  10. data/lib/rubik/config/defaults.rb +23 -0
  11. data/lib/rubik/config/store.rb +14 -0
  12. data/lib/rubik/kernel/dispatcher.rb +4 -4
  13. data/lib/rubik/log.rb +2 -1
  14. data/lib/rubik/lsp/client.rb +83 -180
  15. data/lib/rubik/lsp/document_store.rb +209 -0
  16. data/lib/rubik/mcp/client.rb +4 -3
  17. data/lib/rubik/mcp/manager.rb +6 -2
  18. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  19. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  20. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  21. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  22. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  23. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  24. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  25. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  26. data/lib/rubik/orchestrator.rb +1 -0
  27. data/lib/rubik/platform.rb +15 -0
  28. data/lib/rubik/plugin/storage.rb +20 -29
  29. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  30. data/lib/rubik/repl/commands/agent_execution.rb +7 -470
  31. data/lib/rubik/repl/commands/buffer.rb +1 -1
  32. data/lib/rubik/repl/commands/lsp.rb +1 -1
  33. data/lib/rubik/repl/input_loop.rb +1 -1
  34. data/lib/rubik/repl/lifecycle.rb +28 -0
  35. data/lib/rubik/runtime/manifest_store.rb +116 -0
  36. data/lib/rubik/runtime/overlay_storage.rb +247 -196
  37. data/lib/rubik/runtime/task_manager.rb +7 -2
  38. data/lib/rubik/runtime.rb +1 -0
  39. data/lib/rubik/security/allowlist.rb +167 -0
  40. data/lib/rubik/security/audit_log.rb +72 -0
  41. data/lib/rubik/security/classifier/classifier.rb +8 -0
  42. data/lib/rubik/security/command_gate.rb +567 -0
  43. data/lib/rubik/security/guard.rb +88 -1075
  44. data/lib/rubik/security/path_policy.rb +117 -0
  45. data/lib/rubik/security/synthesis_gate.rb +300 -0
  46. data/lib/rubik/security.rb +5 -0
  47. data/lib/rubik/storage/ranking.rb +113 -0
  48. data/lib/rubik/storage/store.rb +2 -92
  49. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  50. data/lib/rubik/tools/builtins/grep.rb +2 -3
  51. data/lib/rubik/tools/builtins/lifecycle.rb +90 -87
  52. data/lib/rubik/tools/builtins/synthesis.rb +3 -0
  53. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  54. data/lib/rubik/tools/native_search.rb +2 -1
  55. data/lib/rubik/tools/truncator.rb +25 -0
  56. data/lib/rubik/version.rb +1 -1
  57. metadata +11 -1
@@ -0,0 +1,567 @@
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
+ 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)
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
+ 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
+ )
201
+ end
202
+
203
+ # UNKNOWN is fail-closed, not pass-through: the matcher rates every
204
+ # database-less binary unknown/high, so letting it fall through to
205
+ # the catastrophic-only regex would run `socat`/`nmap`/any unlisted
206
+ # tool with zero approval while the tool copy advertises fail-closed.
207
+ # Allowlist rescue unchanged (every top-level segment must match).
208
+ # No safe-probe exemption: an unknown binary's --version still
209
+ # executes an unvetted binary — the allowlist is the valve.
210
+ 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
219
+
220
+ # Workspace Trust Discovery Recognition Gate:
221
+ if workspace_trust_candidate_allowed?(cmd_str, ast)
222
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
223
+ verify_command_fallback_regex!(cmd_str)
224
+ return true
225
+ end
226
+
227
+ # 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)
232
+
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
+ )
260
+ end
261
+
262
+ # Ambiguous parse (tree-sitter syntax errors) is a classification
263
+ # failure, not a pass: the walk cannot vouch for the whole
264
+ # expression, so a safe-looking partial verdict must not fall
265
+ # through to the catastrophic-only regex gate. The allowlist stays
266
+ # the valve because a real AST exists — every segment is checked
267
+ # against the operator entries.
268
+ 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
+ )
285
+ end
286
+
287
+ return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
288
+ rescue BlockedWriteError
289
+ raise
290
+ rescue StandardError => e
291
+ # Unconditional warn + audit trail: a classifier crash is a
292
+ # security-observable downgrade nobody should need RUBIK_DEBUG to
293
+ # notice. The shell gate fails closed — an exception must never
294
+ # mint execution permission; the operator allowlist is the one
295
+ # sanctioned valve. The allow_unknown seam (no production caller
296
+ # today) keeps flowing into its own deny layers
297
+ # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
298
+ if allow_unknown
299
+ warn "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}"
300
+ @audit.log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
301
+ decision: "synthesis_layers")
302
+ else
303
+ warn "[WARN] AST classification error, failing closed: #{e.class}: #{e.message}"
304
+ block_on_classifier_failure!(cmd_str, e)
305
+ end
306
+ end
307
+
308
+ verify_command_fallback_regex!(cmd_str)
309
+ end
310
+
311
+ def verify_command_fallback_regex!(cmd_str)
312
+ return true unless DANGEROUS_COMMAND_PATTERNS.any? { |p| cmd_str.match?(p) }
313
+
314
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "dangerous_pattern")
315
+ raise BlockedWriteError.new(
316
+ "Dangerous command execution blocked: #{cmd_str}",
317
+ kind: :dangerous_pattern,
318
+ blocked_command: cmd_str,
319
+ rule_name: "dangerous_pattern"
320
+ )
321
+ end
322
+
323
+ private
324
+
325
+ # Shellword tokenization for probe-shape detection; nil when the string
326
+ # has none (unbalanced quotes). The caller fails closed on nil rather
327
+ # than guessing with whitespace splitting — a quote-corrupted command
328
+ # (rm "--version) must not shape as a read-only probe.
329
+ def shell_tokens(str)
330
+ Shellwords.split(str)
331
+ rescue ArgumentError
332
+ nil
333
+ end
334
+
335
+ # Single home for the operator allowlist valve, evaluated fail-closed:
336
+ # a bug in the gate itself must deny, never pass, and must stay loud on
337
+ # $stderr — a security-observable downgrade nobody should need
338
+ # RUBIK_DEBUG to notice. The catastrophic fallback regex still runs
339
+ # after every allowlisted pass; allowlisting never bypasses it.
340
+ # raw: the classifier-crash gate authorizes against the raw command
341
+ # string because no AST exists to evaluate.
342
+ def allowlisted_fail_closed(ast, cmd_str, raw: false)
343
+ if raw
344
+ @allowlist.command_allowlisted_raw?(cmd_str)
345
+ else
346
+ @allowlist.command_allowlisted?(ast, cmd_str: cmd_str)
347
+ end
348
+ rescue StandardError => e
349
+ warn "[Guard] #{'raw ' if raw}allowlist evaluation failed, failing closed: #{e.class}: #{e.message}"
350
+ false
351
+ end
352
+
353
+ def dangerous_reason(commands)
354
+ commands.each do |c|
355
+ next unless c.classification == :dangerous
356
+
357
+ # Dangerous INNERS only: recursing into safe inners would shadow
358
+ # the command's own reason with the "dangerous_ast" sentinel —
359
+ # which must stay exclusive to expression-level elevations (the
360
+ # raise site uses it as the expression-case signal).
361
+ inner = nil
362
+ inner = dangerous_reason(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any? { |i| i.classification == :dangerous }
363
+ return inner || (c.respond_to?(:classification_reason) && c.classification_reason) || "dangerous_command"
364
+ end
365
+ "dangerous_ast"
366
+ end
367
+
368
+ # Innermost dangerous segment's rule name — surfaced in blocked-command
369
+ # guidance so the operator knows exactly which rule matched and what
370
+ # prefix to allowlist (e.g. rule: bash, rule: rm).
371
+ def dangerous_rule_name(commands)
372
+ commands.each do |c|
373
+ next unless c.classification == :dangerous
374
+
375
+ inner = dangerous_rule_name(c.inner_commands) if c.respond_to?(:inner_commands) && c.inner_commands&.any?
376
+ return inner || (c.respond_to?(:matched_rule) && c.matched_rule)
377
+ end
378
+ nil
379
+ end
380
+
381
+ # Expression-level elevations (Engine#build_expression_result) are
382
+ # dangerous with no dangerous command to name — the composed evidence
383
+ # rides on the ExpressionResult itself. Presence (non-nil) is the
384
+ # expression-case signal.
385
+ def expression_level_reason(ast)
386
+ return nil unless ast.respond_to?(:classification_reason)
387
+
388
+ reason = ast.classification_reason.to_s.strip
389
+ reason.empty? ? nil : reason
390
+ end
391
+
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
+ def segment_count(report)
534
+ report ? report[:segments].size : 0
535
+ end
536
+
537
+ # Classifier-crash gate for the shell path: structured block by
538
+ # default, one sanctioned rescue — an operator allowlist entry
539
+ # covering the exact single-command prefix (the same explicit
540
+ # authorization contract as the unknown-command gate). The
541
+ # catastrophic fallback regex still runs afterwards on the rescue
542
+ # path; on the block path it gets first refusal so a catastrophic
543
+ # command keeps its precise :dangerous_pattern reason.
544
+ def block_on_classifier_failure!(cmd_str, error)
545
+ allowlisted = allowlisted_fail_closed(cmd_str, cmd_str, raw: true)
546
+ @audit.log_audit("classifier_error", command: cmd_str, reason: "#{error.class}: #{error.message}",
547
+ decision: allowlisted ? "operator_allowlist" : "blocked")
548
+
549
+ if allowlisted
550
+ @audit.log_audit("allowed_command", command: cmd_str, reason: "operator_allowlist_classifier_error")
551
+ return
552
+ end
553
+
554
+ verify_command_fallback_regex!(cmd_str)
555
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "classifier_error")
556
+ raise BlockedWriteError.new(
557
+ "AST evaluation failed, so the command could not be classified; execution blocked (fail-closed): #{cmd_str}",
558
+ kind: :classifier_error,
559
+ blocked_command: cmd_str,
560
+ rule_name: "classifier_error",
561
+ probe_like: probe_shape?(cmd_str),
562
+ segment_report: nil
563
+ )
564
+ end
565
+ end
566
+ end
567
+ end