rubik 0.8.1 → 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 (148) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +207 -43
  4. data/README.md +5 -1
  5. data/bin/rubik +15 -10
  6. data/lib/rubik/adapter/base.rb +19 -0
  7. data/lib/rubik/adapter/generic.rb +0 -14
  8. data/lib/rubik/adapter/node.rb +2 -0
  9. data/lib/rubik/ast/treesitter/zig_walker.rb +15 -2
  10. data/lib/rubik/cli/workspace_trust.rb +17 -0
  11. data/lib/rubik/concurrency/worker.rb +143 -0
  12. data/lib/rubik/concurrency.rb +1 -0
  13. data/lib/rubik/config/deep_ops.rb +17 -0
  14. data/lib/rubik/config/defaults.rb +23 -1
  15. data/lib/rubik/config/schema.rb +0 -1
  16. data/lib/rubik/config/store.rb +14 -0
  17. data/lib/rubik/config.rb +7 -3
  18. data/lib/rubik/context/repo_context_reader.rb +27 -8
  19. data/lib/rubik/events.rb +18 -0
  20. data/lib/rubik/kernel/dispatcher.rb +4 -4
  21. data/lib/rubik/kernel/unit.rb +4 -3
  22. data/lib/rubik/log.rb +2 -1
  23. data/lib/rubik/lsp/client.rb +83 -180
  24. data/lib/rubik/lsp/document_store.rb +209 -0
  25. data/lib/rubik/mcp/client.rb +4 -3
  26. data/lib/rubik/mcp/manager.rb +6 -2
  27. data/lib/rubik/mcp/transport/stdio.rb +51 -9
  28. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  29. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  30. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  31. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  32. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  33. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  34. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  35. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  36. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  37. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  38. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  39. data/lib/rubik/orchestrator/goal_session.rb +505 -0
  40. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  41. data/lib/rubik/orchestrator/loop.rb +62 -63
  42. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  43. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  44. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  45. data/lib/rubik/orchestrator/subagent/instance.rb +4 -0
  46. data/lib/rubik/orchestrator/subagent/journal.rb +2 -1
  47. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  48. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  49. data/lib/rubik/orchestrator/subagent/questioner.rb +21 -6
  50. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  51. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  52. data/lib/rubik/orchestrator/subagent/step_runner.rb +1 -1
  53. data/lib/rubik/orchestrator/subagent/teardown.rb +4 -0
  54. data/lib/rubik/orchestrator/subagent/transcript_formatter.rb +2 -1
  55. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  56. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  57. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  58. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  59. data/lib/rubik/orchestrator.rb +1 -0
  60. data/lib/rubik/platform/path.rb +0 -1
  61. data/lib/rubik/platform.rb +15 -0
  62. data/lib/rubik/plugin/storage.rb +20 -29
  63. data/lib/rubik/prompt/context_builder.rb +24 -18
  64. data/lib/rubik/prompt/context_compactor.rb +31 -8
  65. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  66. data/lib/rubik/prompt/doctrine.rb +4 -2
  67. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  68. data/lib/rubik/repl/commands/agent_context.rb +1 -1
  69. data/lib/rubik/repl/commands/agent_execution.rb +15 -467
  70. data/lib/rubik/repl/commands/buffer.rb +5 -1
  71. data/lib/rubik/repl/commands/lsp.rb +1 -1
  72. data/lib/rubik/repl/commands/mcp.rb +5 -0
  73. data/lib/rubik/repl/commands/subagents.rb +4 -4
  74. data/lib/rubik/repl/commands/workspace.rb +22 -2
  75. data/lib/rubik/repl/config_wiring.rb +24 -7
  76. data/lib/rubik/repl/input_execution.rb +1 -1
  77. data/lib/rubik/repl/input_loop.rb +1 -1
  78. data/lib/rubik/repl/lifecycle.rb +31 -2
  79. data/lib/rubik/repl/pruner/harness.rb +52 -67
  80. data/lib/rubik/repl/pruner/rules.rb +3 -1
  81. data/lib/rubik/repl/service_catalog.rb +1 -1
  82. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  83. data/lib/rubik/repl/turn_recorder.rb +5 -4
  84. data/lib/rubik/repl.rb +1 -0
  85. data/lib/rubik/runtime/context.rb +5 -0
  86. data/lib/rubik/runtime/discovery.rb +55 -0
  87. data/lib/rubik/runtime/manifest_store.rb +116 -0
  88. data/lib/rubik/runtime/overlay_storage.rb +300 -218
  89. data/lib/rubik/runtime/repair_probe.rb +20 -2
  90. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  91. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  92. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  93. data/lib/rubik/runtime/task_manager.rb +7 -2
  94. data/lib/rubik/runtime.rb +3 -0
  95. data/lib/rubik/security/allowlist.rb +167 -0
  96. data/lib/rubik/security/audit_log.rb +72 -0
  97. data/lib/rubik/security/classifier/classifier.rb +24 -8
  98. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  99. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  100. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  101. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  102. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  103. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  104. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  105. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  106. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  107. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  108. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  109. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  110. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  111. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  112. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  113. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  114. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  115. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  116. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  117. data/lib/rubik/security/classifier/database.rb +12 -1
  118. data/lib/rubik/security/classifier/matcher.rb +17 -2
  119. data/lib/rubik/security/classifier/models.rb +3 -2
  120. data/lib/rubik/security/classifier.rb +5 -0
  121. data/lib/rubik/security/command_gate.rb +567 -0
  122. data/lib/rubik/security/guard.rb +96 -989
  123. data/lib/rubik/security/path_policy.rb +117 -0
  124. data/lib/rubik/security/synthesis_gate.rb +300 -0
  125. data/lib/rubik/security.rb +5 -0
  126. data/lib/rubik/storage/ranking.rb +113 -0
  127. data/lib/rubik/storage/store.rb +2 -92
  128. data/lib/rubik/storage/transcript_indexer.rb +2 -3
  129. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  130. data/lib/rubik/tools/base.rb +24 -7
  131. data/lib/rubik/tools/builtins/files.rb +2 -0
  132. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  133. data/lib/rubik/tools/builtins/grep.rb +2 -3
  134. data/lib/rubik/tools/builtins/lifecycle.rb +91 -88
  135. data/lib/rubik/tools/builtins/synthesis.rb +124 -64
  136. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  137. data/lib/rubik/tools/catalog.rb +3 -0
  138. data/lib/rubik/tools/declaration.rb +6 -2
  139. data/lib/rubik/tools/lifecycle_rollbacks.rb +87 -0
  140. data/lib/rubik/tools/native_search.rb +2 -1
  141. data/lib/rubik/tools/preflight_runner.rb +107 -14
  142. data/lib/rubik/tools/registry.rb +2 -0
  143. data/lib/rubik/tools/truncator.rb +25 -0
  144. data/lib/rubik/tools/uri_resolver.rb +3 -1
  145. data/lib/rubik/uris.rb +5 -1
  146. data/lib/rubik/version.rb +1 -1
  147. data/lib/rubik.rb +1 -0
  148. metadata +35 -1
@@ -11,8 +11,11 @@ module Rubik
11
11
  module Runtime
12
12
  # Functional checks own their resources through the caller's probe context.
13
13
  class RepairProbe
14
- def initialize(root_dir:)
14
+ ALLOWED_PROBE_FLAGS = ["--help", "-h", "help", "--version", "-v", "-V", "version", "--status"].freeze
15
+
16
+ def initialize(root_dir:, guard: nil)
15
17
  @root_dir = root_dir
18
+ @guard = guard
16
19
  end
17
20
 
18
21
  PROBE_TIMEOUT = 5
@@ -26,6 +29,15 @@ module Rubik
26
29
  return probe_failure(proposed_cmd, 127, "Availability check failed: executable not found in PATH")
27
30
  end
28
31
 
32
+ if @guard
33
+ cmd_to_check = proposed_cmd.is_a?(Hash) ? [proposed_cmd[:executable], *Array(proposed_cmd[:args])].join(" ") : proposed_cmd.to_s
34
+ begin
35
+ @guard.verify_command_safety!(cmd_to_check)
36
+ rescue Rubik::Security::BlockedWriteError => e
37
+ return probe_failure(proposed_cmd, 1, "Proposed command blocked by security guard: #{e.message}")
38
+ end
39
+ end
40
+
29
41
  if target == "lsp"
30
42
  client = Rubik::LSP::Client.new(lang, root_dir: @root_dir, server_cmd: proposed_cmd)
31
43
  sub_ctx.on_dispose { client.stop }
@@ -45,8 +57,14 @@ module Rubik
45
57
  end
46
58
 
47
59
  probe_args = ["--help"]
60
+ else
61
+ return probe_failure(proposed_cmd, 1, "probe_args must be a non-empty array of strings") unless probe_args.is_a?(Array) && !probe_args.empty? && probe_args.all?(String)
62
+
63
+ disallowed = probe_args.reject { |arg| ALLOWED_PROBE_FLAGS.include?(arg) }
64
+ if disallowed.any?
65
+ return probe_failure(proposed_cmd, 1, "Disallowed probe_args: only safe diagnostic flags #{ALLOWED_PROBE_FLAGS.inspect} are allowed (got: #{disallowed.inspect})")
66
+ end
48
67
  end
49
- return probe_failure(proposed_cmd, 1, "probe_args must be a non-empty array of strings") unless probe_args.is_a?(Array) && !probe_args.empty? && probe_args.all?(String)
50
68
 
51
69
  argv.concat(probe_args)
52
70
  # Array-form spawn never interprets shell operators. File-backed output
@@ -0,0 +1,58 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../coeffects"
4
+ require_relative "../log"
5
+
6
+ module Rubik
7
+ module Runtime
8
+ # Shared capability gate for sealed execution contexts (synthesized tools
9
+ # and commands). The Guard vets the synthesized code itself; this
10
+ # deny-list is the gate on what that code may resolve through the sealed
11
+ # context's coeffect/require path.
12
+ module SealedCoeffects
13
+ # Coeffects that must NEVER be leaked to synthesized code. Canonical
14
+ # keys (Rubik::Coeffects); legacy alias spellings canonicalize to their
15
+ # canonical form before the check, so aliases of a blocked service are
16
+ # denied without being restated here. App-domain coeffects (e.g.
17
+ # storage) stay reachable by design.
18
+ BLOCKED_COEFFECTS = [
19
+ "guard",
20
+ "config",
21
+ "sandbox",
22
+ "sandbox_runner",
23
+ "shell",
24
+ "buffer_manager",
25
+ "runtime_manager",
26
+ "task_manager",
27
+ "subagent_supervisor",
28
+ "init",
29
+ "dispatcher",
30
+ "commands",
31
+ "tool_registry",
32
+ "adapter_registry",
33
+ "mcp_manager",
34
+ "llm_client",
35
+ "router",
36
+ "plugin_manager",
37
+ "plugin_storage",
38
+ "lsp_manager",
39
+ "skill_manager"
40
+ ].freeze
41
+
42
+ private
43
+
44
+ # A legacy alias of a blocked service (e.g. "tools" for
45
+ # "tool_registry") must not slip through under the unblocked spelling.
46
+ # Denials log at warn: audible at the default level, since a blocked
47
+ # probe is a security event. Silence toward synthesized code (the
48
+ # command path and get/has?) is deliberate — the log is the operator
49
+ # record; the error class stays distinguishable host-side only.
50
+ def blocked?(key)
51
+ canonical = Rubik::Coeffects.canonical(key)
52
+ blocked = BLOCKED_COEFFECTS.include?(key) || BLOCKED_COEFFECTS.include?(canonical)
53
+ Rubik::Log.warn(:runtime, "sealed context denied coeffect '#{key}'") if blocked
54
+ blocked
55
+ end
56
+ end
57
+ end
58
+ end
@@ -0,0 +1,80 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "sealed_coeffects"
4
+
5
+ module Rubik
6
+ module Runtime
7
+ # Sealed execution context for synthesized and overlay commands (Pillar 2, Feature 11).
8
+ #
9
+ # Unlike the interactive REPL `CommandContext` (which exposes `guard`, `config`,
10
+ # `sandbox_runner`, `buffer_manager`, `shell`, and session mutations),
11
+ # `SynthesizedCommandContext` exposes ONLY:
12
+ # - Output methods: `out` (wrapped stream), `puts`, `print`, `flush` (and alias `output`)
13
+ # - Safe mediated coeffects: `coeffect(name)`
14
+ #
15
+ # All access to internal subsystems (.guard, .config, .sandbox_runner, .shell,
16
+ # .buffer_manager, .commands, etc.) is blocked; calling them raises NoMethodError.
17
+ class SynthesizedCommandContext
18
+ include SealedCoeffects
19
+
20
+ attr_reader :out
21
+ alias output out
22
+
23
+ def self.wrap(ctx, shell: nil, runtime_manager: nil)
24
+ return ctx if ctx.is_a?(self)
25
+
26
+ output_io = if ctx.respond_to?(:out) then ctx.out
27
+ elsif ctx then ctx
28
+ elsif shell.respond_to?(:output) then shell.output
29
+ else $stdout
30
+ end
31
+ runtime_ctx = if runtime_manager&.context then runtime_manager.context
32
+ elsif shell.respond_to?(:runtime_manager) then shell.runtime_manager&.context
33
+ elsif ctx.respond_to?(:runtime_manager) then ctx.runtime_manager&.context
34
+ end
35
+ new(output: output_io, coeffects: runtime_ctx || {})
36
+ end
37
+
38
+ def initialize(output: $stdout, coeffects: {})
39
+ @out = output || $stdout
40
+ @coeffects = coeffects || {}
41
+ end
42
+
43
+ # IO conveniences delegating to @out
44
+ def puts(*)
45
+ @out.puts(*)
46
+ end
47
+
48
+ def print(*)
49
+ @out.print(*)
50
+ end
51
+
52
+ def flush
53
+ @out.flush if @out.respond_to?(:flush)
54
+ end
55
+
56
+ # Safe mediated coeffect accessor.
57
+ # Returns nil if the coeffect is blocked or not satisfied.
58
+ def coeffect(name)
59
+ return nil if name.nil?
60
+
61
+ key = name.to_s.downcase.strip
62
+ return nil if blocked?(key)
63
+
64
+ if @coeffects.is_a?(Hash)
65
+ @coeffects[key] || @coeffects[name] || @coeffects[name.to_s] || @coeffects[name.to_sym]
66
+ elsif @coeffects.respond_to?(:get)
67
+ @coeffects.get(key)
68
+ elsif @coeffects.respond_to?(:resolve)
69
+ @coeffects.resolve(key)
70
+ elsif @coeffects.respond_to?(:[])
71
+ @coeffects[key] || @coeffects[name]
72
+ end
73
+ end
74
+ end
75
+ end
76
+
77
+ module REPL
78
+ SynthesizedCommandContext = Rubik::Runtime::SynthesizedCommandContext
79
+ end
80
+ end
@@ -0,0 +1,123 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "../coeffects"
4
+ require_relative "context"
5
+ require_relative "sealed_coeffects"
6
+
7
+ module Rubik
8
+ module Runtime
9
+ # Sealed read-only execution context for synthesized and overlay tools (Pillar 2 / Pillar 3).
10
+ #
11
+ # Modeled after `Rubik::REPL::SynthesizedCommandContext`. Exposes ONLY read-only coeffect
12
+ # accessors (`require`, `get`, `has?`, `satisfied?`, `coeffect`).
13
+ #
14
+ # All mutating/lifecycle/parent methods (`dispose`, `provide`, `unprovide`, `parent`,
15
+ # `extend`, `register_disposable`, `on_dispose`, etc.) are blocked with NoMethodError.
16
+ class SynthesizedToolContext
17
+ include SealedCoeffects
18
+
19
+ # Positional parameter kinds accepted as evidence of a 2-arity handler.
20
+ POSITIONAL_KINDS = [:req, :opt, :rest].freeze
21
+
22
+ # Remove Object#extend so calling ctx.extend raises NoMethodError
23
+ undef_method :extend
24
+
25
+ class << self
26
+ # Idempotently wrap an existing context in a sealed SynthesizedToolContext.
27
+ def wrap(context)
28
+ return context if context.is_a?(self)
29
+
30
+ new(context)
31
+ end
32
+
33
+ # Determines whether a tool handler expects or permits context as its 2nd argument.
34
+ #
35
+ # Evaluates positional parameter count (:req, :opt, :rest), ignoring keyword
36
+ # and block parameters.
37
+ def accepts_context?(handler)
38
+ return false unless handler.respond_to?(:call)
39
+
40
+ params = if handler.respond_to?(:parameters)
41
+ handler.parameters
42
+ elsif handler.respond_to?(:method)
43
+ begin
44
+ handler.method(:call).parameters
45
+ rescue StandardError
46
+ []
47
+ end
48
+ else
49
+ []
50
+ end
51
+
52
+ if params.empty?
53
+ return handler.arity == 2 if handler.respond_to?(:arity)
54
+
55
+ return false
56
+ end
57
+
58
+ # params is an Array of [type, name] pairs (Method#parameters), so a
59
+ # Hash-style slice would be wrong here — filter by positional kinds.
60
+ pos_params = params.select { |param| POSITIONAL_KINDS.include?(param[0]) }
61
+ req_count = pos_params.count { |param| param[0] == :req }
62
+
63
+ 2.between?(req_count, pos_params.size)
64
+ end
65
+ end
66
+
67
+ def initialize(context = nil)
68
+ @context = context
69
+ end
70
+
71
+ # Safe read-only coeffect dependency resolution.
72
+ def require(name)
73
+ raise CoeffectMissingError, "Required coeffect '#{name}' is not satisfied in the context." if name.nil?
74
+
75
+ key = name.to_s.downcase.strip
76
+ raise CoeffectBlockedError, "Required coeffect '#{key}' is denied by sealed-context policy." if blocked?(key)
77
+
78
+ val = get(name)
79
+ return val unless val.nil?
80
+
81
+ raise CoeffectMissingError, "Required coeffect '#{name}' is not satisfied in the context."
82
+ end
83
+
84
+ # Safe mediated coeffect reader.
85
+ def get(name, default = nil)
86
+ return default if name.nil?
87
+
88
+ key = name.to_s.downcase.strip
89
+ return default if blocked?(key)
90
+
91
+ val = if @context.respond_to?(:get)
92
+ res = @context.get(key)
93
+ res = @context.get(name) if res.nil? && name.to_s != key
94
+ res
95
+ elsif @context.is_a?(Hash)
96
+ @context[key] || @context[name] || @context[name.to_s] || @context[name.to_sym]
97
+ elsif @context.respond_to?(:resolve)
98
+ @context.resolve(key)
99
+ elsif @context.respond_to?(:[])
100
+ @context[key] || @context[name]
101
+ end
102
+
103
+ val.nil? ? default : val
104
+ end
105
+
106
+ def has?(name)
107
+ return false if name.nil?
108
+
109
+ # get denies blocked keys (returns the default), so a single gate is
110
+ # enough and the denial logs once.
111
+ !get(name).nil?
112
+ end
113
+
114
+ def satisfied?(dependencies)
115
+ Array(dependencies).all? { |dep| has?(dep) }
116
+ end
117
+
118
+ def coeffect(name)
119
+ get(name)
120
+ end
121
+ end
122
+ end
123
+ end
@@ -4,6 +4,7 @@ require "open3"
4
4
  require "monitor"
5
5
  require "time"
6
6
  require_relative "../platform"
7
+ require_relative "../security/guard" unless defined?(Rubik::Security::Guard)
7
8
 
8
9
  module Rubik
9
10
  module Runtime
@@ -98,7 +99,11 @@ module Rubik
98
99
  @tasks = {}
99
100
  @task_counter = 0
100
101
  @monitor = Monitor.new
101
- @guard = guard
102
+ # Fail-closed fallback (house pattern): a bare construction must never
103
+ # leave the popen3 sink unguarded — a fresh Guard still blocks
104
+ # dangerous/unclassifiable commands, it only lacks the operator
105
+ # allowlist of the injected session guard.
106
+ @guard = guard || Rubik::Security::Guard.new
102
107
  @context = context
103
108
  @root_dir = File.expand_path(root_dir)
104
109
  @max_buffer_lines = max_buffer_lines
@@ -116,7 +121,7 @@ module Rubik
116
121
  cmd_str = command.to_s.strip
117
122
  raise ArgumentError, "Command cannot be empty" if cmd_str.empty?
118
123
 
119
- @guard&.verify_command_safety!(cmd_str)
124
+ @guard.verify_command_safety!(cmd_str)
120
125
 
121
126
  # Each task carries its OWN child context, never the shared runtime
122
127
  # root: Kernel::Init#reap_dead_units! disposes a dead unit's context
data/lib/rubik/runtime.rb CHANGED
@@ -1,10 +1,13 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require_relative "runtime/context"
4
+ require_relative "runtime/synthesized_command_context"
5
+ require_relative "runtime/synthesized_tool_context"
4
6
  require_relative "runtime/fiber"
5
7
  require_relative "runtime/manager"
6
8
  require_relative "runtime/service_definition"
7
9
  require_relative "runtime/service_registration"
10
+ require_relative "runtime/manifest_store"
8
11
  require_relative "runtime/overlay_storage"
9
12
  require_relative "runtime/discovery"
10
13
  require_relative "runtime/diagnostic_engine"
@@ -0,0 +1,167 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "shellwords"
4
+ require_relative "../platform"
5
+ require_relative "classifier"
6
+
7
+ module Rubik
8
+ module Security
9
+ # Operator-controlled command allowlist (Plan: komut-allowlist-güvenlik-kapısı),
10
+ # split out of Guard (#403) as the allowlist leaf: state (@command_allowlist),
11
+ # the AST gate, the raw Shellwords gate, and every token-prefix matcher.
12
+ # Entries are token-prefixes: "node" allows every node invocation (broad);
13
+ # "node .gitnexus/run.cjs" allows only that script (narrow — preferred).
14
+ # Applied AFTER classifier verdict, BEFORE the raise, and the catastrophic
15
+ # fallback regex still runs afterwards (defense-in-depth is never skipped).
16
+ class Allowlist
17
+ # Shell metacharacters that make a raw (AST-less) token-prefix allowlist
18
+ # match dishonest: they can join, redirect, substitute, or line-split
19
+ # the string, so "the first tokens match" would not mean "the whole
20
+ # simple command matches". The classifier-crash rescue only accepts a
21
+ # single simple command; anything else fails closed.
22
+ RAW_ALLOWLIST_UNSAFE_PATTERN = /[;&|<>`$(){}\[\]\\\n\r]/
23
+
24
+ def initialize(entries = [])
25
+ @command_allowlist = normalize_allowlist(entries)
26
+ end
27
+
28
+ def command_allowlist
29
+ @command_allowlist.dup
30
+ end
31
+
32
+ def allowed_commands=(entries)
33
+ @command_allowlist = normalize_allowlist(entries)
34
+ end
35
+ alias set_allowed_commands allowed_commands=
36
+
37
+ def command_allowlisted?(ast, cmd_str: nil)
38
+ _ = cmd_str
39
+ return false if @command_allowlist.empty?
40
+ return false unless ast.respond_to?(:commands)
41
+
42
+ ast_commands = ast.commands.to_a
43
+ return false if ast_commands.empty?
44
+
45
+ # EVERY dangerous segment (recursively incl. pipeline inner commands)
46
+ # must match an entry — a single allowlisted prefix cannot rescue
47
+ # `allowlisted-cmd && rm -rf /` chains.
48
+ ast_commands.all? { |c| command_matches_allowlist?(c) }
49
+ end
50
+
51
+ # Token-prefix allowlist check for an input whose AST does not exist
52
+ # (classifier crashed). Only a single simple command qualifies: with
53
+ # shell metacharacters present the string may hold several segments
54
+ # and the gate's "every segment must match" contract cannot be
55
+ # honored — fail closed instead of over-promising the prefix match.
56
+ # Quoting is handled by Shellwords; an unparseable string (unbalanced
57
+ # quote) fails closed.
58
+ def command_allowlisted_raw?(cmd_str)
59
+ return false if @command_allowlist.empty?
60
+ return false if cmd_str.match?(RAW_ALLOWLIST_UNSAFE_PATTERN)
61
+
62
+ tokens = nil
63
+ begin
64
+ tokens = Shellwords.split(cmd_str)
65
+ rescue ArgumentError
66
+ return false
67
+ end
68
+ return false if tokens.empty?
69
+ return false if Rubik::Security::Classifier::Engine.builtin_dangerous?(tokens[0])
70
+
71
+ allowlist_match_argv?(tokens)
72
+ end
73
+
74
+ private
75
+
76
+ def normalize_allowlist(entries)
77
+ Array(entries).filter_map do |e|
78
+ tokens = e.to_s.strip.split(/\s+/).reject(&:empty?)
79
+ tokens unless tokens.empty?
80
+ end
81
+ end
82
+
83
+ def canonical_binary_path(bin)
84
+ return nil if bin.nil? || bin.to_s.empty?
85
+
86
+ str = bin.to_s
87
+ if str.include?("/") || str.include?("\\") || File.exist?(str)
88
+ Rubik::Platform.normalize_path(File.expand_path(str))
89
+ else
90
+ resolved = Rubik::Platform.which(str)
91
+ resolved ? Rubik::Platform.normalize_path(resolved) : nil
92
+ end
93
+ end
94
+
95
+ def binary_allowlist_match?(arg, token)
96
+ return true if arg == token
97
+ # Windows exe-alias fast path (#103): on a windows host "node.exe"
98
+ # IS the allowlisted "node" — a lexical alias, no filesystem probe.
99
+ # The canonical-path probe below resolves through Platform.which +
100
+ # File.file?, a second host seam the windows? stub cannot cover (a
101
+ # linux host has no node.exe on disk, so the probe fails and the
102
+ # allowlist would dead-close). On a posix host the alias is FALSE:
103
+ # node.exe is a different binary than node there.
104
+ return true if windows_executable_alias?(arg, token)
105
+
106
+ c_arg = canonical_binary_path(arg)
107
+ c_token = canonical_binary_path(token)
108
+
109
+ return true if c_arg && c_token && Rubik::Platform.path_equal?(c_arg, c_token)
110
+
111
+ false
112
+ end
113
+
114
+ # True when arg carries an executable extension from PATHEXT and its
115
+ # stem equals the token (case-insensitive — windows path semantics).
116
+ # Bare stems only: a path-form arg ("C:/x/node.exe") keeps going
117
+ # through the canonical-path probe, which resolves both sides.
118
+ def windows_executable_alias?(arg, token)
119
+ return false unless Rubik::Platform.windows?
120
+
121
+ ext = ::File.extname(arg)
122
+ return false if ext.empty? || !Rubik::Platform.pathext.include?(ext.downcase)
123
+
124
+ arg.delete_suffix(ext).casecmp?(token)
125
+ end
126
+
127
+ def command_matches_allowlist?(result)
128
+ # Missing argv (e.g. empty invocation) can never be allowlisted.
129
+ argv = result.respond_to?(:argv) ? result.argv : nil
130
+ return false if argv.nil? || argv.empty?
131
+
132
+ # Dangerous shell builtins (`source`, `.`) are never rescuable by
133
+ # allowlist: they execute arbitrary file content by design.
134
+ return false if Rubik::Security::Classifier::Engine.builtin_dangerous?(argv[0])
135
+
136
+ # W6: If this command wraps inner commands, EVERY inner command must also match allowlist
137
+ if result.respond_to?(:inner_commands) && result.inner_commands && !result.inner_commands.empty? && !result.inner_commands.all? do |inner|
138
+ command_matches_allowlist?(inner)
139
+ end
140
+ return false
141
+ end
142
+
143
+ allowlist_match_argv?(argv)
144
+ end
145
+
146
+ # The single token-prefix matching home shared by the AST path
147
+ # (#command_matches_allowlist?) and the raw Shellwords path
148
+ # (#command_allowlisted_raw?) — two callers, one contract: an entry
149
+ # matches when its tokens are a prefix of argv (position 0 through the
150
+ # binary canonical-path probe, the rest by equality).
151
+ def allowlist_match_argv?(argv)
152
+ @command_allowlist.any? do |entry|
153
+ next false if entry.length > argv.length
154
+
155
+ entry.each_with_index.all? do |token, i|
156
+ arg = argv[i]
157
+ if i.zero?
158
+ binary_allowlist_match?(arg, token)
159
+ else
160
+ arg == token
161
+ end
162
+ end
163
+ end
164
+ end
165
+ end
166
+ end
167
+ end
@@ -0,0 +1,72 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "time"
5
+ require "fileutils"
6
+ require_relative "../platform"
7
+ require_relative "redactor"
8
+
9
+ module Rubik
10
+ module Security
11
+ # The shared audit leaf of the Guard split (#403): owns the audit
12
+ # destination (@audit_log_path), secret masking, and the JSONL append.
13
+ # Every other security module (PathPolicy, CommandGate, SynthesisGate)
14
+ # receives an instance of this class and routes its log_audit calls
15
+ # through it — the audit trail has exactly one home.
16
+ class AuditLog
17
+ MASK_PATTERNS = Rubik::Security::Redactor::PATTERNS
18
+
19
+ attr_reader :audit_log_path
20
+
21
+ # Default audit location, resolved at call time (not a load-time
22
+ # constant) so Platform.home_dir stubs in tests and runtime HOME
23
+ # changes are honored. Single source shared by the constructor
24
+ # default and Guard.for_config.
25
+ def self.default_audit_log_path
26
+ File.join(Rubik::Platform.home_dir, ".rubik", "audit.log")
27
+ end
28
+
29
+ def initialize(audit_log_path = AuditLog.default_audit_log_path)
30
+ @audit_log_path = audit_log_path
31
+ end
32
+
33
+ # Live-reconfigurable audit destination (ConfigWiring applies config
34
+ # changes in place — zero restart). Same blank-means-disabled semantics
35
+ # as for_config; non-string values pass through and surface loudly in
36
+ # log_audit's unconditional warn.
37
+ def audit_log_path=(val)
38
+ @audit_log_path = val.is_a?(String) && val.strip.empty? ? nil : val
39
+ end
40
+
41
+ def mask_text(text)
42
+ Rubik::Security::Redactor.redact(text)
43
+ end
44
+
45
+ def log_audit(action, details = {})
46
+ return if @audit_log_path.nil? || @audit_log_path.to_s.strip.empty?
47
+
48
+ # Nil-safety: a nil details hash (or nil value) must never crash the
49
+ # command path — audit failure is already swallowed below.
50
+ masked_details = (details || {}).transform_values { |v| v.nil? ? "" : mask_text(v.to_s) }
51
+
52
+ entry = {
53
+ ts: Time.now.iso8601,
54
+ action: action,
55
+ details: masked_details
56
+ }
57
+
58
+ dir = File.dirname(@audit_log_path)
59
+ FileUtils.mkdir_p(dir) unless File.directory?(dir)
60
+
61
+ File.open(@audit_log_path, "a") do |f|
62
+ f.puts(JSON.dump(entry))
63
+ end
64
+ rescue StandardError => e
65
+ # Unconditional: an audit trail failing silently is indistinguishable
66
+ # from an operator's intentional disable — the one warn in the guard
67
+ # that must not hide behind RUBIK_DEBUG.
68
+ warn "[WARN] Failed to write audit log #{@audit_log_path}: #{e.message}"
69
+ end
70
+ end
71
+ end
72
+ end
@@ -29,10 +29,22 @@ module Rubik
29
29
  @default_database ||= CommandDatabase.new
30
30
  end
31
31
 
32
+ def self.reset_database!
33
+ @default_database = nil
34
+ end
35
+
32
36
  def self.classify_expression(expression, database: nil, shell: nil)
33
37
  new(database: database, shell: shell).classify(expression)
34
38
  end
35
39
 
40
+ # Public interface predicate over the Matcher's builtin vocabulary.
41
+ # External gates (e.g. Guard's allowlist) depend on this instead of
42
+ # reaching into Matcher::BUILTIN_DANGEROUS_CMDS — a non-interface
43
+ # constant of another module.
44
+ def self.builtin_dangerous?(binary)
45
+ Matcher::BUILTIN_DANGEROUS_CMDS.include?(binary.to_s)
46
+ end
47
+
36
48
  def initialize(database: nil, shell: nil)
37
49
  @database = database || self.class.default_database
38
50
  @shell = shell
@@ -349,11 +361,14 @@ module Rubik
349
361
 
350
362
  p = p[1..-2] if (p.start_with?('"') && p.end_with?('"')) || (p.start_with?("'") && p.end_with?("'"))
351
363
  return false if p.empty? || p.start_with?("-")
352
- return false if !p.include?("..") && temp_path?(p)
364
+ return false if !p.include?("..") && (temp_path?(p) || DEV_PATHS.any? { |dev| p == dev || p.start_with?(dev) })
365
+
366
+ # Bare drive prefix without separator is NOT a drive root or system path
367
+ return false if p =~ %r{\A[a-zA-Z]:(?![\\/])}
353
368
 
354
369
  return true if p =~ %r{\A/(?:\*|\.+)?/?\z}
355
- return true if p =~ %r{\A[a-zA-Z]:(?:[\\/]|\*|\.+)?\z}i
356
- return true if HOME_TOKENS.include?(p)
370
+ return true if p =~ %r{\A[a-zA-Z]:[\\/](?:\*|\.+)?\z}i
371
+ return true if HOME_TOKENS.include?(p) || p.start_with?("~/", "$HOME/", "${HOME}/")
357
372
 
358
373
  if p =~ %r{\A([a-zA-Z]):[/\\](.*)\z}
359
374
  parts = []
@@ -361,11 +376,11 @@ module Rubik
361
376
  win_norm = "#{Regexp.last_match(1).downcase}:/#{parts.join('/')}".downcase
362
377
  return false if win_norm.include?("/appdata/local/temp/") || win_norm.end_with?("/appdata/local/temp")
363
378
 
364
- return true if win_norm =~ %r{\A[a-z]:/(?:windows|program files|program files \(x86\)|system32)(?:/|\z)} ||
365
- win_norm =~ %r{\A[a-z]:/users/?(?:\*|\.+)?/?\z} ||
366
- win_norm =~ %r{\A[a-z]:/?(?:\*|\.+)?/?\z}
367
-
368
- return false
379
+ if win_norm =~ %r{\A[a-z]:/(?:windows|program files|program files \(x86\)|system32)(?:/|\z)} ||
380
+ win_norm =~ %r{\A[a-z]:/users/?(?:\*|\.+)?/?\z} ||
381
+ win_norm =~ %r{\A[a-z]:/?(?:\*|\.+)?/?\z}
382
+ return true
383
+ end
369
384
  end
370
385
 
371
386
  expanded = safe_expand_path(p)
@@ -382,6 +397,7 @@ module Rubik
382
397
 
383
398
  false
384
399
  end
400
+ public :system_path?
385
401
 
386
402
  def safe_expand_path(path)
387
403
  File.expand_path(path)