latticerb 0.2.0 → 0.3.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.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: 60031e0fe6baf8ed371a9e2705e905118008bd25c53f588754405399d7727429
4
- data.tar.gz: 893b27940cca00121e203cf8ed0e685cdddfc8d7ee97758d0b1864d7eef1cb6b
3
+ metadata.gz: f977e711ce31ec3c0355472e32dcff2f95cb82c173d8cbb983f05d9f8c49fb83
4
+ data.tar.gz: 73384303ddfe7fe6cbfef0cc72166d3a79ec975251a1be88a2c1560e02c594db
5
5
  SHA512:
6
- metadata.gz: 7d13bb576b7255cb8cfb255de5cf725d5a344ae8264861fcb0207803999b246fdf5ebf5ba4f07ba511846fbc8301df26256ccda8f48a7c785d66022570ac5a7d
7
- data.tar.gz: fb8d83f8f505e560cdb1277e419a53dea19d2a9350c9090b04c2b5a380b9e6dbbaccd040b3d617d6d77bb1fa1fb1987b499d94cb5cf3803d8d27c54b9c5cbf34
6
+ metadata.gz: 3d50633f9b3c3e6824811806ad8732fbfa7e12812eb94685a03cf2263254195243f44887cbe8984c297f8d05b800063367d7d5aca6413216cace5f7e3d869262
7
+ data.tar.gz: 2b0a3695bb8c6a00a8856aaa143aec10e488088e5f0800738dd3ddeefdd299fde8fd13010f406f680e085ee8c52ec6a6d0a0b7157eb993bbcbb04f8c58678817
data/README.md CHANGED
@@ -97,13 +97,24 @@ constraints:
97
97
  applies_when: [credit_card]
98
98
  ```
99
99
 
100
- Constraint types: `invalid_pair`, `higher_order`, `forward_dep`, `bidirectional`, `conditional`, `forced`. Run `lattice agent instructions` for the full reference.
100
+ Constraint types: `invalid_pair`, `higher_order`, `forward_dep`, `bidirectional`, `conditional`, `forced`. Every constraint needs a `type` key. Run `lattice agent instructions` for an example of each type.
101
+
102
+ ### Values keep their text
103
+
104
+ Every value in a schema (the model name, parameter names and values, and constraint references) is used exactly as written. In YAML, unquoted `1.10`, `0x1F`, `.inf` or `2026-10-26T10:00:00Z` stay as typed rather than being turned into numbers or dates. The exceptions:
105
+
106
+ - Unquoted `yes`, `no`, `on`, `off`, `true` and `false` (lowercase, Capitalized or UPPERCASE) become `true` / `false`, and an empty value, `~` or `null` becomes `null`. Quote them (`"yes"`) to keep the word.
107
+ - JSON integers are written in plain decimal form (`-0` becomes `0`).
108
+
109
+ `strength` must be a whole number, and `weights` decimal numbers such as `0.7` or `1e-3`. Anchors, aliases and `<<` merge keys work; a key written twice, more than one YAML document, or a tag other than YAML's standard ones is an error.
110
+
111
+ Changed in 0.3.0: earlier versions converted unquoted numbers and dates, so `0x1F` became `31`, `1.10` became `1.1`, and some values (`.inf`, timestamps) came out differently in the Ruby and Python implementations.
101
112
 
102
113
  ## Parity with the Python implementation
103
114
 
104
115
  The generator seeds an MT19937 RNG that reproduces CPython's `random.Random` bit-for-bit, so both implementations walk the same candidate pools and pick the same rows. `test/python_parity_test.rb` shells out to the Python implementation (checkout via `LATTICE_PYTHON_SRC`, or an installed `lattice-cli`) and asserts byte-equal output across formats, seeds, strengths, and stopping rules; it skips when no Python implementation is available.
105
116
 
106
- YAML is parsed with Psych here and PyYAML in Python — both YAML 1.1 (libyaml lineage), so common scalars including unquoted `yes`/`no`/`on`/`off` booleans resolve identically. Exotic YAML 1.1 corners (e.g. sexagesimal numbers) may differ between the two parsers; quote ambiguous scalars or use JSON if in doubt.
117
+ Schemas are read with Psych here and PyYAML in Python, but both implementations build values from the parsed text with the same rules (see "Values keep their text"), so a schema means the same thing in either. `test/fixtures/scalar_text.*` pins those rules for both.
107
118
 
108
119
  ## Development
109
120
 
data/lib/lattice/agent.rb CHANGED
@@ -21,7 +21,58 @@ module Lattice
21
21
  "template, or config matrix; extract a Lattice schema; validate it; generate pairwise " \
22
22
  "rows; and use the rows to strengthen the plan, tests, fixtures, or visual review."
23
23
 
24
- GENERIC_AGENT_INSTRUCTIONS = <<~INSTRUCTIONS
24
+ SCHEMA_REFERENCE = <<~REFERENCE
25
+
26
+ Schema format, with one example of each constraint type:
27
+
28
+ ```yaml
29
+ model_name: checkout
30
+ strength: 2
31
+ parameters:
32
+ user: [guest, member]
33
+ payment: [card, paypal, apple_pay, invoice]
34
+ device: [desktop, ios, android]
35
+ region: [us, eu]
36
+ currency: [usd, eur]
37
+ shipping: [standard, express, pickup]
38
+ constraints:
39
+ # invalid_pair: these two assignments never appear in the same row.
40
+ - type: invalid_pair
41
+ if: { parameter: payment, value: apple_pay }
42
+ then_not: { parameter: device, value: android }
43
+ # bidirectional: each assignment requires the other.
44
+ - type: bidirectional
45
+ pair:
46
+ - { parameter: region, value: eu }
47
+ - { parameter: currency, value: eur }
48
+ # forward_dep: the source requires the target; the target may appear elsewhere.
49
+ - type: forward_dep
50
+ source: { parameter: shipping, value: pickup }
51
+ target: { parameter: region, value: us }
52
+ # conditional: defines a child parameter that only applies for some parent values.
53
+ - type: conditional
54
+ parameter: card_type
55
+ values: [visa, mastercard]
56
+ parent: payment
57
+ applies_when: [card]
58
+ # forced: this combination must appear in at least one row.
59
+ - type: forced
60
+ assignments:
61
+ - { parameter: user, value: guest }
62
+ - { parameter: device, value: ios }
63
+ - { parameter: shipping, value: express }
64
+ # higher_order: the last assignment is excluded only when all of if_all hold.
65
+ - type: higher_order
66
+ if_all:
67
+ - { parameter: user, value: guest }
68
+ - { parameter: region, value: eu }
69
+ then_not: { parameter: shipping, value: pickup }
70
+ ```
71
+
72
+ Every constraint needs a `type` key. Each assignment is `{ parameter: <name>, value: <value> }`.
73
+ REFERENCE
74
+
75
+ GENERIC_AGENT_INSTRUCTIONS = <<~INSTRUCTIONS + SCHEMA_REFERENCE
25
76
  # Lattice Agent Instructions
26
77
 
27
78
  Lattice is harness-agnostic. Use these instructions in OpenClaw, Hermes, Codex, xAI-backed agents, Claude Code, or any agent that can run shell commands.
@@ -1,9 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
- require "json"
4
- require "yaml"
5
-
6
3
  require_relative "model"
4
+ require_relative "schema_text"
7
5
 
8
6
  module Lattice
9
7
  class ModelIOError < StandardError; end
@@ -20,6 +18,17 @@ module Lattice
20
18
  module Parser
21
19
  extend self
22
20
 
21
+ # Each constraint type and the keys written beside `type`.
22
+ CONSTRAINT_FIELDS = {
23
+ "invalid_pair" => "`if` and `then_not`",
24
+ "bidirectional" => "`pair`",
25
+ "forward_dep" => "`source` and `target`",
26
+ "conditional" => "`parameter`, `values`, `parent` and `applies_when`",
27
+ "forced" => "`assignments`",
28
+ "higher_order" => "`if_all` and `then_not`"
29
+ }.freeze
30
+ CONSTRAINT_TYPE_LIST = CONSTRAINT_FIELDS.keys.map { |name| "`#{name}`" }.join(", ").freeze
31
+
23
32
  def load_model(path, strength_override: nil)
24
33
  text, source_name, extension = read_model_input(path)
25
34
  data = deserialize_model(text, source_name, extension)
@@ -78,7 +87,7 @@ module Lattice
78
87
 
79
88
  errors = []
80
89
  loaders.each do |loader|
81
- return loader == :json ? JSON.parse(text) : safe_load_yaml(text)
90
+ return loader == :json ? SchemaText.load_json(text) : SchemaText.load_yaml(text)
82
91
  rescue StandardError => e
83
92
  errors << e.message
84
93
  end
@@ -86,10 +95,6 @@ module Lattice
86
95
  raise ModelIOError, "Unable to parse model from `#{source_name}`: #{errors.join('; ')}"
87
96
  end
88
97
 
89
- def safe_load_yaml(text)
90
- YAML.safe_load(text, permitted_classes: [Date, Time], aliases: true)
91
- end
92
-
93
98
  def parse_parameters(raw_parameters, errors)
94
99
  parameters = {}
95
100
  if raw_parameters.nil?
@@ -183,7 +188,17 @@ module Lattice
183
188
  next
184
189
  end
185
190
 
186
- case raw_constraint["type"]
191
+ constraint_type = raw_constraint["type"]
192
+ if constraint_type.nil?
193
+ errors << missing_type_message(index, raw_constraint)
194
+ next
195
+ end
196
+ unless constraint_type.is_a?(String)
197
+ errors << "`constraints[#{index}].type` must be a string, one of: #{CONSTRAINT_TYPE_LIST}."
198
+ next
199
+ end
200
+
201
+ case constraint_type
187
202
  when "invalid_pair"
188
203
  if_assignment = parse_assignment(raw_constraint["if"], parameters, "`constraints[#{index}].if`", errors)
189
204
  then_not = parse_assignment(raw_constraint["then_not"], parameters, "`constraints[#{index}].then_not`", errors)
@@ -211,12 +226,23 @@ module Lattice
211
226
  constraint = parse_higher_order_constraint(raw_constraint, index, parameters, errors)
212
227
  parsed << constraint if constraint
213
228
  else
214
- errors << "`constraints[#{index}]` has unknown type `#{raw_constraint['type']}`."
229
+ errors << "`constraints[#{index}]` has unknown type `#{constraint_type}`. Use one of: #{CONSTRAINT_TYPE_LIST}."
215
230
  end
216
231
  end
217
232
  parsed
218
233
  end
219
234
 
235
+ # Explains a constraint without `type`. A type name used as a key, as in
236
+ # `- invalid_pair: {...}`, gets the correct form spelled out.
237
+ def missing_type_message(index, raw_constraint)
238
+ shorthand = raw_constraint.keys.find { |key| CONSTRAINT_FIELDS.key?(key) }
239
+ return "`constraints[#{index}]` is missing `type`. Use one of: #{CONSTRAINT_TYPE_LIST}." if shorthand.nil?
240
+
241
+ "`constraints[#{index}]` is missing `type`. Write `type: #{shorthand}` as its own key, " \
242
+ "with #{CONSTRAINT_FIELDS.fetch(shorthand)} beside it. " \
243
+ "Run `lattice agent instructions` for an example of each type."
244
+ end
245
+
220
246
  def parse_conditional_constraint(raw_constraint, index, parameters, errors)
221
247
  parent = Lattice.normalize_scalar(raw_constraint["parent"])
222
248
  parameter_name = Lattice.normalize_scalar(raw_constraint["parameter"])
@@ -351,8 +377,9 @@ module Lattice
351
377
  end
352
378
 
353
379
  parsed = []
354
- raw_weights.each do |weight|
355
- unless weight.is_a?(Numeric)
380
+ raw_weights.each do |raw_weight|
381
+ weight = parse_number(raw_weight)
382
+ if weight.nil?
356
383
  errors << "`weights` for parameter `#{parameter_name}` must be numeric."
357
384
  return nil
358
385
  end
@@ -360,24 +387,37 @@ module Lattice
360
387
  errors << "`weights` for parameter `#{parameter_name}` must be greater than zero."
361
388
  return nil
362
389
  end
363
- parsed << weight.to_f
390
+ parsed << weight
364
391
  end
365
392
  parsed
366
393
  end
367
394
 
395
+ DECIMAL_TEXT = /\A[-+]?[0-9]+(\.[0-9]+)?([eE][-+]?[0-9]+)?\z/
396
+ INTEGER_TEXT = /\A[-+]?[0-9]+\z/
397
+
398
+ # A finite number, from a Ruby number or decimal text such as "0.7" or
399
+ # "1e-3" (schema files keep numbers as text). Booleans are not numbers.
400
+ def parse_number(raw)
401
+ number =
402
+ case raw
403
+ when Integer, Float then raw.to_f
404
+ when String then DECIMAL_TEXT.match?(raw) ? Float(raw) : nil
405
+ end
406
+ number&.finite? ? number : nil
407
+ end
408
+
368
409
  def parse_strength(raw_strength, parameter_count, errors)
369
410
  strength =
370
411
  case raw_strength
371
412
  when nil then 2
372
- when Numeric then raw_strength.to_i
373
- else
374
- begin
375
- Integer(raw_strength)
376
- rescue TypeError, ArgumentError
377
- errors << "`strength` must be an integer."
378
- return 2
379
- end
413
+ when Integer then raw_strength
414
+ when Float then raw_strength.finite? ? raw_strength.to_i : nil
415
+ when String then INTEGER_TEXT.match?(raw_strength) ? Integer(raw_strength, 10) : nil
380
416
  end
417
+ if strength.nil?
418
+ errors << "`strength` must be an integer."
419
+ return 2
420
+ end
381
421
 
382
422
  errors << "`strength` must be at least 1." if strength < 1
383
423
  errors << "`strength` cannot exceed the number of parameters." if parameter_count.positive? && strength > parameter_count
@@ -35,7 +35,9 @@ parameters:
35
35
  payment: [card, apple_pay, paypal]
36
36
  cart: [empty, single, multi]
37
37
  constraints:
38
- - invalid_pair: {payment: apple_pay, cart: empty}
38
+ - type: invalid_pair
39
+ if: { parameter: payment, value: apple_pay }
40
+ then_not: { parameter: cart, value: empty }
39
41
  ```
40
42
 
41
43
  One generated row (JSON):
@@ -35,7 +35,9 @@ parameters:
35
35
  payment: [card, apple_pay, paypal]
36
36
  cart: [empty, single, multi]
37
37
  constraints:
38
- - invalid_pair: {payment: apple_pay, cart: empty}
38
+ - type: invalid_pair
39
+ if: { parameter: payment, value: apple_pay }
40
+ then_not: { parameter: cart, value: empty }
39
41
  ```
40
42
 
41
43
  One generated row (JSON):
@@ -35,7 +35,9 @@ parameters:
35
35
  payment: [card, apple_pay, paypal]
36
36
  cart: [empty, single, multi]
37
37
  constraints:
38
- - invalid_pair: {payment: apple_pay, cart: empty}
38
+ - type: invalid_pair
39
+ if: { parameter: payment, value: apple_pay }
40
+ then_not: { parameter: cart, value: empty }
39
41
  ```
40
42
 
41
43
  One generated row (JSON):
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+ require "psych"
5
+
6
+ module Lattice
7
+ # Reads schema text (JSON or YAML) into plain Hashes, Arrays and Strings,
8
+ # keeping every value as the text the user wrote. `1.10` stays "1.10",
9
+ # `0x1F` stays "0x1F" and `2026-10-26T10:00:00Z` stays as typed, instead of
10
+ # being converted to a number or time and printed back differently by Ruby
11
+ # and Python. The only conversions:
12
+ #
13
+ # - unquoted yes/no/on/off/true/false (in the case forms below) become
14
+ # true/false, and an empty value, ~ or null becomes nil;
15
+ # - JSON integers are written in plain decimal form.
16
+ #
17
+ # The Python implementation (lattice.schema_text) follows the same rules, and
18
+ # test/fixtures/scalar_text.* pins the result for both.
19
+ module SchemaText
20
+ extend self
21
+
22
+ class SyntaxError < StandardError; end
23
+
24
+ TRUE_WORDS = %w[yes Yes YES true True TRUE on On ON].freeze
25
+ FALSE_WORDS = %w[no No NO false False FALSE off Off OFF].freeze
26
+ NULL_WORDS = ["", "~", "null", "Null", "NULL"].freeze
27
+
28
+ YAML_TAG_PREFIX = "tag:yaml.org,2002:"
29
+ STR_TAGS = ["!", "#{YAML_TAG_PREFIX}str"].freeze
30
+ SCALAR_TAGS = %w[str int float bool null timestamp binary merge value].map { |name| "#{YAML_TAG_PREFIX}#{name}" }.freeze
31
+ SEQUENCE_TAGS = [nil, "!", "#{YAML_TAG_PREFIX}seq"].freeze
32
+ MAPPING_TAGS = [nil, "!", "#{YAML_TAG_PREFIX}map"].freeze
33
+
34
+ # Hands JSON floats back as their source text.
35
+ class RawNumber
36
+ def self.new(text) = text
37
+ end
38
+
39
+ # Rejects a key written twice. json 2.x calls []= on a custom object_class;
40
+ # json 3.x checks duplicates itself when allow_duplicate_key is false.
41
+ class UniqueHash < Hash
42
+ def []=(key, value)
43
+ raise JSON::ParserError, "duplicate key `#{key}`" if key?(key)
44
+
45
+ super
46
+ end
47
+ end
48
+
49
+ def load_json(text)
50
+ json_strings(
51
+ JSON.parse(text, decimal_class: RawNumber, object_class: UniqueHash, allow_duplicate_key: false)
52
+ )
53
+ end
54
+
55
+ def load_yaml(text)
56
+ documents = Psych.parse_stream(text).children
57
+ raise SyntaxError, "expected a single YAML document, found #{documents.length}" if documents.length > 1
58
+ return nil if documents.empty?
59
+
60
+ yaml_value(documents.first.root, {})
61
+ end
62
+
63
+ private
64
+
65
+ def json_strings(value)
66
+ case value
67
+ when Hash then value.to_h { |key, child| [key, json_strings(child)] }
68
+ when Array then value.map { |child| json_strings(child) }
69
+ when Integer then value.to_s
70
+ else value
71
+ end
72
+ end
73
+
74
+ # `anchors` maps each anchor to its value once built; an anchor still
75
+ # being built (nil value) means an alias points back into itself.
76
+ def yaml_value(node, anchors)
77
+ return yaml_alias(node, anchors) if node.is_a?(Psych::Nodes::Alias)
78
+
79
+ anchors[node.anchor] = nil if node.anchor
80
+ value =
81
+ case node
82
+ when Psych::Nodes::Scalar then yaml_scalar(node)
83
+ when Psych::Nodes::Sequence
84
+ check_tag(node.tag, SEQUENCE_TAGS)
85
+ node.children.map { |child| yaml_value(child, anchors) }
86
+ when Psych::Nodes::Mapping then yaml_mapping(node, anchors)
87
+ end
88
+ anchors[node.anchor] = [value] if node.anchor
89
+ value
90
+ end
91
+
92
+ def yaml_alias(node, anchors)
93
+ built = anchors.fetch(node.anchor) { raise SyntaxError, "unknown alias `*#{node.anchor}`" }
94
+ raise SyntaxError, "recursive alias" if built.nil?
95
+
96
+ built.first
97
+ end
98
+
99
+ def yaml_scalar(node)
100
+ check_tag(node.tag, [nil, "!"] + SCALAR_TAGS)
101
+ return node.value unless node.style == Psych::Nodes::Scalar::PLAIN && !STR_TAGS.include?(node.tag)
102
+ return true if TRUE_WORDS.include?(node.value)
103
+ return false if FALSE_WORDS.include?(node.value)
104
+ return nil if NULL_WORDS.include?(node.value)
105
+
106
+ node.value
107
+ end
108
+
109
+ # Keys from `<<` merges come first, earlier sources winning; the
110
+ # mapping's own keys then override them. A key written twice is an error.
111
+ def yaml_mapping(node, anchors)
112
+ check_tag(node.tag, MAPPING_TAGS)
113
+ merged = {}
114
+ own = {}
115
+ seen_merge = false
116
+ node.children.each_slice(2) do |key_node, value_node|
117
+ key = yaml_value(key_node, anchors)
118
+ raise SyntaxError, "mapping keys must be scalars" if key.is_a?(Enumerable)
119
+
120
+ if merge_key?(key_node)
121
+ raise SyntaxError, "duplicate key `<<`" if seen_merge
122
+
123
+ seen_merge = true
124
+ merge_sources(yaml_value(value_node, anchors)).each do |source|
125
+ source.each { |merged_key, merged_value| merged[merged_key] = merged_value unless merged.key?(merged_key) }
126
+ end
127
+ next
128
+ end
129
+
130
+ raise SyntaxError, "duplicate key `#{Lattice.normalize_scalar(key)}`" if own.key?(key)
131
+
132
+ own[key] = yaml_value(value_node, anchors)
133
+ end
134
+ merged.merge(own)
135
+ end
136
+
137
+ def merge_key?(key_node)
138
+ key_node.is_a?(Psych::Nodes::Scalar) && key_node.style == Psych::Nodes::Scalar::PLAIN && key_node.value == "<<" &&
139
+ [nil, "#{YAML_TAG_PREFIX}merge"].include?(key_node.tag)
140
+ end
141
+
142
+ def merge_sources(value)
143
+ sources = [value].flatten(1)
144
+ raise SyntaxError, "merge key `<<` needs a mapping or a list of mappings" unless sources.all?(Hash)
145
+
146
+ sources
147
+ end
148
+
149
+ def check_tag(tag, allowed)
150
+ raise SyntaxError, "unsupported YAML tag `#{tag}`" unless allowed.include?(tag)
151
+ end
152
+ end
153
+ end
@@ -1,5 +1,5 @@
1
1
  # frozen_string_literal: true
2
2
 
3
3
  module Lattice
4
- VERSION = "0.2.0"
4
+ VERSION = "0.3.1"
5
5
  end
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: latticerb
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.2.0
4
+ version: 0.3.1
5
5
  platform: ruby
6
6
  authors:
7
7
  - Tyler Klose
@@ -56,6 +56,7 @@ files:
56
56
  - lib/lattice/resources/generic/lattice-workflow/SKILL.md
57
57
  - lib/lattice/resources/generic/lattice-workflow/references/modeling-rules.md
58
58
  - lib/lattice/resources/generic/lattice-workflow/references/worked-examples.md
59
+ - lib/lattice/schema_text.rb
59
60
  - lib/lattice/version.rb
60
61
  - lib/latticerb.rb
61
62
  homepage: https://github.com/tylerklose/lattice-ruby