rubik 0.7.1 → 0.8.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 (46) hide show
  1. checksums.yaml +4 -4
  2. data/CHANGELOG.md +141 -1
  3. data/lib/rubik/ast/typescript_extractor.rb +2 -2
  4. data/lib/rubik/config/deep_ops.rb +14 -0
  5. data/lib/rubik/config/defaults.rb +5 -4
  6. data/lib/rubik/config/env_loader.rb +88 -0
  7. data/lib/rubik/config/model_catalog.rb +13 -0
  8. data/lib/rubik/config/pruner.rb +34 -0
  9. data/lib/rubik/config/schema.rb +163 -0
  10. data/lib/rubik/config/scoped.rb +108 -0
  11. data/lib/rubik/config/store.rb +19 -8
  12. data/lib/rubik/config.rb +129 -53
  13. data/lib/rubik/diagnostics/parser.rb +2 -2
  14. data/lib/rubik/orchestrator/step_executor.rb +12 -59
  15. data/lib/rubik/orchestrator/subagent/scoped_registry.rb +14 -23
  16. data/lib/rubik/orchestrator/subagent/spawn_transaction.rb +12 -2
  17. data/lib/rubik/orchestrator/subagent/tool_dispatch.rb +12 -49
  18. data/lib/rubik/orchestrator/turn_executor.rb +9 -4
  19. data/lib/rubik/repl/commands/workspace.rb +14 -8
  20. data/lib/rubik/repl/lifecycle.rb +11 -0
  21. data/lib/rubik/repl/service_catalog.rb +2 -1
  22. data/lib/rubik/sandbox/runner.rb +28 -13
  23. data/lib/rubik/storage/render.rb +1 -1
  24. data/lib/rubik/storage/vakanuvis/distill_gate.rb +3 -3
  25. data/lib/rubik/storage/vakanuvis/harness.rb +4 -65
  26. data/lib/rubik/storage/vakanuvis/orientation.rb +1 -2
  27. data/lib/rubik/storage/vakanuvis/recall.rb +84 -0
  28. data/lib/rubik/storage/vakanuvis.rb +1 -0
  29. data/lib/rubik/tools/base.rb +34 -0
  30. data/lib/rubik/tools/builtins/define_subagent.rb +6 -0
  31. data/lib/rubik/tools/builtins/dmesg.rb +4 -4
  32. data/lib/rubik/tools/builtins/files.rb +18 -24
  33. data/lib/rubik/tools/builtins/goal_ledger.rb +1 -1
  34. data/lib/rubik/tools/builtins/grep.rb +6 -6
  35. data/lib/rubik/tools/builtins/interactive.rb +6 -0
  36. data/lib/rubik/tools/builtins/lifecycle.rb +2 -1
  37. data/lib/rubik/tools/builtins/pruner.rb +1 -1
  38. data/lib/rubik/tools/builtins/send_message.rb +6 -0
  39. data/lib/rubik/tools/builtins/subagent.rb +12 -0
  40. data/lib/rubik/tools/builtins/vakanuvis.rb +1 -1
  41. data/lib/rubik/tools/catalog.rb +19 -0
  42. data/lib/rubik/tools/declaration.rb +15 -2
  43. data/lib/rubik/tools/result_normalizer.rb +115 -0
  44. data/lib/rubik/tools/truncator.rb +3 -3
  45. data/lib/rubik/version.rb +1 -1
  46. metadata +7 -1
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 0b147c192626203788c45315062bc380c3937c5ac638a81726ca7f135e6abfd0
4
- data.tar.gz: d95f5cce661e09ed190d7cf77ec0171d797c700756adb93769be99334f5c7a97
3
+ metadata.gz: b13fa3e4750644023e95cc953102e1bb886a5634b8c554f6e1021beb808557c8
4
+ data.tar.gz: a479e4c6e76fa1b28cc8928fb14c0afc41187abf9bdf26bf24fb599631127643
5
5
  SHA512:
6
- metadata.gz: ee9551a32ca6cb978a2c6f412f84b7d825e42b9fd73b4c24810117e3376fcf5f12b3def72efca7cdf7b5d7e20e917b5c6a400e18e1a28c72fc35b54d1996fbc8
7
- data.tar.gz: d29bdf8214f918ed81209540aeff311dfb5f4e8201201bbab85bc642d65aeda4eca6466979cb767862446e644f9cce52fafade3c74350fd81dc90e4f638d5abf
6
+ metadata.gz: 4c4e1a5e5b5b002d5fb3249e7d1b311519d26cc685e82ed1efba0dc31b2824b52ca7ac04e283558f57c15f5dc9facb37c7c4963b7688536f54a5db3a5f23fdbc
7
+ data.tar.gz: 3fc168d0ee27f4716ee8f1a027bd6b140ccb91dec09dfa4ec61a69f3335f1f208abddcacaa4001445c30eb548f53358df4df973d1cd9924f3cd4a857f8f436b0
data/CHANGELOG.md CHANGED
@@ -6,6 +6,145 @@ commits, 2026-08-23 → 2026-10-09, see `git log`).
6
6
 
7
7
  The format follows [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
8
8
 
9
+ ## [0.8.0] - 2026-11-05
10
+
11
+ A configuration-architecture minor: the write plane goes strict — typed
12
+ schema enforcement, layered composable configuration with delta pruning,
13
+ and a universal 12-factor environment loader — while the toolbelt deepens
14
+ around it (single-homed argument access and output normalization,
15
+ tool-owned plane membership, tool-owned terminal flag) and the vakanüvis
16
+ recall plane is extracted from the Harness. Existing configs carrying
17
+ out-of-spec values (a removed `buffer.auto_apply` value, an out-of-range
18
+ integer) will fail boot loudly — the value was never reaching a consumer
19
+ anyway.
20
+
21
+ ### Added
22
+
23
+ - **Layered composable configuration (#362):** a five-layer model
24
+ (`@defaults` → `@global` → `@project` → `@env` → `@session`) with
25
+ automated delta persistence that prunes redundancy against
26
+ `DEFAULT_CONFIG` on save; `config.extend` scoped child configurations
27
+ for subagent context isolation; strict typed schema validation
28
+ (`Schema`) with boundary checks and scalar coercion; a 12-factor
29
+ universal environment loader (`RUBIK_<SECTION>_<KEY>`) with a legacy
30
+ deprecation bridge; revertible configuration mutations
31
+ (`set_revertible`) with reactive delete events; and lifecycle-aligned
32
+ observers (Sandbox::Runner, REPL observers) bound to `Context#on_dispose`.
33
+ The `!config set` operator surface is hardened to be operator-only
34
+ against autonomous agent tampering.
35
+
36
+ ### Changed
37
+
38
+ - **Single-homed model-supplied argument access in `BaseTool#param`
39
+ (#367):** ~110 builtin call sites across four string/symbol
40
+ normalization dialects (||-chains, `.to_i/.to_s.strip` postfix,
41
+ `== true` flag compares, hash-fetch) now delegate to
42
+ `param(args, *keys, type:, default:)`, keeping the old chains' byte
43
+ semantics — string key before symbol key per key, first non-nil wins,
44
+ `false` falls through to the default exactly like the old ||-chains,
45
+ type coercion applied to the resolved value and the default. The three
46
+ densest files (files, grep, dmesg) migrate first; remaining builtins
47
+ migrate per-touch, and rescue ladders stay deliberately untouched.
48
+ - **Tool-output normalization single-homed (#365):** the root StepExecutor and the
49
+ subagent ToolDispatch each carried a private copy of the carrier
50
+ classification (Result / status-duck / raw string), the error-prefix
51
+ lexicon and the truncation-knob fetch. Both planes now delegate to
52
+ `Rubik::Tools::ResultNormalizer`; the parity suite stays as anti-drift
53
+ insurance and a non-fetchable config object now warns once instead of
54
+ silently dropping operator-set truncation limits. Subagent-plane edge
55
+ cases (blank error first line, error?/failed? precedence) unified onto
56
+ the root behavior, pinned by tests.
57
+ - **Tool plane membership declared on the tool (#366):** ScopedRegistry's
58
+ hand-maintained `ROOT_ONLY_TOOLS` / `BUFFER_BOUND_TOOLS` name lists now
59
+ project from the tools' own `Declaration`s (`root_only:`, `buffer_bound:`)
60
+ via `Catalog` — the same declaration→projection pattern the archetype
61
+ allowlists, spawn set, write gate and maestro gate already use.
62
+ - **Vakanüvis recall plane extracted (#363):** the deterministic recall prose and
63
+ the RECALL_* policy constants moved out of the Harness thread core into
64
+ a pure Recall module - Harness#recall is now a one-line delegate, the
65
+ verbatim first_body_line duplication between Harness and Orientation is
66
+ gone, and Orientation/DistillGate no longer reach into Harness constants.
67
+ - **Terminal flag and plane rebinds declared on the tool (#369):** finish
68
+ was string-compared at four dispatch sites — `Declaration` gains
69
+ `terminal:`, the FinishTool declares it and `Catalog` projects
70
+ `terminal_tools`, with the name compare kept as the duck-typed fallback
71
+ so fake registries and Declaration-less finish tools still complete the
72
+ turn. The five tool classes ScopedRegistry case-matched onto the
73
+ subagent plane now own `rebind_to(ctx)`, reusing their own
74
+ `resolve_supervisor`; constructor knowledge and the rebind live in one
75
+ place per tool.
76
+
77
+ ### Fixed
78
+
79
+ - **Strict typed schema enforcement (#364):** `Config#set`, `Scoped#set`, and
80
+ `Scoped` constructor overrides now reject values that violate
81
+ `Schema::DEFINITIONS` (previously the validation result was ignored —
82
+ e.g. `set("agent.max_steps", 0)` was silently accepted). The per-key
83
+ prompt-grace escape hatch is gone; the schema is the single validation
84
+ authority, including whole-section writes (nested leaves are coerced
85
+ first) and boot-time merged-tree validation. The stale
86
+ `buffer.auto_apply` enum gained the documented `on_test`/`on_finish`
87
+ modes, `sandbox.driver` became free-form (the driver registry is
88
+ plugin-extensible), and `tools.call_timeout` accepts `0` as its
89
+ documented off value.
90
+ - **Phantom legacy env mappings removed (#364):** six `LEGACY_MAP` entries pointed
91
+ at config keys no consumer reads (their real consumers read ENV
92
+ directly), so their deprecation advice was false and the mapped values
93
+ tripped "Unknown config key" warnings. Only config-backed legacy
94
+ variables remain.
95
+ - **CodeQL ReDoS and sanitization alerts resolved:** the four polynomial
96
+ backtracking quantifiers from the previous ReDoS pass converted to
97
+ possessive forms whose boundaries are forced by characters outside
98
+ their classes (captures and match results unchanged, backtracking
99
+ removed), and listing titles truncate before escaping so an escape
100
+ pair can no longer be cut in half. Closes the 5 open code scanning
101
+ alerts (#12, #33, #34, #35, #36).
102
+ - **Storage markdown cell escaping single-passed:** the two-gsub
103
+ backslash-then-pipe chain replaced with one pass over the character
104
+ class; the mapping is byte-identical (backslash doubles, pipe gains a
105
+ backslash) and truncation can no longer split an escape sequence.
106
+
107
+ ## [0.7.1] - 2026-11-04
108
+ the RECALL_* policy constants moved out of the Harness thread core into
109
+ a pure Recall module - Harness#recall is now a one-line delegate, the
110
+ verbatim first_body_line duplication between Harness and Orientation is
111
+ gone, and Orientation/DistillGate no longer reach into Harness constants.
112
+
113
+ - **Tool-output normalization single-homed:** the root StepExecutor and the
114
+ subagent ToolDispatch each carried a private copy of the carrier
115
+ classification (Result / status-duck / raw string), the error-prefix
116
+ lexicon and the truncation-knob fetch. Both planes now delegate to
117
+ `Rubik::Tools::ResultNormalizer`; the parity suite stays as anti-drift
118
+ insurance and a non-fetchable config object now warns once instead of
119
+ silently dropping operator-set truncation limits. Subagent-plane edge
120
+ cases (blank error first line, error?/failed? precedence) unified onto
121
+ the root behavior, pinned by tests.
122
+
123
+ - **Tool plane membership declared on the tool:** ScopedRegistry's
124
+ hand-maintained `ROOT_ONLY_TOOLS` / `BUFFER_BOUND_TOOLS` name lists now
125
+ project from the tools' own `Declaration`s (`root_only:`, `buffer_bound:`)
126
+ via `Catalog` — the same declaration→projection pattern the archetype
127
+ allowlists, spawn set, write gate and maestro gate already use.
128
+
129
+ ### Fixed
130
+
131
+ - **Strict typed schema enforcement:** `Config#set`, `Scoped#set`, and
132
+ `Scoped` constructor overrides now reject values that violate
133
+ `Schema::DEFINITIONS` (previously the validation result was ignored —
134
+ e.g. `set("agent.max_steps", 0)` was silently accepted). The per-key
135
+ prompt-grace escape hatch is gone; the schema is the single validation
136
+ authority, including whole-section writes (nested leaves are coerced
137
+ first) and boot-time merged-tree validation. The stale
138
+ `buffer.auto_apply` enum gained the documented `on_test`/`on_finish`
139
+ modes, `sandbox.driver` became free-form (the driver registry is
140
+ plugin-extensible), and `tools.call_timeout` accepts `0` as its
141
+ documented off value.
142
+ - **Phantom legacy env mappings removed:** six `LEGACY_MAP` entries pointed
143
+ at config keys no consumer reads (their real consumers read ENV
144
+ directly), so their deprecation advice was false and the mapped values
145
+ tripped "Unknown config key" warnings. Only config-backed legacy
146
+ variables remain.
147
+
9
148
  ## [0.7.1] - 2026-11-04
10
149
 
11
150
  An LSP maturity patch: the language-server integration comes back from
@@ -1165,7 +1304,8 @@ installation section.
1165
1304
  - Context: serialized index mutations, snapshot-outside-lock reconcile,
1166
1305
  streaming-first truncation.
1167
1306
 
1168
- [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.7.1...HEAD
1307
+ [Unreleased]: https://github.com/ozgurulukir/rubik/compare/v0.8.0...HEAD
1308
+ [0.8.0]: https://github.com/ozgurulukir/rubik/compare/v0.7.1...v0.8.0
1169
1309
  [0.7.1]: https://github.com/ozgurulukir/rubik/compare/v0.7.0...v0.7.1
1170
1310
  [0.7.0]: https://github.com/ozgurulukir/rubik/compare/v0.6.0...v0.7.0
1171
1311
  [0.6.0]: https://github.com/ozgurulukir/rubik/compare/v0.5.0...v0.6.0
@@ -185,7 +185,7 @@ module Rubik
185
185
  next_i = end_line > line_num ? end_line - 1 : idx
186
186
  [sym, next_i]
187
187
  elsif (match = stripped.match(
188
- /^(?:export\s+)?(?:const|let|var)\s+([A-Za-z0-9_$]+)(?:\s*:\s*[^=]*?[^=\s])?\s*=\s*(?:async\s*)?(?:\([^)]*\)|[A-Za-z0-9_$]+)\s*=>/
188
+ /^(?:export\s++)?(?:const|let|var)\s++([A-Za-z0-9_$]++)(?:\s*+:\s*+[^=]++)?\s*+=\s*+(?:async\s*+)?(?:\([^)]*+\)|[A-Za-z0-9_$]++)\s*+=>/
189
189
  )) ||
190
190
  (match = stripped.match(/^(?:export\s+)?(?:const|let|var)\s+([A-Za-z0-9_$]+)\s*=\s*(?:async\s*)?function\b/))
191
191
  fn_name = match[1]
@@ -210,7 +210,7 @@ module Rubik
210
210
 
211
211
  def parse_method(line, stripped, line_num, idx, current_class)
212
212
  return unless (match = stripped.match(
213
- /^(?:(?:public|private|protected|static|async|get|set)\s+)*([A-Za-z0-9_$]+)\s*\([^)]*\)(?:\s*:\s*[^{]*?[^{\s])?\s*\{/
213
+ /^(?:(?:public|private|protected|static|async|get|set)\s++)*([A-Za-z0-9_$]++)\s*+\([^)]*+\)(?:\s*+:\s*+[^{]++)?\s*+\{/
214
214
  ))
215
215
 
216
216
  method_name = match[1]
@@ -75,6 +75,20 @@ module Rubik
75
75
 
76
76
  node.delete(keys.last) ? :deleted : :absent
77
77
  end
78
+
79
+ # Sets a dot-path leaf in nested string-keyed hashes, creating intermediate
80
+ # Hash nodes as needed.
81
+ def deep_set_key(target_hash, path, value)
82
+ return unless target_hash.is_a?(Hash)
83
+
84
+ keys = path.to_s.split(".")
85
+ last_key = keys.pop
86
+ target = keys.reduce(target_hash) do |acc, k|
87
+ acc[k] = {} unless acc[k].is_a?(Hash)
88
+ acc[k]
89
+ end
90
+ target[last_key] = value
91
+ end
78
92
  end
79
93
  end
80
94
  end
@@ -222,10 +222,11 @@ module Rubik
222
222
 
223
223
  private
224
224
 
225
- def validate_prompt_grace_value!(key, value)
226
- return unless key == "ui.prompt_grace_window_ms" && !(value.is_a?(Integer) && value >= 0)
225
+ # Schema-backed keys must satisfy their spec wherever the merged tree is validated.
226
+ def validate_typed_value!(key, value)
227
+ return unless Schema::DEFINITIONS.key?(key.to_s)
227
228
 
228
- raise ArgumentError, "ui.prompt_grace_window_ms must be a non-negative integer (milliseconds)"
229
+ Schema.validate_value!(key, value, strict: true)
229
230
  end
230
231
 
231
232
  def validate_schema(config, schema = DEFAULT_CONFIG, prefix = "", strict: false)
@@ -233,7 +234,7 @@ module Rubik
233
234
 
234
235
  config.each do |key, val|
235
236
  current_key = prefix.empty? ? key.to_s : "#{prefix}.#{key}"
236
- validate_prompt_grace_value!(current_key, val)
237
+ validate_typed_value!(current_key, val)
237
238
  if schema.is_a?(Hash) && !schema.key?(key.to_s)
238
239
  candidate_keys = schema.keys
239
240
  candidates = defined?(Rubik::Tools::FuzzyMatcher) ? Rubik::Tools::FuzzyMatcher.best_matches(key.to_s, candidate_keys) : []
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "schema"
4
+ require_relative "defaults"
5
+
6
+ module Rubik
7
+ class Config
8
+ # 12-Factor Universal Environment Variable Loader (AGENTS.md & Plan Remedy Phase 3).
9
+ # Discovers RUBIK_<SECTION>_<KEY> environment variables, coerces them to typed values,
10
+ # and populates Layer 3 of the configuration stack.
11
+ # Provides a backward-compatible deprecation bridge for legacy variables.
12
+ # Only variables with a real config-backed key belong here; consumers that
13
+ # read ENV directly (concurrency, overlays, native search, test armor)
14
+ # never flow through this map.
15
+ module EnvLoader
16
+ LEGACY_MAP = {
17
+ "RUBIK_NATIVE" => "tools.native",
18
+ "RUBIK_TOOLS_CALL_TIMEOUT" => "tools.call_timeout",
19
+ "RUBIK_LOG_LEVEL" => "ui.verbosity"
20
+ }.freeze
21
+
22
+ module_function
23
+
24
+ def load_env(env = ENV, schema = Defaults::DEFAULT_CONFIG, warnings = [])
25
+ resolved = {}
26
+
27
+ # 1. Parse RUBIK_<SECTION>_<KEY> universal patterns
28
+ env.each do |k, v|
29
+ next unless k.start_with?("RUBIK_")
30
+
31
+ stripped = k.delete_prefix("RUBIK_").downcase
32
+ parts = stripped.split("_")
33
+ matching_key = match_schema_key(parts, schema)
34
+ if matching_key
35
+ coerced = Schema.coerce(matching_key, v)
36
+ deep_set(resolved, matching_key, coerced)
37
+ end
38
+ end
39
+
40
+ # 2. Process legacy variables with deprecation notice if canonical variable was unset
41
+ LEGACY_MAP.each do |legacy_name, dot_key|
42
+ next unless env.key?(legacy_name)
43
+
44
+ current_val = deep_fetch(resolved, dot_key)
45
+ next unless current_val.nil?
46
+
47
+ raw_val = env[legacy_name]
48
+ coerced = Schema.coerce(dot_key, raw_val)
49
+ deep_set(resolved, dot_key, coerced)
50
+ warnings << "[DEPRECATION] Environment variable '#{legacy_name}' is deprecated. Use the universal format 'RUBIK_#{dot_key.upcase.tr('.', '_')}' instead."
51
+ end
52
+
53
+ resolved
54
+ end
55
+
56
+ def match_schema_key(parts, schema, prefix = "")
57
+ (1..parts.length).each do |len|
58
+ head = parts[0...len].join("_")
59
+ tail = parts[len..]
60
+ full = prefix.empty? ? head : "#{prefix}.#{head}"
61
+
62
+ next unless schema.is_a?(Hash) && schema.key?(head)
63
+ return full if tail.empty?
64
+
65
+ nested = match_schema_key(tail, schema[head], full)
66
+ return nested if nested
67
+ end
68
+ nil
69
+ end
70
+
71
+ def deep_set(hash, dotted_key, value)
72
+ keys = dotted_key.split(".")
73
+ last = keys.pop
74
+ node = keys.reduce(hash) { |acc, k| acc[k] ||= {} }
75
+ node[last] = value
76
+ end
77
+
78
+ def deep_fetch(hash, dotted_key)
79
+ keys = dotted_key.split(".")
80
+ keys.reduce(hash) do |acc, k|
81
+ return nil unless acc.is_a?(Hash) && acc.key?(k)
82
+
83
+ acc[k]
84
+ end
85
+ end
86
+ end
87
+ end
88
+ end
@@ -22,6 +22,19 @@ module Rubik
22
22
 
23
23
  @data["model"] = spec_hash.dup if role_str == "default"
24
24
 
25
+ if persisting?(persist)
26
+ scope_sym = persist.to_s.downcase.to_sym == :project ? :project : :global
27
+ layer = scope_sym == :project ? (@project_layer ||= {}) : (@global_layer ||= {})
28
+ layer["models"] ||= {}
29
+ layer["models"][role_str] = deep_dup(spec_hash)
30
+ layer["model"] = deep_dup(spec_hash) if role_str == "default"
31
+ else
32
+ @session_layer ||= {}
33
+ @session_layer["models"] ||= {}
34
+ @session_layer["models"][role_str] = deep_dup(spec_hash)
35
+ @session_layer["model"] = deep_dup(spec_hash) if role_str == "default"
36
+ end
37
+
25
38
  res = persisting?(persist) ? persist_result(save!(persist)) : { ok: true }
26
39
  res[:reason] = :persist_failed unless res[:ok]
27
40
  notify_change("models.#{role_str}", spec_hash, old_spec)
@@ -0,0 +1,34 @@
1
+ # frozen_string_literal: true
2
+
3
+ require_relative "defaults"
4
+
5
+ module Rubik
6
+ class Config
7
+ # Automated redundancy pruner (AGENTS.md Spatiotemporal Remedy).
8
+ # Deeply prunes keys from `target` that are identical to `reference`.
9
+ # Preserves explicit non-default overrides and custom unmanaged keys.
10
+ # Drops redundant inherited defaults, shrinking disk files to true deltas.
11
+ module Pruner
12
+ module_function
13
+
14
+ def prune(target, reference = Defaults::DEFAULT_CONFIG)
15
+ return target unless target.is_a?(Hash) && reference.is_a?(Hash)
16
+
17
+ pruned = {}
18
+ target.each do |k, v|
19
+ k_str = k.to_s
20
+ has_key = reference.key?(k_str)
21
+ ref_val = reference[k_str]
22
+
23
+ if v.is_a?(Hash) && ref_val.is_a?(Hash)
24
+ nested = prune(v, ref_val)
25
+ pruned[k_str] = nested unless nested.empty?
26
+ elsif !has_key || v != ref_val
27
+ pruned[k_str] = v
28
+ end
29
+ end
30
+ pruned
31
+ end
32
+ end
33
+ end
34
+ end
@@ -0,0 +1,163 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ class Config
5
+ # Typed schema definition, boundary validation, and scalar coercion engine
6
+ # (AGENTS.md & Plan Remedy Phase 3). Eliminates primitive obsession across
7
+ # subsystems while preserving fail-soft backward compatibility.
8
+ module Schema
9
+ DEFINITIONS = {
10
+ "llm.stream" => { type: :boolean },
11
+ "llm.stream_timeout" => { type: :integer, min: 1 },
12
+ "llm.open_timeout" => { type: :integer, min: 1 },
13
+ "llm.default_max_output_tokens" => { type: :integer, min: 1 },
14
+ "llm.capture_reasoning" => { type: :boolean },
15
+ "llm.auto_continue_on_length" => { type: :boolean },
16
+ "llm.max_auto_continues" => { type: :integer, min: 0 },
17
+ "llm.thinking_budget_ratio" => { type: :float, min: 0.0, max: 0.8, nullable: true },
18
+ "llm.reasoning_effort" => { type: :enum, allowed: ["low", "medium", "high"], nullable: true },
19
+ "agent.max_steps" => { type: :integer, min: 1 },
20
+ "agent.goal_max_steps" => { type: :integer, min: 1 },
21
+ "agent.plan_max_steps" => { type: :integer, min: 1 },
22
+ "agent.warn_at_ratio" => { type: :float, min: 0.0, max: 1.0 },
23
+ "agent.ask_continue_on_limit" => { type: :boolean },
24
+ "tools.timeout_seconds" => { type: :integer, min: 1 },
25
+ "tools.max_output_chars" => { type: :integer, min: 100 },
26
+ "tools.max_output_lines" => { type: :integer, min: 10 },
27
+ "tools.truncation_strategy" => { type: :enum, allowed: ["head_tail", "head_only", "tail_only"] },
28
+ # min 0: 0 is a documented disable value (tool_timeout treats <=0 as off).
29
+ "tools.call_timeout" => { type: :integer, min: 0, nullable: true },
30
+ "tools.native" => { type: :enum, allowed: ["auto", "on", "off"] },
31
+ "router.mode" => { type: :enum, allowed: ["auto", "manual", "fast", "advanced"] },
32
+ "router.sticky" => { type: :boolean },
33
+ "repair.max_attempts" => { type: :integer, min: 0 },
34
+ "sandbox.enabled" => { type: :boolean },
35
+ # Free-form: the driver registry is dynamically extensible (plugins
36
+ # register drivers at runtime), so the value space is not closed.
37
+ "sandbox.driver" => { type: :string },
38
+ "sandbox.timeout_seconds" => { type: :integer, min: 1 },
39
+ "sandbox.memory_limit_mb" => { type: :integer, min: 16 },
40
+ "sandbox.allow_network" => { type: :boolean },
41
+ "sandbox.shell" => { type: :enum, allowed: ["auto", "bash", "powershell"] },
42
+ "security.allow_safe_probes" => { type: :boolean },
43
+ "security.command_allowlist" => { type: :array },
44
+ "network.allow" => { type: :boolean },
45
+ "buffer.auto_apply" => { type: :enum, allowed: ["manual", "on_test", "on_finish", "always"] },
46
+ "buffer.model_can_apply" => { type: :boolean },
47
+ "buffer.prompt_indicator" => { type: :boolean },
48
+ "buffer.exit_guard" => { type: :boolean },
49
+ "buffer.reminder_interval" => { type: :integer, min: 0 },
50
+ "ui.verbosity" => { type: :enum, allowed: ["quiet", "normal", "verbose", "debug", "trace", "0", "1", "2", "3"] },
51
+ "ui.color" => { type: :enum, allowed: ["auto", "always", "never"] },
52
+ "ui.glyphs" => { type: :enum, allowed: ["unicode", "ascii"] },
53
+ "ui.banner" => { type: :boolean },
54
+ "ui.spinner" => { type: :boolean },
55
+ "ui.markdown" => { type: :enum, allowed: ["live", "off"] },
56
+ "ui.statusline" => { type: :boolean },
57
+ "ui.prompt_grace_window_ms" => { type: :integer, min: 0 },
58
+ "workspace.allow_external_writes" => { type: :boolean },
59
+ "workspace.auto_index_additional" => { type: :boolean },
60
+ "subagents.max_concurrency" => { type: :integer, min: 1 },
61
+ "subagents.max_depth" => { type: :integer, min: 1 },
62
+ "subagents.default_max_steps" => { type: :integer, min: 1 },
63
+ "subagents.max_total_steps" => { type: :integer, min: 1 }
64
+ }.freeze
65
+
66
+ module_function
67
+
68
+ def validate_value!(key, val, strict: false)
69
+ spec = DEFINITIONS[key.to_s]
70
+ return true unless spec
71
+
72
+ return true if val.nil? && spec[:nullable]
73
+
74
+ case spec[:type]
75
+ when :boolean
76
+ unless [true, false].include?(val)
77
+ msg = "#{key} must be a boolean (true or false), got #{val.inspect}"
78
+ raise ArgumentError, msg if strict
79
+
80
+ return false
81
+ end
82
+ when :integer
83
+ unless val.is_a?(Integer) && (!spec[:min] || val >= spec[:min]) && (!spec[:max] || val <= spec[:max])
84
+ min_str = spec[:min] ? " >= #{spec[:min]}" : ""
85
+ max_str = spec[:max] ? " <= #{spec[:max]}" : ""
86
+ msg = "#{key} must be an integer#{min_str}#{max_str}, got #{val.inspect}"
87
+ raise ArgumentError, msg if strict
88
+
89
+ return false
90
+ end
91
+ when :float
92
+ val_f = val.is_a?(Numeric) ? val.to_f : nil
93
+ unless val_f && (!spec[:min] || val_f >= spec[:min]) && (!spec[:max] || val_f <= spec[:max])
94
+ msg = "#{key} must be a float between #{spec[:min]} and #{spec[:max]}, got #{val.inspect}"
95
+ raise ArgumentError, msg if strict
96
+
97
+ return false
98
+ end
99
+ when :enum
100
+ val_str = val.to_s.downcase.strip
101
+ unless spec[:allowed].include?(val_str)
102
+ msg = "#{key} must be one of #{spec[:allowed].inspect}, got #{val.inspect}"
103
+ raise ArgumentError, msg if strict
104
+
105
+ return false
106
+ end
107
+ when :string
108
+ unless val.is_a?(String)
109
+ msg = "#{key} must be a string, got #{val.inspect}"
110
+ raise ArgumentError, msg if strict
111
+
112
+ return false
113
+ end
114
+ when :array
115
+ unless val.is_a?(Array)
116
+ msg = "#{key} must be an Array, got #{val.inspect}"
117
+ raise ArgumentError, msg if strict
118
+
119
+ return false
120
+ end
121
+ end
122
+ true
123
+ end
124
+
125
+ # Coerce schema-backed scalar leaves inside a whole-section Hash write
126
+ # (e.g. set("ui", {...})) so nested string values get the same
127
+ # coercion the dotted-key path enjoys before strict validation.
128
+ def coerce_nested!(hash, prefix = "")
129
+ hash.each do |key, val|
130
+ full = prefix.empty? ? key.to_s : "#{prefix}.#{key}"
131
+ if val.is_a?(Hash)
132
+ coerce_nested!(val, full)
133
+ elsif DEFINITIONS.key?(full)
134
+ hash[key] = coerce(full, val)
135
+ end
136
+ end
137
+ hash
138
+ end
139
+
140
+ def coerce(key, val)
141
+ spec = DEFINITIONS[key.to_s]
142
+ return val unless spec && val.is_a?(String)
143
+
144
+ case spec[:type]
145
+ when :boolean
146
+ case val.strip.downcase
147
+ when "true", "yes", "1", "on" then true
148
+ when "false", "no", "0", "off" then false
149
+ else val
150
+ end
151
+ when :integer
152
+ val.strip =~ /^-?\d+$/ ? val.strip.to_i : val
153
+ when :float
154
+ val.strip =~ /^-?\d+(\.\d+)?$/ ? val.strip.to_f : val
155
+ when :enum
156
+ val.strip.downcase
157
+ else
158
+ val
159
+ end
160
+ end
161
+ end
162
+ end
163
+ end
@@ -0,0 +1,108 @@
1
+ # frozen_string_literal: true
2
+
3
+ module Rubik
4
+ class Config
5
+ # Scoped child configuration (AGENTS.md §1.C Unified Context Paradigm).
6
+ # Created via parent_config.extend(overrides = {}).
7
+ # Reads fall back to the parent config unless overridden in the child.
8
+ # Writes modify only the child's local scope, never polluting parent state.
9
+ # Disk persistence from child configs is fail-closed (raises ArgumentError).
10
+ class Scoped < Config
11
+ attr_reader :parent, :overrides
12
+
13
+ # rubocop:disable-next Lint/MissingSuper
14
+ def initialize(parent, overrides = {})
15
+ @parent = parent
16
+ @root_dir = parent.root_dir
17
+ @home_dir = parent.home_dir
18
+ @monitor = Monitor.new
19
+ @warnings = []
20
+ @listeners = []
21
+ @event_bus = parent.event_bus
22
+ @overrides = {}
23
+ return unless overrides.is_a?(Hash)
24
+
25
+ overrides.each do |k, v|
26
+ typed = v.is_a?(Hash) ? deep_stringify_keys(deep_dup(v)) : Schema.coerce(k.to_s, parse_scalar_value(deep_dup(v)))
27
+ Schema.validate_value!(k, typed, strict: true)
28
+ # Hash overrides get the same leaf coercion + validation that
29
+ # dotted-key writes go through, so extend(ui: {verbosity: 'x'})
30
+ # is as strict as set('ui.verbosity', 'x').
31
+ if typed.is_a?(Hash)
32
+ Schema.coerce_nested!(typed, k.to_s)
33
+ section = DEFAULT_CONFIG[k.to_s]
34
+ validate_schema(typed, section, k.to_s) if section.is_a?(Hash) && !section.empty?
35
+ end
36
+ deep_set_key(@overrides, k.to_s, typed)
37
+ end
38
+ end
39
+
40
+ def fetch(key, default = nil)
41
+ @monitor.synchronize do
42
+ keys = key.to_s.split(".")
43
+ val = keys.reduce(@overrides) do |acc, k|
44
+ break nil unless acc.is_a?(Hash) && acc.key?(k)
45
+
46
+ acc[k]
47
+ end
48
+ return val unless val.nil?
49
+
50
+ @parent.fetch(key, default)
51
+ end
52
+ end
53
+
54
+ def [](key)
55
+ fetch(key)
56
+ end
57
+
58
+ def set(key, value, persist: nil)
59
+ raise ArgumentError, "Scoped child configurations cannot persist to disk (scope: #{persist.inspect})" if persisting?(persist)
60
+
61
+ @monitor.synchronize do
62
+ old_val = fetch(key)
63
+ typed_val = parse_scalar_value(value)
64
+ typed_val = Schema.coerce(key, typed_val)
65
+ Schema.validate_value!(key, typed_val, strict: true)
66
+ if typed_val.is_a?(Hash)
67
+ typed_val = deep_dup(typed_val)
68
+ Schema.coerce_nested!(typed_val, key.to_s)
69
+ section = DEFAULT_CONFIG[key.to_s]
70
+ validate_schema(typed_val, section, key.to_s) if section.is_a?(Hash) && !section.empty?
71
+ end
72
+ deep_set_key(@overrides, key, typed_val)
73
+ notify_change(key, typed_val, old_val) if old_val != typed_val
74
+ { ok: true }
75
+ end
76
+ end
77
+
78
+ def delete(key, persist: nil)
79
+ raise ArgumentError, "Scoped child configurations cannot persist to disk" if persisting?(persist)
80
+
81
+ @monitor.synchronize do
82
+ old_val = fetch(key)
83
+ deep_delete(@overrides, key)
84
+ new_val = fetch(key)
85
+ if old_val != new_val
86
+ notify_change(key, new_val, old_val)
87
+ @event_bus&.emit(:config_deleted, key: key.to_s, old_val: old_val)
88
+ end
89
+ { ok: true }
90
+ end
91
+ end
92
+
93
+ def model_spec(role = :default)
94
+ role_str = role.to_s.downcase
95
+ spec = fetch("models.#{role_str}")
96
+ return spec if spec.is_a?(Hash) && spec["provider"] && spec["name"]
97
+
98
+ @parent.model_spec(role)
99
+ end
100
+
101
+ def data
102
+ @monitor.synchronize do
103
+ deep_merge(@parent.data, @overrides)
104
+ end
105
+ end
106
+ end
107
+ end
108
+ end