rubik 0.13.0 → 0.15.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 (131) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +1 -1
  3. data/CHANGELOG.md +122 -1
  4. data/lib/rubik/adapter/node.rb +4 -1
  5. data/lib/rubik/ast/c_extractor.rb +1 -1
  6. data/lib/rubik/ast/fallback_cleaner.rb +6 -1
  7. data/lib/rubik/ast/graph.rb +38 -57
  8. data/lib/rubik/ast/graph_extensions.rb +57 -15
  9. data/lib/rubik/ast/ruby_extractor.rb +16 -6
  10. data/lib/rubik/ast/treesitter/c_walker.rb +11 -3
  11. data/lib/rubik/buffer/manager.rb +38 -11
  12. data/lib/rubik/buffer/snapshot.rb +116 -28
  13. data/lib/rubik/cli/connect.rb +3 -5
  14. data/lib/rubik/config/defaults.rb +3 -7
  15. data/lib/rubik/config/env_guard.rb +43 -0
  16. data/lib/rubik/config/schema.rb +7 -1
  17. data/lib/rubik/config/scoped.rb +12 -5
  18. data/lib/rubik/config/secret_policy.rb +6 -5
  19. data/lib/rubik/config.rb +1 -1
  20. data/lib/rubik/connect/models_dev.rb +11 -0
  21. data/lib/rubik/connect/probes.rb +9 -2
  22. data/lib/rubik/connect/wizard.rb +117 -57
  23. data/lib/rubik/context/repo_context_reader.rb +8 -4
  24. data/lib/rubik/diagnostics/collector.rb +25 -2
  25. data/lib/rubik/llm/chunk_assembler.rb +12 -1
  26. data/lib/rubik/llm/client.rb +19 -0
  27. data/lib/rubik/llm/connection_pool.rb +7 -1
  28. data/lib/rubik/llm/formatter.rb +22 -2
  29. data/lib/rubik/llm/provider_key.rb +32 -0
  30. data/lib/rubik/llm/registry.rb +18 -2
  31. data/lib/rubik/llm/router.rb +27 -1
  32. data/lib/rubik/llm/session_header.rb +128 -0
  33. data/lib/rubik/llm/sse_parser.rb +57 -10
  34. data/lib/rubik/lsp/client.rb +244 -23
  35. data/lib/rubik/lsp/document_store.rb +6 -0
  36. data/lib/rubik/lsp/manager.rb +14 -0
  37. data/lib/rubik/lsp/transport.rb +34 -7
  38. data/lib/rubik/mcp/transport/stdio.rb +42 -4
  39. data/lib/rubik/orchestrator/continuation_manager.rb +68 -7
  40. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +18 -2
  41. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +13 -4
  42. data/lib/rubik/orchestrator/goal_ledger/validator.rb +46 -7
  43. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +8 -1
  44. data/lib/rubik/orchestrator/goal_session.rb +14 -14
  45. data/lib/rubik/orchestrator/goal_wait.rb +15 -9
  46. data/lib/rubik/orchestrator/loop.rb +39 -39
  47. data/lib/rubik/orchestrator/provider_resolver.rb +29 -6
  48. data/lib/rubik/orchestrator/step_executor.rb +17 -2
  49. data/lib/rubik/orchestrator/subagent/instance.rb +46 -5
  50. data/lib/rubik/orchestrator/subagent/lifecycle.rb +25 -25
  51. data/lib/rubik/orchestrator/subagent/messaging.rb +5 -1
  52. data/lib/rubik/orchestrator/subagent/narration.rb +2 -1
  53. data/lib/rubik/orchestrator/subagent/notices.rb +7 -3
  54. data/lib/rubik/orchestrator/subagent/questioner.rb +42 -4
  55. data/lib/rubik/orchestrator/subagent/reaper.rb +70 -20
  56. data/lib/rubik/orchestrator/subagent/start_gate.rb +1 -1
  57. data/lib/rubik/orchestrator/subagent/step_runner.rb +7 -7
  58. data/lib/rubik/orchestrator/subagent/supervisor.rb +21 -3
  59. data/lib/rubik/orchestrator/tool_call_id.rb +8 -4
  60. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +21 -5
  61. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +40 -5
  62. data/lib/rubik/orchestrator/turn_executor.rb +24 -8
  63. data/lib/rubik/platform/filesystem.rb +52 -24
  64. data/lib/rubik/platform/process.rb +32 -7
  65. data/lib/rubik/platform/sanitize.rb +17 -18
  66. data/lib/rubik/platform.rb +27 -0
  67. data/lib/rubik/plugin/storage.rb +34 -8
  68. data/lib/rubik/prompt/context_builder.rb +2 -1
  69. data/lib/rubik/prompt/doctrine.rb +3 -2
  70. data/lib/rubik/repair/loop.rb +22 -2
  71. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  72. data/lib/rubik/repl/commands/agent_execution.rb +20 -15
  73. data/lib/rubik/repl/commands/base.rb +7 -3
  74. data/lib/rubik/repl/commands/buffer.rb +21 -2
  75. data/lib/rubik/repl/commands/connect.rb +0 -1
  76. data/lib/rubik/repl/commands/lsp.rb +1 -1
  77. data/lib/rubik/repl/commands/plugins.rb +31 -31
  78. data/lib/rubik/repl/commands/session.rb +16 -6
  79. data/lib/rubik/repl/commands/workspace.rb +4 -4
  80. data/lib/rubik/repl/input_execution.rb +33 -32
  81. data/lib/rubik/repl/input_loop.rb +9 -4
  82. data/lib/rubik/repl/lifecycle.rb +1 -2
  83. data/lib/rubik/repl/notice_router.rb +11 -5
  84. data/lib/rubik/repl/paste_support.rb +1 -1
  85. data/lib/rubik/repl/prompt_grace.rb +3 -3
  86. data/lib/rubik/repl/service_catalog.rb +6 -2
  87. data/lib/rubik/repl/shell.rb +10 -2
  88. data/lib/rubik/repl/turn_recorder.rb +18 -4
  89. data/lib/rubik/runtime/context.rb +33 -27
  90. data/lib/rubik/runtime/manager.rb +23 -15
  91. data/lib/rubik/runtime/manifest_store.rb +7 -2
  92. data/lib/rubik/runtime/task_manager.rb +13 -10
  93. data/lib/rubik/sandbox/driver/base.rb +34 -0
  94. data/lib/rubik/sandbox/driver/bubblewrap.rb +60 -8
  95. data/lib/rubik/sandbox/driver/docker.rb +8 -0
  96. data/lib/rubik/sandbox/driver/podman.rb +8 -0
  97. data/lib/rubik/sandbox/driver/process.rb +29 -1
  98. data/lib/rubik/sandbox/runner.rb +9 -1
  99. data/lib/rubik/security/classifier/classifier.rb +147 -13
  100. data/lib/rubik/security/classifier/commands/docker.yaml +1 -1
  101. data/lib/rubik/security/classifier/commands/git.yaml +27 -1
  102. data/lib/rubik/security/classifier/commands/sed.yaml +3 -3
  103. data/lib/rubik/security/classifier/database.rb +2 -2
  104. data/lib/rubik/security/command_gate.rb +8 -1
  105. data/lib/rubik/security/path_policy.rb +28 -3
  106. data/lib/rubik/security/redactor.rb +62 -19
  107. data/lib/rubik/session/recorder.rb +27 -20
  108. data/lib/rubik/session/replayer.rb +29 -7
  109. data/lib/rubik/storage/store.rb +26 -5
  110. data/lib/rubik/tools/builtins/exec.rb +8 -2
  111. data/lib/rubik/tools/builtins/files.rb +8 -12
  112. data/lib/rubik/tools/builtins/grep.rb +3 -2
  113. data/lib/rubik/tools/builtins/interactive.rb +5 -2
  114. data/lib/rubik/tools/builtins/lsp.rb +59 -9
  115. data/lib/rubik/tools/builtins/send_message.rb +7 -2
  116. data/lib/rubik/tools/builtins/show_file.rb +1 -1
  117. data/lib/rubik/tools/builtins/synthesis.rb +4 -4
  118. data/lib/rubik/tools/preflight_runner.rb +4 -1
  119. data/lib/rubik/tools/result_normalizer.rb +1 -1
  120. data/lib/rubik/ui/banner.rb +3 -3
  121. data/lib/rubik/ui/dialog.rb +15 -8
  122. data/lib/rubik/ui/diff_viewer.rb +4 -4
  123. data/lib/rubik/ui/frame.rb +13 -3
  124. data/lib/rubik/ui/markdown_stream.rb +8 -2
  125. data/lib/rubik/ui/panel.rb +11 -11
  126. data/lib/rubik/ui/renderer.rb +10 -7
  127. data/lib/rubik/ui/spinner.rb +1 -1
  128. data/lib/rubik/ui/statusline.rb +3 -3
  129. data/lib/rubik/ui/theme.rb +1 -1
  130. data/lib/rubik/version.rb +1 -1
  131. metadata +4 -1
@@ -24,6 +24,25 @@ module Rubik
24
24
  READ_OPERATORS = ["<"].freeze
25
25
  # PERF: Hoist home token array to avoid per-path array allocations in system_path? check.
26
26
  HOME_TOKENS = ["~", "~/", "$HOME", "${HOME}"].freeze
27
+ # Variables whose VALUE the host command executes as a shell command
28
+ # (git ssh/editor/pager hooks, shell startup files, askpass helpers).
29
+ # An unclassifiable payload here must fail closed instead of hiding
30
+ # behind a clean outer allowlist entry (issue #540).
31
+ EXECUTED_ENV_VARS = [
32
+ "GIT_SSH_COMMAND", "GIT_EDITOR", "GIT_SEQUENCE_EDITOR", "GIT_EXTERNAL_DIFF",
33
+ "GIT_PAGER", "GIT_ASKPASS", "EDITOR", "VISUAL", "PAGER", "SHELL", "BASH_ENV", "ENV",
34
+ "SSH_ASKPASS", "SSH_COMMAND", "LESSOPEN"
35
+ ].freeze
36
+ EXECUTED_ENV_PREFIXES = ["GIT_CONFIG_"].freeze
37
+ # Pre-subcommand git config assignments that redirect execution
38
+ # (editors, hooks, pagers, ssh, aliases). Global-option stripping
39
+ # removes these before subcommand options are evaluated, so the
40
+ # Engine must gate them from the raw argv (#539 residual).
41
+ GIT_CONFIG_FLAGS = ["-c", "--config"].freeze
42
+ DANGEROUS_GIT_CONFIG_KEYS = [
43
+ "core.editor", "core.hookspath", "core.pager", "core.sshcommand",
44
+ "core.fsmonitor", "core.gitproxy", "diff.external"
45
+ ].freeze
27
46
 
28
47
  def self.default_database
29
48
  @default_database ||= CommandDatabase.new
@@ -82,6 +101,7 @@ module Rubik
82
101
  # as a sibling inner command BEFORE redirects/system-path checks
83
102
  # so the rest of the pipeline sees the elevation.
84
103
  result = apply_assignment_payloads(result, inv, parse_warnings)
104
+ result = apply_git_config_overrides(result, inv, parse_warnings)
85
105
 
86
106
  write_paths, read_paths, all_temp = extract_paths(inv.redirects)
87
107
  result = apply_redirects(result, inv.redirects, write_paths, all_temp)
@@ -101,25 +121,36 @@ module Rubik
101
121
  def apply_assignment_payloads(result, inv, parse_warnings)
102
122
  return result if inv.assignments.empty?
103
123
 
104
- inners = inv.assignments.filter_map do |assignment|
124
+ inners = inv.assignments.flat_map do |assignment|
105
125
  name, value = assignment.split("=", 2)
106
126
  value = Matcher::Delegation.strip_quotes(value.to_s)
107
- next nil if value.strip.empty?
127
+ next [] if value.strip.empty?
108
128
 
109
129
  inner_invs, warnings = Parser.parse(value, shell: @shell)
110
130
  Matcher::Delegation.record_warnings(parse_warnings, warnings)
111
- next nil unless command_shaped?(inner_invs)
131
+ next [] if inner_invs.empty?
132
+
133
+ executed = executed_env_var?(name)
134
+ shaped = command_shaped?(inner_invs)
135
+ # A host-executed variable whose payload we cannot classify is
136
+ # the #540 bypass: `GIT_SSH_COMMAND='nc ...' git push` used to
137
+ # read as a clean `git push`. Floor it to UNKNOWN so the gate
138
+ # fails closed instead of trusting the outer allowlist entry.
139
+ next [] if !shaped && !executed
140
+
141
+ floor = executed && !shaped ? Classification::UNKNOWN : nil
112
142
 
113
143
  inner_invs.map do |inner_inv|
114
144
  Matcher::Delegation.match_inner_command(
115
145
  inner_inv.argv, @database,
116
146
  delegation_mode: "env_assignment",
117
147
  delegation_source: name,
148
+ min_classification: floor,
118
149
  parse_warnings: parse_warnings,
119
150
  redirects: inner_inv.redirects
120
151
  ) { |i, db, w| Matcher.match_command(i, db, w, shell: @shell) }
121
152
  end
122
- end.flatten
153
+ end
123
154
  return result if inners.empty?
124
155
 
125
156
  classification = result.classification
@@ -136,15 +167,14 @@ module Rubik
136
167
  classification: classification, risk: risk, classification_reason: reason)
137
168
  end
138
169
 
139
- # False-positive firewall: env values are usually scalars (LANG=C)
140
- # or config blobs (CFLAGS="-O2 -Wall", PS1="\u@\h"). A value counts
141
- # as a command payload only when it parses into an invocation whose
142
- # binary the database KNOWS or that is invoked by path — the same
143
- # trust boundary the matcher applies to any other argv[0].
144
- # Known residual: unknown-binary payloads (a DB-less interpreter
145
- # spelled without a path) stay unclassified, at parity with typing
146
- # that binary directly (UNKNOWN). Closing that would need a
147
- # known-env-exec-binaries list (GIT_SSH_COMMAND, GIT_EDITOR, SHELL).
170
+ # False-positive firewall for ORDINARY env values: they are usually
171
+ # scalars (LANG=C) or config blobs (CFLAGS="-O2 -Wall", PS1="\u@\h").
172
+ # A value counts as a command payload only when it parses into an
173
+ # invocation whose binary the database KNOWS or that is invoked by
174
+ # path — the same trust boundary the matcher applies to any argv[0].
175
+ # Host-executed variables (EXECUTED_ENV_VARS / EXECUTED_ENV_PREFIXES)
176
+ # bypass this firewall in apply_assignment_payloads and fail closed
177
+ # with an UNKNOWN floor when their payload cannot be classified.
148
178
  def command_shaped?(inner_invs)
149
179
  inner_invs.any? do |inv|
150
180
  binary = inv.argv.first.to_s
@@ -153,6 +183,79 @@ module Rubik
153
183
  end
154
184
  end
155
185
 
186
+ def executed_env_var?(name)
187
+ n = name.to_s
188
+ EXECUTED_ENV_VARS.include?(n) || EXECUTED_ENV_PREFIXES.any? { |prefix| n.start_with?(prefix) }
189
+ end
190
+
191
+ def dangerous_git_config_key?(key)
192
+ k = key.to_s.downcase
193
+ DANGEROUS_GIT_CONFIG_KEYS.include?(k) || k.start_with?("alias.")
194
+ end
195
+
196
+ def dangerous_git_config_assignments(result, argv)
197
+ # Only the pre-subcommand region: global options are stripped there
198
+ # before subcommand options run (#539 residual). Post-subcommand
199
+ # -c/--config stays owned by the command definitions; restricting
200
+ # the scan also avoids flagging config-like text inside -m/--grep.
201
+ subcommand = result.command[1..].first
202
+ limit = subcommand ? (argv.index(subcommand) || argv.size) : argv.size
203
+ candidates = argv[1...limit] || []
204
+
205
+ assignments = []
206
+ candidates.each_with_index do |token, i|
207
+ if GIT_CONFIG_FLAGS.include?(token)
208
+ value = candidates[i + 1].to_s
209
+ next unless value.include?("=")
210
+
211
+ key, payload = value.split("=", 2)
212
+ assignments << [key, payload] if dangerous_git_config_key?(key)
213
+ elsif token.start_with?("--config=")
214
+ spec = token.delete_prefix("--config=")
215
+ next unless spec.include?("=")
216
+
217
+ key, payload = spec.split("=", 2)
218
+ assignments << [key, payload] if dangerous_git_config_key?(key)
219
+ end
220
+ end
221
+ assignments
222
+ end
223
+
224
+ # `git -c core.editor='curl ... | bash' clone ...` is stripped as a
225
+ # global option before subcommand options run, so the payload stayed
226
+ # invisible (#539 residual). Gate the dangerous key directly and
227
+ # surface its value through inner-command classification so the
228
+ # verdict is at least as strict as typing the payload itself.
229
+ def apply_git_config_overrides(result, inv, parse_warnings)
230
+ return result unless result.command.first.to_s == "git"
231
+
232
+ assignments = dangerous_git_config_assignments(result, inv.argv)
233
+ return result if assignments.empty?
234
+
235
+ inners = assignments.flat_map do |key, value|
236
+ inner_invs, warnings = Parser.parse(value, shell: @shell)
237
+ Matcher::Delegation.record_warnings(parse_warnings, warnings)
238
+ inner_invs.map do |inner_inv|
239
+ Matcher::Delegation.match_inner_command(
240
+ inner_inv.argv, @database,
241
+ delegation_mode: "git_config",
242
+ delegation_source: key,
243
+ parse_warnings: parse_warnings,
244
+ redirects: inner_inv.redirects
245
+ ) { |i, db, w| Matcher.match_command(i, db, w, shell: @shell) }
246
+ end
247
+ end
248
+
249
+ reason = append_reason(result.classification_reason,
250
+ "dangerous git config #{assignments.map(&:first).join(', ')}")
251
+ result.with(
252
+ inner_commands: result.inner_commands + inners,
253
+ classification: Classification::DANGEROUS,
254
+ risk: Risk::HIGH,
255
+ classification_reason: reason
256
+ )
257
+ end
258
+
156
259
  def extract_paths(redirects)
157
260
  write_paths = []
158
261
  read_paths = []
@@ -361,6 +464,13 @@ module Rubik
361
464
 
362
465
  p = p[1..-2] if (p.start_with?('"') && p.end_with?('"')) || (p.start_with?("'") && p.end_with?("'"))
363
466
  return false if p.empty? || p.start_with?("-")
467
+
468
+ # The current user's home is a system path however it is spelled —
469
+ # ~, $HOME/... and a literal /home/<user>/... must agree (#540).
470
+ # Checked before the temp exemption so a HOME under /tmp (test
471
+ # harnesses, containers) cannot slip through as a "temp path".
472
+ return true if home_path?(p)
473
+
364
474
  return false if !p.include?("..") && (temp_path?(p) || DEV_PATHS.any? { |dev| p == dev || p.start_with?(dev) })
365
475
 
366
476
  # Bare drive prefix without separator is NOT a drive root or system path
@@ -401,6 +511,30 @@ module Rubik
401
511
  end
402
512
  public :system_path?
403
513
 
514
+ # Prefix containment against the current user's home. HOME_TOKENS
515
+ # covers ~/$HOME spellings; this covers the literal absolute spelling
516
+ # that dangerous_system_roots only matched exactly (#540). Any
517
+ # expansion/containment failure (EACCES/EPERM, malformed HOME) is
518
+ # unprovable, so skip this elevation and let the other checks decide.
519
+ def home_path?(path)
520
+ p = path.to_s
521
+ # Only absolute spellings: ~/$HOME are covered by HOME_TOKENS, and
522
+ # expanding relative paths would flag every path under a home-rooted cwd.
523
+ return false unless p.start_with?("/") || p.match?(%r{\A[a-zA-Z]:[\\/]})
524
+
525
+ home = Rubik::Platform.home_dir
526
+ return false if home.nil? || home.to_s.empty?
527
+
528
+ home_abs = safe_expand_path(home.to_s)
529
+ return false unless home_abs.to_s.match?(%r{\A/}) || home_abs.to_s.match?(%r{\A[a-zA-Z]:[\\/]})
530
+
531
+ path_abs = safe_expand_path(path)
532
+ Rubik::Platform.path_under?(Rubik::Platform.normalize_path(path_abs),
533
+ Rubik::Platform.normalize_path(home_abs))
534
+ rescue StandardError
535
+ false
536
+ end
537
+
404
538
  def safe_expand_path(path)
405
539
  File.expand_path(path)
406
540
  rescue ArgumentError, TypeError
@@ -100,7 +100,7 @@ subcommands:
100
100
  classification: READONLY
101
101
  strict: false
102
102
  up:
103
- classification: EXTERNAL_EFFECTS
103
+ classification: DANGEROUS
104
104
  strict: false
105
105
  down:
106
106
  classification: EXTERNAL_EFFECTS
@@ -48,6 +48,13 @@ subcommands:
48
48
  ls-remote:
49
49
  classification: READONLY
50
50
  strict: false
51
+ # Transport/config options that spawn a shell or hijack execution (issue #539).
52
+ options:
53
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
54
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
55
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
56
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
57
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
51
58
  ls-tree:
52
59
  classification: READONLY
53
60
  strict: false
@@ -307,16 +314,33 @@ subcommands:
307
314
  pull:
308
315
  classification: LOCAL_EFFECTS
309
316
  strict: false
317
+ options:
318
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
319
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
321
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
322
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
310
323
  fetch:
311
324
  classification: LOCAL_EFFECTS
312
325
  risk: LOW
313
326
  strict: false
314
327
  options:
315
328
  --prune: {overrides: LOCAL_EFFECTS}
329
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
330
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
331
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
332
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
333
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
316
334
  clone:
317
335
  classification: LOCAL_EFFECTS
318
336
  risk: LOW
319
337
  strict: false
338
+ options:
339
+ --upload-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
340
+ --receive-pack: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
341
+ --exec: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
342
+ -c: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
343
+ --config: {overrides: DANGEROUS, takes_value: true, risk: HIGH}
320
344
  init:
321
345
  classification: LOCAL_EFFECTS
322
346
  risk: LOW
@@ -436,7 +460,9 @@ subcommands:
436
460
  classification: READONLY
437
461
  strict: false
438
462
  foreach:
439
- classification: READONLY
463
+ # git evaluates the argument as a shell command in every submodule;
464
+ # typing the payload directly would be DANGEROUS (issue #539).
465
+ classification: DANGEROUS
440
466
  strict: false
441
467
  init:
442
468
  classification: LOCAL_EFFECTS
@@ -1,7 +1,7 @@
1
1
  # $schema: ../../../schemas/command.schema.json
2
2
  command: sed
3
3
  description: "Stream editor for filtering and transforming text"
4
- classification: READONLY
4
+ classification: LOCAL_EFFECTS
5
5
  strict: false
6
6
  global_options:
7
7
  --help: {overrides: READONLY}
@@ -10,5 +10,5 @@ options:
10
10
  --in-place: {overrides: DANGEROUS, risk: HIGH, aliases: [-i]}
11
11
  -e: {takes_value: true}
12
12
  --expression: {takes_value: true, aliases: [-e]}
13
- -f: {takes_value: true}
14
- --file: {takes_value: true, aliases: [-f]}
13
+ -f: {overrides: DANGEROUS, risk: HIGH, takes_value: true}
14
+ --file: {overrides: DANGEROUS, risk: HIGH, takes_value: true, aliases: [-f]}
@@ -81,7 +81,7 @@ module Rubik
81
81
  key_s = self.class.yaml_str(key)
82
82
  return true if shell == :powershell && PwshRules.key?(key_s)
83
83
 
84
- @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s)
84
+ synchronize { @cache.key?(key_s) || @files.key?(key_s) || PwshRules.key?(key_s) }
85
85
  end
86
86
 
87
87
  def resolve_alias(command_def)
@@ -97,7 +97,7 @@ module Rubik
97
97
  end
98
98
 
99
99
  def keys
100
- (@files.keys + PwshRules.definitions.keys).uniq
100
+ synchronize { (@files.keys + PwshRules.definitions.keys).uniq }
101
101
  end
102
102
 
103
103
  def size
@@ -197,7 +197,14 @@ module Rubik
197
197
  block_ambiguous_parse!(ast, cmd_str)
198
198
  end
199
199
 
200
- return true if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
200
+ # Classification-based allow verdicts must not skip the un-bypassable
201
+ # fallback regex: every other allow path runs it (directly or via
202
+ # operator_allowlist_pass?). An under-rated database entry must not
203
+ # become a silent full bypass of the final safety layer.
204
+ if [:readonly, :local_effects, :external_effects].include?(ast.classification) && ast.parse_warnings.empty?
205
+ verify_command_fallback_regex!(cmd_str)
206
+ return true
207
+ end
201
208
  rescue BlockedWriteError
202
209
  raise
203
210
  rescue StandardError => e
@@ -101,11 +101,36 @@ module Rubik
101
101
  write_targets.concat(ast.write_paths.to_a) if ast.respond_to?(:write_paths)
102
102
 
103
103
  write_targets.uniq.each do |wp|
104
- next unless critical_path?(wp)
104
+ if critical_path?(wp)
105
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
106
+ raise BlockedWriteError.new(
107
+ "Command write to critical path blocked: #{wp} in `#{cmd_str}`",
108
+ kind: :critical_path_write,
109
+ blocked_command: cmd_str,
110
+ path: wp
111
+ )
112
+ end
113
+
114
+ # Symlink re-check (fail-closed, issue #590): the lexical test above
115
+ # cannot see `evil -> .git/config`, so `echo x > evil` would sail
116
+ # through while naming nothing critical. Resolve each write target
117
+ # exactly like verify_path_write! does and re-check the resolution;
118
+ # a nil resolution (symlink loop / permission wall) fails closed.
119
+ resolved = Rubik::Platform.resolved_path(wp, strict: true)
120
+ if resolved.nil?
121
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "path_resolution_failed", path: wp)
122
+ raise BlockedWriteError.new(
123
+ "Command write blocked: path could not be safely resolved: #{wp} in `#{cmd_str}`",
124
+ kind: :critical_path_write,
125
+ blocked_command: cmd_str,
126
+ path: wp
127
+ )
128
+ end
129
+ next unless critical_path?(resolved)
105
130
 
106
- @audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
131
+ @audit.log_audit("blocked_command", command: cmd_str, reason: "critical_path_write_symlink", path: wp, resolved: resolved)
107
132
  raise BlockedWriteError.new(
108
- "Command write to critical path blocked: #{wp} in `#{cmd_str}`",
133
+ "Command write to critical path blocked (symlink-resolved): #{wp} -> #{resolved} in `#{cmd_str}`",
109
134
  kind: :critical_path_write,
110
135
  blocked_command: cmd_str,
111
136
  path: wp
@@ -17,8 +17,15 @@ module Rubik
17
17
  %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
18
18
  ].freeze
19
19
 
20
- ASSIGNMENT_KEY_REGEX = /\b(password|passwd|api_key|secret)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
21
- ASSIGNMENT_TOKEN_REGEX = /\b(token)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/i
20
+ # Generic NAME <sep> VALUE assignment. The name is normalized (camelCase
21
+ # boundaries -> snake_case, downcase) and classified by #secret_key? at
22
+ # match time, so `password=...`, `OPENAI_API_KEY=...`, `apiKey=...` and the
23
+ # `--key=...` flag form all share ONE rule. The optional `--` prefix is
24
+ # what makes provider CLI flags land here (issue #542).
25
+ ASSIGNMENT_KEY_REGEX = /(--)?\b([A-Za-z][A-Za-z0-9_-]*)(\s*[:=]\s*)(['"][^'"]*['"]|[^\s,;'"]+)/
26
+ # Positional counterpart of `--key=...`: `!provider set <name> key <value>`
27
+ # has no separator, so it needs its own bounded shape (no prose masking).
28
+ CLI_POSITIONAL_KEY_REGEX = /\b(set\s+\S+\s+(?:key|api[_-]?key|secret|token|password|passwd)\s+)(['"][^'"]*['"]|[^\s,;'"]+)/i
22
29
 
23
30
  # PERF: Pre-compiled constants to avoid re-allocation inside hot loops
24
31
  URL_PATTERN = %r{(https?://[^\s/@:]+:)([^\s/@:]+)@}
@@ -26,13 +33,18 @@ module Rubik
26
33
  STATIC_PATTERNS = PATTERNS.reject { |pattern| pattern == URL_PATTERN }.freeze
27
34
  # Skip static replacement passes for assignment-only and URL-only inputs.
28
35
  STATIC_PATTERNS_COMBINED_REGEX = Regexp.union(STATIC_PATTERNS).freeze
29
- QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token}i
36
+ # `key` is load-bearing: without it `--key=...` and `apiKey` take the
37
+ # fast path and keep the credential verbatim (issue #542).
38
+ QUICK_CHECK_REGEX = %r{sk-|AKIA|ghp_|github_pat_|AIza|bearer|PRIVATE KEY|://[^\s/@:]+:|password|passwd|api_key|secret|token|\bkey\b}i
30
39
 
31
40
  # Anahtar-maskeleme desenleri (Session::Recorder#mask_payload ile aynı
32
41
  # aile): sır görünümlü anahtarların değerleri desen eşleşmese bile
33
- # maskelenir; sayaç anahtarları (tokens, max_tokens) istisnadır.
34
- SECRET_KEY_REGEX = /(api_key|auth|password|secret|_token\b|^token\b)/i
35
- TOKEN_COUNT_REGEX = /(tokens|token_count|max_tokens)/i
42
+ # maskelenir. Her iki desen de NORMALİZE anahtara uygulanır; sayaç
43
+ # istisnası tam adla eşleşir, yoksa `auth_tokens` gibi bir sır anahtarı
44
+ # `tokens` alt dizgisi yüzünden yanlışlıkla istisna sayılırdı (#542).
45
+ SECRET_KEY_REGEX = /(?:api_key|auth|password|passwd|secret|_token\z|\Atoken\b|\bkey\b)/i
46
+ TOKEN_COUNT_REGEX = /\A(?:tokens|token_count|max_tokens)\z/i
47
+ TOKEN_NAME_REGEX = /(?:\Atoken\b|_token\z)/i
36
48
 
37
49
  def self.redact(text)
38
50
  return text unless text.is_a?(String)
@@ -59,23 +71,56 @@ module Rubik
59
71
  result.gsub!(URL_PATTERN, URL_MASK)
60
72
 
61
73
  result.gsub!(ASSIGNMENT_KEY_REGEX) do
62
- "#{Regexp.last_match(1)}#{Regexp.last_match(2)}#{MASK_STRING}"
63
- end
64
-
65
- result.gsub!(ASSIGNMENT_TOKEN_REGEX) do |match|
66
- prefix = Regexp.last_match(1)
67
- sep = Regexp.last_match(2)
68
- val = Regexp.last_match(3)
69
- if val =~ /\A['"]?\d+['"]?\z/
70
- match
74
+ full = Regexp.last_match(0)
75
+ flag = Regexp.last_match(1)
76
+ name = Regexp.last_match(2)
77
+ sep = Regexp.last_match(3)
78
+ value = Regexp.last_match(4)
79
+ if maskable_assignment?(name, value)
80
+ "#{flag}#{name}#{sep}#{MASK_STRING}"
71
81
  else
72
- "#{prefix}#{sep}#{MASK_STRING}"
82
+ full
73
83
  end
74
84
  end
75
85
 
86
+ result.gsub!(CLI_POSITIONAL_KEY_REGEX) do
87
+ "#{Regexp.last_match(1)}#{MASK_STRING}"
88
+ end
89
+
76
90
  result
77
91
  end
78
92
 
93
+ # camelCase / SCREAMING_SNAKE -> lower snake_case, so one vocabulary
94
+ # recognizes `apiKey`, `APIKey`, `OPENAI_API_KEY` and `api_key` alike.
95
+ # Both patterns are FIXED-LENGTH: the old `([A-Z]+)([A-Z][a-z])` had a
96
+ # repeated class immediately followed by an overlapping class, which
97
+ # backtracks polynomially on a long uppercase run (CodeQL rb/polynomial-
98
+ # redos). Matching a single uppercase before the boundary is equivalent
99
+ # — the preceding uppercase chars are simply copied — and linear.
100
+ def self.normalize_key(key)
101
+ key.to_s
102
+ .gsub(/([A-Z])([A-Z][a-z])/, '\1_\2')
103
+ .gsub(/([a-z\d])([A-Z])/, '\1_\2')
104
+ .downcase
105
+ end
106
+
107
+ # True for a secret-looking key, with counter names excluded by EXACT
108
+ # match (so `auth_tokens` stays a secret while `max_tokens` does not).
109
+ def self.secret_key?(key)
110
+ normalized = normalize_key(key)
111
+ normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
112
+ end
113
+
114
+ # Token-valued assignments keep a numeric value (the existing contract:
115
+ # `token: 20` / `max_tokens: 100` are counters, not credentials).
116
+ def self.maskable_assignment?(name, value)
117
+ normalized = normalize_key(name)
118
+ return false unless normalized.match?(SECRET_KEY_REGEX) && !normalized.match?(TOKEN_COUNT_REGEX)
119
+ return false if normalized.match?(TOKEN_NAME_REGEX) && value.to_s.match?(/\A['"]?\d+['"]?\z/)
120
+
121
+ true
122
+ end
123
+
79
124
  # Bir payload ağacında (Hash/Array/String) her metne redact uygular ve
80
125
  # sır görünümlü anahtarların değerlerini komple maskeler — kalıcı
81
126
  # serileştirmeden önce satır başına çağrılır (transcript sağlığı
@@ -88,9 +133,7 @@ module Rubik
88
133
  case payload
89
134
  when Hash
90
135
  payload.each_with_object({}) do |(k, v), h|
91
- key_str = k.to_s
92
- is_secret_key = key_str.match?(SECRET_KEY_REGEX) && !key_str.match?(TOKEN_COUNT_REGEX)
93
- h[k] = is_secret_key ? MASK_STRING : mask_value(v)
136
+ h[k] = secret_key?(k) ? MASK_STRING : mask_value(v)
94
137
  end
95
138
  when Array
96
139
  payload.map { |v| mask_value(v) }
@@ -16,6 +16,14 @@ module Rubik
16
16
 
17
17
  attr_reader :session_file, :events
18
18
 
19
+ # The session identity spelled everywhere else (parent_session_id
20
+ # stamps, session listings, LLM session-header derivation): the file
21
+ # basename without extension. Single-homed so a filename-scheme
22
+ # change cannot silently fork downstream spellings.
23
+ def session_id
24
+ File.basename(@session_file.to_s, ".jsonl")
25
+ end
26
+
19
27
  def initialize(sessions_dir: nil, session_name: nil, root_dir: Dir.pwd, home_dir: ENV.fetch("HOME", nil)) # rubocop:disable Lint/UnusedMethodArgument -- arayüz kwarg'i korunuyor
20
28
  @sessions_dir = sessions_dir || File.join(root_dir, ".rubik", "sessions")
21
29
  begin
@@ -70,7 +78,19 @@ module Rubik
70
78
  record("repl_command", { "command" => cmd, "output" => output })
71
79
  end
72
80
 
73
- def switch_session_file(target_file, cleanup_empty_current: true)
81
+ # Durability barrier for copies of the live JSONL (issue #598): records
82
+ # are opened, written and closed per event, so there is no buffered
83
+ # writer to flush — this fsync barrier guarantees a save copy taken
84
+ # afterwards never observes a torn tail.
85
+ def flush
86
+ return unless @session_file && File.exist?(@session_file)
87
+
88
+ File.open(@session_file, "a", &:fsync)
89
+ rescue StandardError
90
+ nil
91
+ end
92
+
93
+ def switch_session_file(target_file, cleanup_empty_current: true, parent_session_id: nil)
74
94
  if cleanup_empty_current && @session_file && File.exist?(@session_file) && File.expand_path(@session_file) != File.expand_path(target_file)
75
95
  begin
76
96
  lines = File.readlines(@session_file).reject { |l| l.strip.empty? }
@@ -103,7 +123,7 @@ module Rubik
103
123
  end
104
124
 
105
125
  record("session_resumed", {
106
- "parent_session_id" => File.basename(target_file, ".jsonl"),
126
+ "parent_session_id" => parent_session_id || File.basename(target_file, ".jsonl"),
107
127
  "resumed_at" => Time.now.iso8601
108
128
  })
109
129
  end
@@ -125,25 +145,12 @@ module Rubik
125
145
  event
126
146
  end
127
147
 
148
+ # SSOT: the subagent channel masks with Redactor.mask_value, so the
149
+ # session recorder must delegate to the very same routine — a second
150
+ # copy of the key vocabulary drifts (camelCase, counter exclusions,
151
+ # env-style assignments) the moment one side is hardened (issue #542).
128
152
  def mask_payload(payload)
129
- case payload
130
- when Hash
131
- payload.each_with_object({}) do |(k, v), h|
132
- key_str = k.to_s
133
- is_secret_key = key_str.match?(/(api_key|auth|password|secret|_token\b|^token\b)/i) && !key_str.match?(/(tokens|token_count|max_tokens)/i)
134
- h[k] = if is_secret_key
135
- "***MASKED***"
136
- else
137
- mask_payload(v)
138
- end
139
- end
140
- when Array
141
- payload.map { |v| mask_payload(v) }
142
- when String
143
- mask_text(payload)
144
- else
145
- payload
146
- end
153
+ Rubik::Security::Redactor.mask_value(payload)
147
154
  end
148
155
  end
149
156
  end
@@ -7,6 +7,22 @@ module Rubik
7
7
  class Replayer
8
8
  DESTRUCTIVE_COMMANDS = ["apply", "sh", "rm", "execute"].freeze
9
9
 
10
+ # The recorder's current event vocabulary plus the legacy pair. Only
11
+ # input-shaped events are re-executed; output-shaped ones are still
12
+ # recognized (and reported in replayed_events) so a current-format
13
+ # session is no longer a no-op for `!replay` (issue #562).
14
+ INPUT_EVENT_TYPES = ["input", "command", "prompt", "user_turn", "repl_command"].freeze
15
+ EVENT_TEXT_KEYS = {
16
+ "input" => ["raw", "input", "content"],
17
+ "command" => ["raw", "input", "command"],
18
+ "prompt" => ["raw", "input", "content"],
19
+ "user_turn" => ["content", "text", "raw"],
20
+ "repl_command" => ["command", "raw"],
21
+ "assistant_response" => ["content", "text", "output"],
22
+ "tool_call" => ["tool", "name"],
23
+ "tool_result" => ["tool", "name", "output"]
24
+ }.freeze
25
+
10
26
  attr_reader :shell, :replayed_events, :skipped_events
11
27
 
12
28
  def initialize(shell)
@@ -37,18 +53,24 @@ module Rubik
37
53
  private
38
54
 
39
55
  def process_event(event)
40
- type = event["type"]
41
- payload = event["payload"]
56
+ type = event["type"].to_s
57
+ keys = EVENT_TEXT_KEYS[type]
58
+ return unless keys
42
59
 
43
- return unless ["input", "command"].include?(type)
44
-
45
- cmd_text = payload.is_a?(Hash) ? (payload["raw"] || payload["input"]) : payload.to_s
60
+ payload = event["payload"]
61
+ cmd_text = if payload.is_a?(Hash)
62
+ keys.filter_map { |key| payload[key] }.first
63
+ else
64
+ payload.to_s
65
+ end
66
+ return if cmd_text.nil? || cmd_text.to_s.strip.empty?
46
67
 
47
- if destructive?(cmd_text)
68
+ input_event = INPUT_EVENT_TYPES.include?(type)
69
+ if input_event && destructive?(cmd_text)
48
70
  @skipped_events << { event: event, reason: "[skipped: destructive]" }
49
71
  else
50
72
  @replayed_events << event
51
- @shell.execute_input(cmd_text)
73
+ @shell.execute_input(cmd_text.to_s) if input_event
52
74
  end
53
75
  end
54
76