rubik 0.8.1 → 0.9.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 (107) hide show
  1. checksums.yaml +4 -4
  2. data/ATTRIBUTION.md +2 -2
  3. data/CHANGELOG.md +100 -1
  4. data/bin/rubik +15 -10
  5. data/lib/rubik/cli/workspace_trust.rb +1 -0
  6. data/lib/rubik/concurrency/worker.rb +143 -0
  7. data/lib/rubik/concurrency.rb +1 -0
  8. data/lib/rubik/config/deep_ops.rb +17 -0
  9. data/lib/rubik/config/defaults.rb +0 -1
  10. data/lib/rubik/config/schema.rb +0 -1
  11. data/lib/rubik/config.rb +7 -3
  12. data/lib/rubik/context/repo_context_reader.rb +27 -8
  13. data/lib/rubik/events.rb +18 -0
  14. data/lib/rubik/kernel/unit.rb +4 -3
  15. data/lib/rubik/orchestrator/auto_apply.rb +2 -0
  16. data/lib/rubik/orchestrator/budget_manager.rb +18 -2
  17. data/lib/rubik/orchestrator/goal_ledger/deep_ops.rb +41 -0
  18. data/lib/rubik/orchestrator/goal_ledger/drift.rb +2 -1
  19. data/lib/rubik/orchestrator/goal_ledger/ledger.rb +56 -50
  20. data/lib/rubik/orchestrator/goal_ledger/observation_projection.rb +26 -0
  21. data/lib/rubik/orchestrator/goal_ledger/patch.rb +10 -17
  22. data/lib/rubik/orchestrator/goal_ledger/suspend_lifecycle.rb +9 -41
  23. data/lib/rubik/orchestrator/goal_ledger/validator.rb +6 -20
  24. data/lib/rubik/orchestrator/goal_ledger/verifier.rb +3 -14
  25. data/lib/rubik/orchestrator/goal_ledger/xml_render.rb +21 -14
  26. data/lib/rubik/orchestrator/goal_state.rb +15 -15
  27. data/lib/rubik/orchestrator/loop.rb +62 -63
  28. data/lib/rubik/orchestrator/lsp_feedback.rb +7 -1
  29. data/lib/rubik/orchestrator/subagent/admission_policy.rb +161 -0
  30. data/lib/rubik/orchestrator/subagent/builtin_types.rb +3 -2
  31. data/lib/rubik/orchestrator/subagent/notices.rb +5 -4
  32. data/lib/rubik/orchestrator/subagent/profile_contract.rb +4 -10
  33. data/lib/rubik/orchestrator/subagent/run_cycle.rb +22 -1
  34. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +34 -2
  35. data/lib/rubik/orchestrator/subagent/type_registry.rb +19 -1
  36. data/lib/rubik/orchestrator/turn_executor/subagent_channel.rb +6 -1
  37. data/lib/rubik/orchestrator/turn_executor/user_channel.rb +6 -1
  38. data/lib/rubik/orchestrator/turn_executor.rb +2 -1
  39. data/lib/rubik/platform/path.rb +0 -1
  40. data/lib/rubik/prompt/context_builder.rb +24 -18
  41. data/lib/rubik/prompt/context_compactor.rb +31 -8
  42. data/lib/rubik/prompt/conversation_rows.rb +33 -0
  43. data/lib/rubik/prompt/doctrine.rb +4 -2
  44. data/lib/rubik/prompt/emergency_compactor.rb +5 -4
  45. data/lib/rubik/repl/commands/agent_execution.rb +13 -2
  46. data/lib/rubik/repl/commands/buffer.rb +4 -0
  47. data/lib/rubik/repl/commands/mcp.rb +5 -0
  48. data/lib/rubik/repl/commands/subagents.rb +4 -4
  49. data/lib/rubik/repl/commands/workspace.rb +22 -2
  50. data/lib/rubik/repl/config_wiring.rb +24 -7
  51. data/lib/rubik/repl/input_execution.rb +1 -1
  52. data/lib/rubik/repl/lifecycle.rb +3 -2
  53. data/lib/rubik/repl/pruner/harness.rb +52 -67
  54. data/lib/rubik/repl/pruner/rules.rb +3 -1
  55. data/lib/rubik/repl/service_catalog.rb +1 -1
  56. data/lib/rubik/repl/synthesized_command_context.rb +3 -0
  57. data/lib/rubik/repl/turn_recorder.rb +5 -4
  58. data/lib/rubik/repl.rb +1 -0
  59. data/lib/rubik/runtime/context.rb +5 -0
  60. data/lib/rubik/runtime/discovery.rb +55 -0
  61. data/lib/rubik/runtime/overlay_storage.rb +54 -23
  62. data/lib/rubik/runtime/repair_probe.rb +20 -2
  63. data/lib/rubik/runtime/sealed_coeffects.rb +58 -0
  64. data/lib/rubik/runtime/synthesized_command_context.rb +80 -0
  65. data/lib/rubik/runtime/synthesized_tool_context.rb +123 -0
  66. data/lib/rubik/runtime.rb +2 -0
  67. data/lib/rubik/security/classifier/classifier.rb +16 -8
  68. data/lib/rubik/security/classifier/commands/biome.yaml +49 -0
  69. data/lib/rubik/security/classifier/commands/bun.yaml +91 -0
  70. data/lib/rubik/security/classifier/commands/bundle.yaml +107 -0
  71. data/lib/rubik/security/classifier/commands/clang-format.yaml +21 -0
  72. data/lib/rubik/security/classifier/commands/clang.yaml +37 -0
  73. data/lib/rubik/security/classifier/commands/cmake.yaml +37 -0
  74. data/lib/rubik/security/classifier/commands/ctest.yaml +30 -0
  75. data/lib/rubik/security/classifier/commands/gcc.yaml +36 -0
  76. data/lib/rubik/security/classifier/commands/gem.yaml +104 -0
  77. data/lib/rubik/security/classifier/commands/gofmt.yaml +15 -0
  78. data/lib/rubik/security/classifier/commands/pnpm.yaml +8 -8
  79. data/lib/rubik/security/classifier/commands/python.yaml +18 -1
  80. data/lib/rubik/security/classifier/commands/python3.yaml +18 -1
  81. data/lib/rubik/security/classifier/commands/rake.yaml +60 -0
  82. data/lib/rubik/security/classifier/commands/rspec.yaml +42 -0
  83. data/lib/rubik/security/classifier/commands/rubocop.yaml +38 -0
  84. data/lib/rubik/security/classifier/commands/ruby.yaml +25 -0
  85. data/lib/rubik/security/classifier/commands/rustc.yaml +34 -0
  86. data/lib/rubik/security/classifier/commands/zig.yaml +77 -0
  87. data/lib/rubik/security/classifier/database.rb +12 -1
  88. data/lib/rubik/security/classifier/matcher.rb +17 -2
  89. data/lib/rubik/security/classifier/models.rb +3 -2
  90. data/lib/rubik/security/classifier.rb +5 -0
  91. data/lib/rubik/security/guard.rb +133 -39
  92. data/lib/rubik/storage/vakanuvis/harness.rb +49 -89
  93. data/lib/rubik/tools/base.rb +24 -7
  94. data/lib/rubik/tools/builtins/files.rb +2 -0
  95. data/lib/rubik/tools/builtins/goal_ledger.rb +9 -9
  96. data/lib/rubik/tools/builtins/lifecycle.rb +1 -1
  97. data/lib/rubik/tools/builtins/synthesis.rb +121 -64
  98. data/lib/rubik/tools/builtins/unsynthesize.rb +38 -0
  99. data/lib/rubik/tools/catalog.rb +3 -0
  100. data/lib/rubik/tools/declaration.rb +6 -2
  101. data/lib/rubik/tools/preflight_runner.rb +107 -14
  102. data/lib/rubik/tools/registry.rb +2 -0
  103. data/lib/rubik/tools/uri_resolver.rb +3 -1
  104. data/lib/rubik/uris.rb +5 -1
  105. data/lib/rubik/version.rb +1 -1
  106. data/lib/rubik.rb +1 -0
  107. metadata +25 -1
@@ -14,6 +14,8 @@ module Rubik
14
14
  class Guard
15
15
  DEFAULT_CRITICAL_PATTERNS = [
16
16
  ".git/**",
17
+ ".rubik/**",
18
+ "**/.rubik/**",
17
19
  ".env*",
18
20
  "secrets.*",
19
21
  "*.pem",
@@ -95,6 +97,7 @@ module Rubik
95
97
  # Unmanaged background threads survive context disposal — the exact
96
98
  # "Leaked Side Effects" anti-pattern (AGENTS.md §5).
97
99
  /\bThread\s*\.\s*(?:new|fork|start)\b/,
100
+ /\bPathname\s*\(/,
98
101
  /`[^`]*`/,
99
102
  Regexp.new('%x\s*[({\[<|/]', Regexp::IGNORECASE)
100
103
  ].freeze
@@ -117,6 +120,7 @@ module Rubik
117
120
  RAW_ALLOWLIST_UNSAFE_PATTERN = /[;&|<>`$(){}\[\]\\\n\r]/
118
121
 
119
122
  attr_reader :audit_log_path
123
+ attr_accessor :shell, :root_dir
120
124
 
121
125
  # Live-reconfigurable audit destination (ConfigWiring applies config
122
126
  # changes in place — zero restart). Same blank-means-disabled semantics
@@ -144,7 +148,7 @@ module Rubik
144
148
  # suppresses on nil/empty. (The previous composition call site's
145
149
  # `fetch(...) || default` silently re-enabled auditing an operator had
146
150
  # turned off.)
147
- def self.for_config(config)
151
+ def self.for_config(config, root_dir: nil, shell: nil)
148
152
  return new if config.nil? || !config.respond_to?(:fetch)
149
153
 
150
154
  raw_audit = config.fetch("security.audit_log_path", default_audit_log_path)
@@ -160,20 +164,49 @@ module Rubik
160
164
  warn "[Guard] security.audit_log_path has non-path value #{raw_audit.inspect}; auditing disabled"
161
165
  nil
162
166
  end
167
+
168
+ effective_root = root_dir || (config.respond_to?(:root_dir) ? config.root_dir : nil)
169
+
163
170
  new(
164
171
  audit_log_path: audit_path,
165
172
  command_allowlist: Array(config.fetch("security.command_allowlist", [])),
166
173
  # Stringy "false" from persisted config must disable probes too.
167
- allow_safe_probes: config.fetch("security.allow_safe_probes", true).to_s.downcase != "false"
174
+ allow_safe_probes: config.fetch("security.allow_safe_probes", true).to_s.downcase != "false",
175
+ root_dir: effective_root,
176
+ shell: shell
168
177
  )
169
178
  end
170
179
 
171
180
  def initialize(custom_patterns: [], command_allowlist: [], allow_safe_probes: true,
172
- audit_log_path: Guard.default_audit_log_path)
181
+ audit_log_path: Guard.default_audit_log_path, root_dir: nil, shell: nil)
173
182
  @critical_patterns = (DEFAULT_CRITICAL_PATTERNS + custom_patterns).uniq
174
183
  @command_allowlist = normalize_allowlist(command_allowlist)
175
184
  @allow_safe_probes = allow_safe_probes == true
176
185
  @audit_log_path = audit_log_path
186
+ @root_dir = root_dir
187
+ @shell = shell
188
+ end
189
+
190
+ def workspace_trust_candidate_allowed?(cmd_str, ast = nil)
191
+ return false if cmd_str.to_s.match?(RAW_ALLOWLIST_UNSAFE_PATTERN)
192
+
193
+ ast ||= begin
194
+ Rubik::Security::Classifier.classify(cmd_str.to_s)
195
+ rescue StandardError
196
+ nil
197
+ end
198
+ return false unless ast
199
+ return false if ast.respond_to?(:parse_warnings) && ast.parse_warnings.to_a.any?
200
+ return false unless ast.respond_to?(:commands) && ast.commands.to_a.size == 1
201
+
202
+ cmd = ast.commands.first
203
+ return false if cmd.respond_to?(:inner_commands) && cmd.inner_commands && !cmd.inner_commands.empty?
204
+
205
+ effective_root = @root_dir || Dir.pwd
206
+ return false unless defined?(Rubik::CLI::WorkspaceTrust) && Rubik::CLI::WorkspaceTrust.trusted?(effective_root)
207
+ return false unless defined?(Rubik::Runtime::Discovery)
208
+
209
+ Rubik::Runtime::Discovery.recognized_candidate?(cmd_str, root_dir: effective_root)
177
210
  end
178
211
 
179
212
  # security.allow_safe_probes — operator-managed toggle (live-reconfigurable
@@ -390,17 +423,42 @@ module Rubik
390
423
  end
391
424
  end
392
425
 
393
- # allow_unknown: the ONLY sanctioned true is the synthesis pre-check —
394
- # Ruby source ("->(args) { … }") legitimately classifies UNKNOWN through
395
- # the shell classifier, and synthesis carries its own deny layers
396
- # (DANGEROUS_SYNTHESIS_PATTERNS + AST walk). Shell-gate callers must keep
397
- # the default: an UNKNOWN verdict means an unvetted binary, and a binary
398
- # the database cannot classify is exactly the one that must not run
399
- # without operator approval.
426
+ def check_critical_path_writes!(ast, cmd_str)
427
+ ast_commands = ast.respond_to?(:commands) ? ast.commands.to_a : []
428
+ write_targets = ast_commands.flat_map do |c|
429
+ targets = Array(c.respond_to?(:write_paths) ? c.write_paths : nil)
430
+ cmd_name = c.respond_to?(:command) ? c.command.to_a.first.to_s : ""
431
+ targets.concat(c.positionals.to_a) if ["cp", "mv", "tee", "touch", "ln", "install"].include?(cmd_name) && c.respond_to?(:positionals)
432
+ targets
433
+ end.compact.reject(&:empty?)
434
+
435
+ write_targets.concat(ast.write_paths.to_a) if ast.respond_to?(:write_paths)
436
+
437
+ write_targets.uniq.each do |wp|
438
+ next unless critical_path?(wp)
439
+
440
+ log_audit("blocked_command", command: cmd_str, reason: "critical_path_write", path: wp)
441
+ raise BlockedWriteError.new(
442
+ "Command write to critical path blocked: #{wp} in `#{cmd_str}`",
443
+ kind: :critical_path_write,
444
+ blocked_command: cmd_str,
445
+ path: wp
446
+ )
447
+ end
448
+ end
449
+
450
+ # allow_unknown: synthesis verification no longer routes through the
451
+ # shell gate (it has its own deny layers: DANGEROUS_SYNTHESIS_PATTERNS
452
+ # + AST walk), so no production caller passes true today. The flag
453
+ # remains a tested seam for future in-gate verifiers of non-shell
454
+ # source; shell-gate callers must keep the default: an UNKNOWN verdict
455
+ # means an unvetted binary, and a binary the database cannot classify
456
+ # is exactly the one that must not run without operator approval.
400
457
  def verify_command_safety!(cmd, shell: nil, allow_unknown: false)
401
458
  cmd_str = cmd.to_s
402
459
  begin
403
460
  ast = Rubik::Security::Classifier.classify(cmd_str, shell: shell)
461
+ check_critical_path_writes!(ast, cmd_str)
404
462
  if ast.classification == :dangerous
405
463
  # Safe-probe exemption (highest-priority friction fix): run the
406
464
  # catastrophic fallback regex first — it never loosens.
@@ -480,6 +538,36 @@ module Rubik
480
538
  verify_command_fallback_regex!(cmd_str)
481
539
  return true
482
540
  end
541
+
542
+ # Workspace Trust Discovery Recognition Gate:
543
+ if workspace_trust_candidate_allowed?(cmd_str, ast)
544
+ log_audit("allowed_command", command: cmd_str, reason: "workspace_trust_discovery")
545
+ verify_command_fallback_regex!(cmd_str)
546
+ return true
547
+ end
548
+
549
+ # Interactive operator approval gate (Antigravity-style single keypress)
550
+ effective_shell = shell || @shell
551
+ if effective_shell.respond_to?(:interactive_input?) && effective_shell.interactive_input?
552
+ # Defense-in-depth: Un-bypassable catastrophic fallback regex MUST pass before prompt
553
+ verify_command_fallback_regex!(cmd_str)
554
+
555
+ theme = (effective_shell.respond_to?(:ui_theme) && effective_shell.ui_theme) ||
556
+ (defined?(Rubik::UI::Theme) ? Rubik::UI::Theme.new : nil)
557
+
558
+ question = "Allow unclassified command execution: '#{cmd_str}'?"
559
+ answer = if defined?(Rubik::UI::Approvals)
560
+ Rubik::UI::Approvals.keypress_yes_no(effective_shell, question, theme: theme, default: "n")
561
+ else
562
+ "n"
563
+ end
564
+
565
+ if ["y", "yes"].include?(answer.to_s.downcase)
566
+ log_audit("allowed_command", command: cmd_str, reason: "operator_interactive_approval")
567
+ return true
568
+ end
569
+ end
570
+
483
571
  log_audit("blocked_command", command: cmd_str, reason: "unknown_command")
484
572
  raise BlockedWriteError.new(
485
573
  "Unknown command execution blocked (fail-closed): #{cmd_str}. The binary is not in the " \
@@ -531,9 +619,9 @@ module Rubik
531
619
  # security-observable downgrade nobody should need RUBIK_DEBUG to
532
620
  # notice. The shell gate fails closed — an exception must never
533
621
  # mint execution permission; the operator allowlist is the one
534
- # sanctioned valve. The synthesis seam (allow_unknown) keeps
535
- # flowing into its own deny layers (DANGEROUS_SYNTHESIS_PATTERNS
536
- # + RubyVM walk), which run after this gate.
622
+ # sanctioned valve. The allow_unknown seam (no production caller
623
+ # today) keeps flowing into its own deny layers
624
+ # (DANGEROUS_SYNTHESIS_PATTERNS + RubyVM walk) after this gate.
537
625
  if allow_unknown
538
626
  warn "[WARN] AST classification error on non-shell input, continuing to synthesis deny layers: #{e.message}"
539
627
  log_audit("classifier_error", command: cmd_str, reason: "#{e.class}: #{e.message}",
@@ -854,14 +942,16 @@ module Rubik
854
942
  SynthesisCapability.new(
855
943
  name: :dynamic_execution,
856
944
  reason: "string eval and Binding turn data into code outside the AST walk",
857
- calls: [:eval, :instance_eval, :class_eval, :module_eval, :binding]
945
+ calls: [:eval, :instance_eval, :class_eval, :module_eval, :binding,
946
+ :instance_exec, :class_exec, :module_exec, :define_method, :define_singleton_method]
858
947
  ),
859
948
  SynthesisCapability.new(
860
949
  name: :process_control,
861
950
  reason: "subprocess spawn and process lifecycle control escape the sandbox and audit trail; " \
862
951
  "trap/at_exit install process-wide hooks the host cannot revert — Signal.trap can " \
863
- "swallow the host REPL's Interrupt/exit handling",
864
- calls: [:system, :exec, :spawn, :fork, :syscall, :exit!, :trap, :at_exit,
952
+ "swallow the host REPL's Interrupt/exit handling; exit/exit! can kill the host " \
953
+ "when preflight runs in-process",
954
+ calls: [:system, :exec, :spawn, :fork, :syscall, :exit, :exit!, :trap, :at_exit,
865
955
  :popen, :capture2, :capture2e, :capture3, :popen2, :popen2e,
866
956
  :popen3, :pipeline, :kill, :daemon],
867
957
  consts: [:Process, :Thread, :Signal, :Open3]
@@ -870,7 +960,8 @@ module Rubik
870
960
  name: :reflection,
871
961
  reason: "send/method-object families bypass static call-name checks (the method(:x).call escape)",
872
962
  calls: [:send, :public_send, :__send__,
873
- :method, :public_method, :singleton_method]
963
+ :method, :public_method, :singleton_method,
964
+ :instance_method, :public_instance_method, :bind, :bind_call]
874
965
  ),
875
966
  SynthesisCapability.new(
876
967
  name: :state_introspection,
@@ -886,8 +977,9 @@ module Rubik
886
977
  SynthesisCapability.new(
887
978
  name: :filesystem,
888
979
  reason: "raw file/IO handles bypass the OutputView and every guard write check",
889
- calls: [:open, :read, :write, :binread, :binwrite, :delete, :unlink, :rm_rf],
890
- consts: [:IO, :File, :Dir, :FileUtils, :STDIN, :STDOUT, :STDERR, :ARGF]
980
+ calls: [:open, :read, :write, :binread, :binwrite, :unlink, :rm_rf, :rmtree,
981
+ :sysopen, :syswrite, :sysread, :readlines, :foreach, :Pathname],
982
+ consts: [:IO, :File, :Dir, :FileUtils, :STDIN, :STDOUT, :STDERR, :ARGF, :Pathname]
891
983
  ),
892
984
  SynthesisCapability.new(
893
985
  name: :code_loading,
@@ -901,7 +993,7 @@ module Rubik
901
993
  SynthesisCapability.new(
902
994
  name: :runtime_root,
903
995
  reason: "core runtime singletons (Kernel/RubyVM/Class/Module/...) re-open every denied capability",
904
- consts: [:Kernel, :RubyVM, :Object, :Class, :Module, :BasicObject]
996
+ consts: [:Kernel, :RubyVM, :Object, :Class, :Module, :BasicObject, :Rubik, :Fiber, :TracePoint, :GC]
905
997
  ),
906
998
  SynthesisCapability.new(
907
999
  name: :ambient_state,
@@ -963,20 +1055,13 @@ module Rubik
963
1055
  # Reject synthesized Ruby before it is ever eval'd.
964
1056
  #
965
1057
  # Defense-in-depth architecture:
966
- # 1. verify_command_safety! checks shell command patterns.
967
- # 2. Fast regex pattern matching (DANGEROUS_SYNTHESIS_PATTERNS) intercepts known keywords.
968
- # 3. RubyVM::AbstractSyntaxTree semantic walk checks normalized node types, method calls,
1058
+ # 1. Fast regex pattern matching (DANGEROUS_SYNTHESIS_PATTERNS) intercepts known keywords.
1059
+ # 2. RubyVM::AbstractSyntaxTree semantic walk checks normalized node types, method calls,
969
1060
  # and receiver constants against explicit deny rules to block AST-level evasion vectors.
970
1061
  #
971
1062
  # Raises Rubik::Security::BlockedWriteError with an actionable message.
972
1063
  def verify_synthesis_safety!(code)
973
1064
  code_str = code.to_s
974
- # allow_unknown: synthesized Ruby is not shell — its UNKNOWN verdicts
975
- # are "not shell-shaped" noise (see verify_command_safety! comment).
976
- # The shell-classifier layer here still blocks dangerous shapes and
977
- # still runs the catastrophic regex; synthesis-specific escapes are
978
- # denied by DANGEROUS_SYNTHESIS_PATTERNS and the AST walk below.
979
- verify_command_safety!(code_str, allow_unknown: true)
980
1065
 
981
1066
  matched = DANGEROUS_SYNTHESIS_PATTERNS.find { |p| code_str.match?(p) }
982
1067
  if matched
@@ -1012,11 +1097,16 @@ module Rubik
1012
1097
 
1013
1098
  case type
1014
1099
  when :const, :colon3
1015
- # :const covers Net::HTTP / Marshal.dump receivers and `X = Socket`
1016
- # RHS values; :colon3 covers top-level scoped `::TCPSocket` — the
1017
- # one-character bypass (children[0] is the name symbol in both).
1100
+ # :const covers Net::HTTP / Marshal.dump receivers, `X = Socket`
1101
+ # RHS values, and local aliasing `k = Kernel`; :colon3 covers top-level scoped `::TCPSocket`.
1018
1102
  name = node.children[0]
1019
- reject_unsafe(node, "reference to forbidden constant :#{name}") if FORBIDDEN_SYNTHESIS_NETWORK_CONSTS.include?(name)
1103
+ forbidden_const = FORBIDDEN_SYNTHESIS_NETWORK_CONSTS.include?(name) || FORBIDDEN_SYNTHESIS_CONSTS.include?(name)
1104
+ reject_unsafe(node, "reference to forbidden constant :#{name}") if forbidden_const
1105
+ when :colon2
1106
+ # Scoped constant reference like Rubik::Security::Guard
1107
+ name = node.children[1]
1108
+ forbidden_const = FORBIDDEN_SYNTHESIS_NETWORK_CONSTS.include?(name) || FORBIDDEN_SYNTHESIS_CONSTS.include?(name)
1109
+ reject_unsafe(node, "reference to forbidden constant :#{name}") if forbidden_const
1020
1110
  when :fcall, :vcall
1021
1111
  name = node.children[0]
1022
1112
  reject_unsafe(node, "call to :#{name}") if FORBIDDEN_SYNTHESIS_CALLS.include?(name)
@@ -1027,12 +1117,16 @@ module Rubik
1027
1117
 
1028
1118
  reject_unsafe(node, "call to :#{name}") if FORBIDDEN_SYNTHESIS_CALLS.include?(name)
1029
1119
 
1030
- # Receiver const check must accept BOTH const node shapes: :const
1031
- # (Net::HTTP) and :colon3 (::ENV, ::Thread.new, ::Kernel.require —
1032
- # top-level scoping would otherwise re-open every denylist entry).
1033
- if recv.respond_to?(:type) && [:const, :colon3].include?(recv.type.to_s.downcase.to_sym)
1034
- const_name = recv.children[0]
1035
- reject_unsafe(node, "access to #{const_name}.#{name}") if FORBIDDEN_SYNTHESIS_CONSTS.include?(const_name)
1120
+ # Receiver const check must accept const node shapes: :const, :colon3, and :colon2
1121
+ if recv.respond_to?(:type)
1122
+ recv_type = recv.type.to_s.downcase.to_sym
1123
+ if [:const, :colon3].include?(recv_type)
1124
+ const_name = recv.children[0]
1125
+ reject_unsafe(node, "access to #{const_name}.#{name}") if FORBIDDEN_SYNTHESIS_CONSTS.include?(const_name)
1126
+ elsif recv_type == :colon2
1127
+ const_name = recv.children[1]
1128
+ reject_unsafe(node, "access to #{const_name}.#{name}") if FORBIDDEN_SYNTHESIS_CONSTS.include?(const_name)
1129
+ end
1036
1130
  end
1037
1131
  end
1038
1132
 
@@ -1,31 +1,39 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  require "monitor"
4
+ require_relative "../../concurrency"
5
+ require_relative "../../events"
4
6
 
5
7
  module Rubik
6
8
  module Storage
7
9
  module Vakanuvis
8
- # Düzlem 1 — Deterministik Çekirdek: tek worker thread + sınırlı FIFO kuyruk.
9
- # Olay kapıları mevcut bus abonelikleridir (subagent tamamlanma + goal
10
- # bitişi — K3); NE ZAMAN, NEREYE, NASIL yazılacağı burada kural tabanlıdır.
10
+ # Düzlem 1 — Deterministik Çekirdek: tek worker thread + sınırlı FIFO
11
+ # kuyruk (Concurrency::Worker iskeleti: atomik kabul, idempotent
12
+ # kapanış, busy sayımı ve son-çare ağı iskelettedir). Olay kapıları
13
+ # mevcut bus abonelikleridir (subagent tamamlanma + goal bitişi — K3);
14
+ # NE ZAMAN, NEREYE, NASIL yazılacağı burada kural tabanlıdır.
11
15
  # Sessizlik sözleşmesi (§4.3): WAKE_KINDS dışında kalır, notice yaymaz —
12
16
  # sadece dmesg/stderr. Ömür: ctx dispose'u LIFO ile kapatır (worker kill + abonelik geri alımı).
13
17
  class Harness
14
- STOP = :__vakanuvis_stop__
18
+ include Concurrency::Worker
19
+
20
+ # STOP işareti iskeletin tek ev sahibinde; sabit adı kuyruk gözetimi
21
+ # ve test ikizleri için yaşar.
22
+ STOP = Concurrency::Worker::STOP
15
23
  MAX_QUEUE = 200
16
24
  # v2 §4-V4: damıtıcı kaynak disiplini — yalnız TAMAMLANMIŞ transcript'ler,
17
25
  # damıtıcının kendisi Hariç (özyineleme kirliliği: canlı depoda transcript satırları 'vakanuvis' etiketi taşır).
18
26
  SOURCE_TRANSCRIPT_LIMIT = 8
19
- # Literaller, depolama katmanını orchestrator require'larından
20
- # uzak tutar; test ikizleri her ikisini de sabitlere pinler:
21
- # Notices::COMPLETED_EVENT ve GoalState::FINISH_EVENT. TURN_EVENT,
22
- # REPL TurnRecorder#emit_turn_finished kapısıdır (root-turn planı 2026-10-04).
23
- SUBAGENT_EVENT = :subagent_completed
24
- GOAL_EVENT = :goal_finished
25
- TURN_EVENT = :turn_finished
26
- # Askı kroniği (tarama kartı 2, 2026-11-01): GoalState::SUSPEND_EVENT — abonelik
27
- # :goal akışına yazar; worker status=="suspended" ile ayırt eder.
28
- SUSPEND_EVENT = :goal_suspended
27
+ # Olay adları Rubik::Events yaprağından okunur: yaprak sıfır
28
+ # require'lıdır (uris.rb gramer yaprağı öncülü) — depolama
29
+ # katmanı orchestrator mantığına bağımlı olmadan tek söz
30
+ # dağarcığına bağlanır; izolasyon doktrininin harfi bozulmaz.
31
+ SUBAGENT_EVENT = Rubik::Events::SUBAGENT_COMPLETED
32
+ GOAL_EVENT = Rubik::Events::GOAL_FINISHED
33
+ TURN_EVENT = Rubik::Events::TURN_FINISHED
34
+ # Askı kroniği: abonelik :goal akışına yazar; worker
35
+ # status=="suspended" ile ayırt eder.
36
+ SUSPEND_EVENT = Rubik::Events::GOAL_SUSPENDED
29
37
 
30
38
  attr_reader :store, :config, :supervisor, :dmesg, :session_slug, :gate
31
39
 
@@ -74,61 +82,19 @@ module Rubik
74
82
  self
75
83
  end
76
84
 
77
- def stopped? = @monitor.synchronize { @stopped }
78
-
79
- # Dispose yolu: FIFO'daki her şey (STOP dahil öncesindeki olaylar) işlenir,
80
- # sonra thread sonlanır. Kalan olay yarımda kalmaz; thread 2 saniyede durmazsa
81
- # (yavaş bir flush/spawn içinde) kill gelir ve işlenemeyen olay sayısı dmesg'e düşer — sessiz kayıp yok.
82
- def shutdown
83
- @monitor.synchronize do
84
- return if @stopped
85
-
86
- @stopped = true
87
- @busy += 1 # STOP işaretinin de işleniş sayılır
88
- @queue.push(STOP)
89
- end
90
- begin
91
- auto_digest_touched!(spawn: false)
92
- rescue StandardError => e
93
- Vakanuvis.log_via(@dmesg, :warn, "shutdown auto-digest failed (#{e.class}: #{e.message}) — worker teardown continues")
94
- end
95
- @worker&.join(2)
96
- if @worker&.alive?
97
- Vakanuvis.log_via(@dmesg, :warn, "worker did not stop in 2s — killing with #{queue_size} event(s) unprocessed")
98
- @worker.kill
99
- end
100
- @worker = nil
101
- end
102
-
103
- def wait_idle(timeout: 2.0)
104
- deadline = Time.now + timeout
105
- sleep 0.01 while busy? && Time.now < deadline
106
- !busy?
107
- end
108
-
109
- # Kuyrukta + uçuştaki olay sayısı (push'ta artar, işlenince/düşürülünce azalır) — pop ile işaretleme arasındaki yarış penceresini kapatır.
110
- def busy? = @monitor.synchronize { @busy.positive? }
111
-
112
85
  # ---- olay giriş kapıları (kworker thread'inde çağrılır) -----------
113
86
 
87
+ # Atomik kabul (stopped-kontrol + push tek kritik bölümde) iskelette:
88
+ # kapanış yarışındaki olay ya STOP'tan önce düşer ve işlenir ya da
89
+ # reddedilir — arada kalan işleyeneksiz olay kalamaz.
114
90
  def enqueue_event(kind, payload)
115
91
  unless payload.is_a?(Hash)
116
92
  Vakanuvis.log_via(@dmesg, :warn, "discarded non-hash #{kind} event (#{payload.class})")
117
93
  return false
118
94
  end
119
-
120
- @monitor.synchronize do
121
- return false if @stopped
122
-
123
- drop_oldest! if @queue.size >= @max_queue
124
- @busy += 1
125
- @queue.push([kind, payload])
126
- true
127
- end
95
+ super
128
96
  end
129
97
 
130
- def queue_size = @queue.size
131
-
132
98
  # ---- talep düzlemi (maestro aracı buraya delege eder; K7) ---------
133
99
 
134
100
  # Deterministik geri çağırma Recall düzleminde (recall.rb); burada
@@ -215,37 +181,31 @@ module Rubik
215
181
  @event_bus.subscribe(TURN_EVENT, context: @context) { |p| enqueue_event(:turn, p) } if @root_turns
216
182
  end
217
183
 
218
- # Taşma düşürmesi asla STOP işaretini yutamaz (yutsa worker hiç
219
- # sonlanamazdı): STOP geldiyse kuyruğun sonuna geri konur.
220
- def drop_oldest!
221
- item = @queue.pop(true)
222
- if item == STOP
223
- @queue.push(STOP)
224
- else
225
- @monitor.synchronize do
226
- @dropped += 1
227
- @busy -= 1
228
- end
229
- Vakanuvis.log_via(@dmesg, :warn, "event queue overflow — dropped oldest (total: #{@dropped})")
230
- end
231
- rescue ThreadError
232
- nil
184
+ # ---- Concurrency::Worker iskelet kancaları --------------------------
185
+
186
+ def worker_max_queue = @max_queue
187
+
188
+ def worker_warn(message) = Vakanuvis.log_via(@dmesg, :warn, message)
189
+
190
+ # Kapanış yolundaki son damıtım fırsatı (spawn yok — zombi doğum
191
+ # engeli); hata yalıtılmış: worker sökümü devam eder.
192
+ def worker_before_join
193
+ auto_digest_touched!(spawn: false)
194
+ rescue StandardError => e
195
+ Vakanuvis.log_via(@dmesg, :warn, "shutdown auto-digest failed (#{e.class}: #{e.message}) — worker teardown continues")
233
196
  end
234
197
 
235
- def run_worker
236
- loop do
237
- kind, payload = @queue.pop
238
- break if kind == STOP
198
+ def worker_drop_accounted(_item)
199
+ @monitor.synchronize { @dropped += 1 }
200
+ Vakanuvis.log_via(@dmesg, :warn, "event queue overflow — dropped oldest (total: #{@dropped})")
201
+ end
239
202
 
240
- handle_event(kind, payload)
241
- rescue StandardError => e
242
- # Last-ditch net: a raise escaping handle_event's own rescue
243
- # would kill the worker with queued events unconsumed — and
244
- # shutdown's alive?-check stays blind to that loss.
245
- Vakanuvis.log_via(@dmesg, :warn, "chronicler worker event dispatch failed (#{e.class}: #{e.message}) — worker continues")
246
- ensure
247
- @monitor.synchronize { @busy -= 1 }
248
- end
203
+ def worker_dispatch_failed(kind, _payload, error)
204
+ # A dispatch-lost event must leave a chronicle trace — the same
205
+ # ledger as overflow drops, so the session annal cannot look
206
+ # complete when it is not.
207
+ @monitor.synchronize { @dropped += 1 }
208
+ Vakanuvis.log_via(@dmesg, :warn, "chronicler worker event dispatch failed (#{error.class}: #{error.message}) — #{kind} event lost, worker continues")
249
209
  end
250
210
 
251
211
  # TranscriptIndexer disiplini: kronikçinin kendi hatası akışı
@@ -383,7 +343,7 @@ module Rubik
383
343
  @monitor.synchronize do
384
344
  if @dropped.positive?
385
345
  seq = @seq += 1
386
- overflow = [["dropped.#{seq}", "- [#{seq}] #{@dropped} event(s) dropped — queue overflow (event=dropped.#{seq})"]]
346
+ overflow = [["dropped.#{seq}", "- [#{seq}] #{@dropped} event(s) dropped — queue overflow or dispatch failure (event=dropped.#{seq})"]]
387
347
  @dropped = 0
388
348
  end
389
349
  end
@@ -129,18 +129,35 @@ module Rubik
129
129
  return [sub_path, nil]
130
130
  end
131
131
 
132
- return [filter, nil] unless filter =~ %r{\A([A-Za-z]:/|/)}
132
+ # Handle Windows drive letters portably across Linux, macOS and Windows
133
+ filter_drive = filter =~ %r{\A([A-Za-z]):(/.*)?\z} ? Regexp.last_match(1).upcase : nil
134
+ filter_path = filter_drive ? (Regexp.last_match(2) || "/") : filter
135
+ root_drive = norm_root =~ %r{\A([A-Za-z]):(/.*)?\z} ? Regexp.last_match(1).upcase : nil
136
+ root_path = root_drive ? (Regexp.last_match(2) || "/") : norm_root
137
+
138
+ outside = if (filter_drive && !root_drive) ||
139
+ (!filter_drive && root_drive && filter_path.start_with?("/")) ||
140
+ (filter_drive && root_drive && filter_drive != root_drive)
141
+ true
142
+ else
143
+ base_root = File.expand_path(root_path)
144
+ expanded = File.expand_path(filter_path, base_root)
145
+ rel_check = begin
146
+ Pathname.new(expanded).relative_path_from(Pathname.new(base_root)).to_s.tr("\\", "/")
147
+ rescue ArgumentError
148
+ nil
149
+ end
150
+ rel_check.nil? || rel_check == ".." || rel_check.start_with?("../")
151
+ end
133
152
 
134
- rel = begin
135
- Pathname.new(File.expand_path(filter)).relative_path_from(Pathname.new(File.expand_path(root_dir))).to_s.tr("\\", "/")
136
- rescue ArgumentError
137
- nil
138
- end
139
- outside = rel.nil? || rel == ".." || rel.start_with?("../")
140
153
  if outside
141
154
  return [nil, "Path '#{raw}' is outside the project workspace (#{root_dir}). " \
142
155
  "Use a path relative to the project root, e.g. 'lib'."]
143
156
  end
157
+
158
+ base_root = File.expand_path(root_path)
159
+ expanded = File.expand_path(filter_path, base_root)
160
+ rel = Pathname.new(expanded).relative_path_from(Pathname.new(base_root)).to_s.tr("\\", "/")
144
161
  return ["", nil] if rel == "."
145
162
 
146
163
  [rel, nil]
@@ -91,6 +91,7 @@ module Rubik
91
91
  "For surgical edits to existing files, use replace_file_content instead. " \
92
92
  "Use apply_buffer to persist the buffer to disk before running tests or tests will not see your changes.",
93
93
  risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
94
+ buffer_sync_writer: true,
94
95
  params_schema: {
95
96
  type: "object",
96
97
  properties: {
@@ -237,6 +238,7 @@ module Rubik
237
238
  description: "Replace an exact chunk of code within an existing file. Requires exact verbatim matching of target_content " \
238
239
  "(including whitespace and indentation). Optional start_line and end_line narrow the search range.",
239
240
  risk: :write, archetypes: [:coder], write_grant: true, maestro_blocked: true, buffer_bound: true,
241
+ buffer_sync_writer: true,
240
242
  params_schema: {
241
243
  type: "object",
242
244
  properties: {
@@ -18,15 +18,15 @@ module Rubik
18
18
 
19
19
  DECLARATION = Declaration.new(
20
20
  name: "update_goal_ledger", aliases: ["ledger"],
21
- description: "Update the structured goal ledger of the RUNNING !goal loop with a " \
22
- "JSON patch ({\"rev\": N, \"ops\": [{\"op\": ..., \"path\": ..., \"value\": ...}]}). " \
23
- "Read the current ledger via read_file(path: 'rubik://goal/ledger') and issue the " \
24
- "patch against the rev it reports. Rejections carry per-op fix hints; after the " \
25
- "retry budget the ledger stays unchanged — read it and continue. A task status of " \
26
- "`stale` means the harness re-checked that entry's verify predicate against the " \
27
- "filesystem and it FAILED (the world drifted): re-inspect reality, then update the " \
28
- "entry (including status) with a normal patch — a stale rev also means the ledger " \
29
- "moved under you.",
21
+ description: "Update the structured goal ledger of the RUNNING !goal loop with an RFC 6902 " \
22
+ "JSON patch ({\"rev\": N, \"ops\": [{\"op\": \"add\"|\"replace\"|\"remove\", \"path\": \"/tasks/0/status\", \"value\": ...}]}). " \
23
+ "Read current state via read_file(path: 'rubik://goal/ledger') (or 'rubik://goal/ledger.json') and issue " \
24
+ "the patch against the rev it reports. Items carry 0-based indices (/tasks/0); append via /tasks/-. " \
25
+ "Tasks and environment notes may carry declarative verify specs: {\"type\": \"file_exists\", \"path\": ...}, " \
26
+ "{\"type\": \"file_contains\", \"path\": ..., \"pattern\": ...}, or {\"type\": \"marker\", \"path\": ..., \"marker\": ...}. " \
27
+ "Rejections carry per-op fix hints; after the retry budget the ledger stays unchanged. A task status of " \
28
+ "`stale` means the harness re-checked that entry's verify predicate against the filesystem and it FAILED " \
29
+ "(the world drifted): re-inspect reality, then update the entry with a normal patch against the bumped rev.",
30
30
  risk: :write, archetypes: [], write_grant: false, root_only: true,
31
31
  maestro_blocked: false, # vakanüvis/pruner emsali: kök düzlem aracı
32
32
  params_schema: {
@@ -330,7 +330,7 @@ module Rubik
330
330
  private
331
331
 
332
332
  def verify_binary(target, lang, proposed_cmd, sub_ctx, probe_args: nil)
333
- Rubik::Runtime::RepairProbe.new(root_dir: @root_dir).verify(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
333
+ Rubik::Runtime::RepairProbe.new(root_dir: @root_dir, guard: @guard).verify(target, lang, proposed_cmd, sub_ctx, probe_args: probe_args)
334
334
  end
335
335
 
336
336
  def command_provided?(command)