menuconform 0.1.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.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: 497b0ace6a30de42bc5d0d494ae7c9e23206331407902b3a84a3636d809c40d0
4
+ data.tar.gz: cea2dfe8a743d55e2957381401d666eee1fb4bf339dabe3f147b37e938ae9ee2
5
+ SHA512:
6
+ metadata.gz: 199304d9779008366dec8be4740bfb1b19e70cf89e77c84fe427b22ead45c0870f5c3a19faf60ff2c83951a97a6ce50003f1cfe4b691e817dcbd1243d2f3a8e6
7
+ data.tar.gz: 938be138bea321d6b64ada27c482fe46f5c56eb5b47a3cf72f16cd8923e3bfe88f99476c131eb281333d576658a799dd1440ece3b08c1a1f1502a13a3f43177e
data/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
data/README.md ADDED
@@ -0,0 +1,156 @@
1
+ # menuconform
2
+
3
+ [![CI](https://github.com/amitkssolanki/menuconform/actions/workflows/ci.yml/badge.svg)](https://github.com/amitkssolanki/menuconform/actions/workflows/ci.yml)
4
+
5
+ **Could an AI agent build a valid, correctly priced, makeable cart from your restaurant menu?**
6
+
7
+ menuconform is an open-source conformance kit for restaurant menus entering the
8
+ [Universal Commerce Protocol](https://ucp.dev) food-ordering world. Feed it a menu
9
+ (Menu IR JSON, or an NCR Voyix Menu API export via `--from ncr-menu`) and it produces
10
+ a scored 0–100 report with per-rule findings and fix hints written for menu owners,
11
+ not just engineers.
12
+
13
+ ```
14
+ $ menuconform check menu.json
15
+ menuconform 0.1.0 · rules 0.1.0 · reference time 2026-08-30T00:00:00Z
16
+ Menu: Bucky's Pizza & Wings — All Day (IR 0.2, USD, America/New_York)
17
+ Score: 0/100 errors: 17 warns: 14 infos: 16
18
+
19
+ CART-001 [error] item/itm_wings_6
20
+ no selection satisfies this item's modifier constraints — it cannot be ordered
21
+ fix: See the accompanying CONFLICT/STRUCT findings on this item's groups; ...
22
+ PRICE-002 [warn] modifier_group/mg_pizza_toppings12
23
+ option mod_extra_cheese12 conditional-price matrix does not cover mod_size_xl12 ...
24
+ fix: Add the missing matrix entries — this is the classic 'new size added,
25
+ topping table not updated' undercharge.
26
+ ```
27
+
28
+ ## Why this exists
29
+
30
+ Agent ordering is arriving faster than menu data is getting ready for it. The official
31
+ [UCP conformance suite](https://github.com/Universal-Commerce-Protocol/conformance)
32
+ is the *final protocol check*: pytest against a running UCP merchant server, with a
33
+ flat `id,title,price` product model and (today) no food-domain coverage. menuconform
34
+ is the **pre-flight check for the menu data itself**: no server required, food
35
+ semantics only — modifier constraint satisfiability, nested-group depth, half/half
36
+ slot pricing, size-conditional prices, availability windows, allergen and
37
+ age-restriction completeness.
38
+
39
+ The two are complementary: menuconform → build your UCP endpoint → official
40
+ conformance suite.
41
+
42
+ ## What it checks
43
+
44
+ Menus are validated against a language-agnostic **Menu IR** (JSON Schema 2020-12, in
45
+ [`schema/menu_ir.schema.json`](schema/menu_ir.schema.json)), designed from a field
46
+ study of the Uber Eats, DoorDash, Grubhub, and Checkmate menu models. The schema
47
+ checks shape only; ~30 stable rules
48
+ ([`rules/catalog.json`](rules/catalog.json)) check meaning:
49
+
50
+ | Family | Checks |
51
+ |-------------|--------|
52
+ | `STRUCT-` | schema validity, dangling references, duplicate IDs, orphans, nesting depth (>6 error, >4 warn) |
53
+ | `CONFLICT-` | unsatisfiable constraints: min>max, required-empty groups, defaults vs limits, invalid conditional-price triggers |
54
+ | `PRICE-` | negative prices, incomplete topping-by-size matrices, reachable negative totals |
55
+ | `AVAIL-` | windows that contradict parent scopes, never-available declarations, retirement-via-86 |
56
+ | `NAME-` | empty names, case-insensitive duplicates, back-of-house junk (`86 DNU`, `zzz DO NOT USE`) |
57
+ | `ALLERGEN-` | missing or contradictory allergen declarations (US big-9 ∪ EU-14 vocabulary) |
58
+ | `AGE-` | alcohol-indicative items without `min_age`, age-restricted items in kids categories |
59
+ | `CART-` | **the cart solver**: items no valid cart can be built for, defaults that violate their own constraints, no-positive-total items, equivalent carts that price differently |
60
+ | `EXPORT-` | lossiness against the pinned UCP draft (roadmap) |
61
+
62
+ The cart solver is the differentiator: it does exact constraint satisfiability with
63
+ recursive option selectability, so it catches menus that are *statically clean but
64
+ unorderable* — the class of problem no field-by-field validator sees.
65
+
66
+ ## Scoring
67
+
68
+ `score = max(0, 100 − Σ deductions)`: error −5, warn −2, info −0.5, at most 15 points
69
+ per rule, then hard caps — any cart-blocking finding caps the score at 49, a
70
+ schema-invalid document at 59. Deterministic: the only time input is an injectable
71
+ `reference_time`, stated in the report. Same menu + same rules version = same score.
72
+
73
+ ## Install & use
74
+
75
+ Not yet on RubyGems (soon). From source (Ruby ≥ 3.1):
76
+
77
+ ```
78
+ git clone https://github.com/amitkssolanki/menuconform && cd menuconform
79
+ bundle install
80
+ bundle exec exe/menuconform check fixtures/12_legacy_sprawl/menu.json
81
+ ```
82
+
83
+ CLI:
84
+
85
+ ```
86
+ menuconform check MENU.json [--from FORMAT] [--json] [--reference-time ISO8601] [--fail-below SCORE]
87
+ menuconform import --from FORMAT SOURCE.json [--config PATH] [-o OUT.json]
88
+ menuconform rules
89
+ menuconform version
90
+ ```
91
+
92
+ ## Importers
93
+
94
+ `--from ncr-menu` ingests an **NCR Voyix Menu API** v2 menu-details payload
95
+ (`nep-service-version 2A:1`): link groups map onto the IR's two constraint axes,
96
+ Aloha-style price levels (group-scoped `prices[].linkGroupId`) lower to per-link
97
+ price overrides, `freeQuantity` becomes `included_quantity`, and per-item
98
+ `itemCustomModifiers` defaults are applied where unambiguous. Everything lossy
99
+ (prep-code price multipliers, step quantities, item factors, scheduled prices,
100
+ promotions/quick combos) is stashed under `x_` extension keys and reported as
101
+ import notes — the same list that seeds the `EXPORT-` lossiness story. Vendor
102
+ field mappings live in [`config/importers/ncr_menu.json`](config/importers/ncr_menu.json)
103
+ (set `timezone` to the site's IANA zone; NCR payloads don't carry one). A
104
+ sanitized sample export and its golden IR live in
105
+ [`fixtures/importers/ncr_menu/`](fixtures/importers/ncr_menu/) — a clean NCR
106
+ import scores **98/100**, because NCR's menu contract has no allergen fields at
107
+ all: that gap is exactly what agents will trip over.
108
+
109
+ Exit codes: `0` passed the gate, `1` failed (error findings, or score below
110
+ `--fail-below`), `2` usage/input error. Ruby API:
111
+
112
+ ```ruby
113
+ require "menuconform"
114
+ report = Menuconform::Engine.new.analyze(JSON.parse(File.read("menu.json")))
115
+ report.score # => 0..100
116
+ report.findings # => [Menuconform::Finding]
117
+ report.to_h # => full report hash
118
+ ```
119
+
120
+ ## UCP export
121
+
122
+ `menuconform export MENU.json` maps the IR onto the pinned UCP draft's catalog
123
+ shapes (`product`/`variant`/`option`/`price`) and reports what the export loses as
124
+ `EXPORT-` findings: required single-select sizes become real options/variants;
125
+ everything else — multi-select modifiers, nested groups, conditional prices,
126
+ half/half, allergens, age restrictions, schedules — is dropped, degraded, or makes
127
+ the item unrepresentable (`EXPORT-001`, exit 1). The full lossy-construct analysis
128
+ lives in [docs/export-lossiness.md](docs/export-lossiness.md). Export findings
129
+ deliberately do **not** affect the `check` score: `check` judges your menu data,
130
+ `export` judges the current draft's fit for food.
131
+
132
+ ## Fixtures
133
+
134
+ [`fixtures/`](fixtures/) contains twelve menus with pinned expected findings — from
135
+ `01_golden_path` (must score 100) to `12_legacy_sprawl`, a plausible 15-year-old
136
+ franchise export that scores 0. They double as the conformance suite for the rules
137
+ themselves and as worked examples of the IR. There is currently no public sample
138
+ food menu anywhere in the UCP ecosystem; these aim to fill that gap.
139
+
140
+ ## UCP spec pin
141
+
142
+ The IR is validated against **Menu IR v0.2**. The UCP exporter (in progress) tracks
143
+ **UCP spec v2026-08-25** (pin checked 2026-08-30; re-pinned monthly). The IR is
144
+ deliberately *not* coupled to the draft — menus are validated against the IR, and
145
+ only the exporter chases the moving spec.
146
+
147
+ ## Roadmap
148
+
149
+ - More POS-family importers and a generic CSV importer
150
+ - UCP exporter + `EXPORT-` lossiness rules against the pinned draft
151
+ - TypeScript port if implementers need it
152
+
153
+ ## License & maintainer
154
+
155
+ Apache-2.0. Built and maintained by [Amit Solanki](https://github.com/amitkssolanki).
156
+ Issues and real-world menu pathologies (sanitized!) are very welcome.
@@ -0,0 +1,12 @@
1
+ {
2
+ "comment": "Mapping config for the NCR Voyix Menu API (v2 menu-details payload, nep-service-version 2A:1). Vendor field mappings live here, not in code. Override per run with --config.",
3
+ "timezone": null,
4
+ "default_currency": "USD",
5
+ "currency_map": {
6
+ "USD": "USD",
7
+ "US Dollar": "USD",
8
+ "United States Dollar": "USD"
9
+ },
10
+ "included_allocation": "cheapest_first",
11
+ "per_option_max_fallback": 99
12
+ }
data/exe/menuconform ADDED
@@ -0,0 +1,7 @@
1
+ #!/usr/bin/env ruby
2
+ # frozen_string_literal: true
3
+
4
+ require "menuconform"
5
+ require "menuconform/cli"
6
+
7
+ exit Menuconform::CLI.run(ARGV)
@@ -0,0 +1,28 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "json"
4
+
5
+ module Menuconform
6
+ # Loads rules/catalog.json — the single source of truth for rule severities,
7
+ # titles, and fix hints.
8
+ class Catalog
9
+ def self.load(path)
10
+ new(JSON.parse(File.read(path, encoding: "UTF-8")))
11
+ end
12
+
13
+ attr_reader :rules_version
14
+
15
+ def initialize(doc)
16
+ @rules_version = doc.fetch("rules_version")
17
+ @by_id = doc.fetch("rules").to_h { |r| [r.fetch("id"), r] }
18
+ end
19
+
20
+ def entry(rule_id)
21
+ @by_id.fetch(rule_id) { raise KeyError, "rule #{rule_id} is not in the catalog" }
22
+ end
23
+
24
+ def severity(rule_id)
25
+ entry(rule_id).fetch("severity")
26
+ end
27
+ end
28
+ end
@@ -0,0 +1,256 @@
1
+ # frozen_string_literal: true
2
+
3
+ require "optparse"
4
+ require "json"
5
+ require "time"
6
+
7
+ module Menuconform
8
+ # Command-line interface. Exit codes:
9
+ # 0 - check ran and passed the gate (no error-severity findings, or score
10
+ # at/above --fail-below when given)
11
+ # 1 - check ran and failed the gate
12
+ # 2 - usage error or unreadable input
13
+ class CLI
14
+ USAGE = <<~TEXT
15
+ menuconform — UCP food-ordering menu conformance kit
16
+
17
+ Usage:
18
+ menuconform check MENU.json [options] Validate a menu (IR, or --from a source format)
19
+ menuconform import --from FORMAT SRC.json Convert a source export to Menu IR JSON
20
+ menuconform export MENU.json [options] Export to the pinned UCP catalog draft,
21
+ reporting EXPORT- lossiness findings
22
+ menuconform rules List the rule catalog
23
+ menuconform version Print version
24
+
25
+ Check options:
26
+ --from FORMAT Treat input as a source export; import to IR first
27
+ --json Emit the full JSON report instead of text
28
+ --reference-time TIME ISO 8601 instant for time-dependent rules
29
+ (default: now; pin it for reproducible runs)
30
+ --fail-below SCORE Exit 1 when the score is below SCORE
31
+ (default gate: exit 1 on any error finding)
32
+
33
+ Import options:
34
+ --from FORMAT Source format (required; see below)
35
+ --config PATH Override the importer's default mapping config
36
+ -o, --out PATH Write IR JSON to PATH (default: stdout)
37
+ TEXT
38
+
39
+ def self.run(argv, stdout: $stdout, stderr: $stderr)
40
+ new(stdout: stdout, stderr: stderr).run(argv)
41
+ end
42
+
43
+ def initialize(stdout:, stderr:)
44
+ @stdout = stdout
45
+ @stderr = stderr
46
+ end
47
+
48
+ def run(argv)
49
+ case argv.first
50
+ when "check" then check(argv[1..])
51
+ when "import" then import(argv[1..])
52
+ when "export" then export(argv[1..])
53
+ when "rules" then rules
54
+ when "version", "--version", "-v" then @stdout.puts(VERSION) || 0
55
+ when "help", "--help", "-h" then @stdout.puts(USAGE) || 0
56
+ when nil then @stderr.puts(USAGE) || 2
57
+ else
58
+ @stderr.puts "unknown command: #{argv.first}\n\n#{USAGE}"
59
+ 2
60
+ end
61
+ end
62
+
63
+ private
64
+
65
+ def check(args)
66
+ options = { json: false, reference_time: Time.now.utc, fail_below: nil, from: nil, config: nil }
67
+ parser = OptionParser.new do |o|
68
+ o.on("--from FORMAT") { |f| options[:from] = f }
69
+ o.on("--config PATH") { |p| options[:config] = p }
70
+ o.on("--json") { options[:json] = true }
71
+ o.on("--reference-time TIME") do |t|
72
+ options[:reference_time] = Time.iso8601(t)
73
+ rescue ArgumentError
74
+ return usage_error("--reference-time must be ISO 8601 (got #{t.inspect})")
75
+ end
76
+ o.on("--fail-below SCORE", Integer) { |s| options[:fail_below] = s }
77
+ end
78
+
79
+ begin
80
+ files = parser.parse(args)
81
+ rescue OptionParser::ParseError => e
82
+ return usage_error(e.message)
83
+ end
84
+ return usage_error("exactly one menu file required") unless files.size == 1
85
+
86
+ doc = read_json(files.first)
87
+ return doc if doc.is_a?(Integer) # usage-error exit code
88
+
89
+ if options[:from]
90
+ config = nil
91
+ if options[:config]
92
+ config = read_json(options[:config])
93
+ return config if config.is_a?(Integer)
94
+ end
95
+ begin
96
+ result = Importers.import(options[:from], doc, config: config)
97
+ rescue Importers::SourceError => e
98
+ return usage_error(e.message)
99
+ end
100
+ result.notes.each { |n| @stderr.puts "import note: #{n}" }
101
+ doc = result.doc
102
+ end
103
+
104
+ report = Engine.new.analyze(doc, reference_time: options[:reference_time])
105
+ options[:json] ? @stdout.puts(report.to_json) : render(report)
106
+
107
+ if options[:fail_below]
108
+ report.score < options[:fail_below] ? 1 : 0
109
+ else
110
+ report.findings.any? { |f| f.severity == "error" } ? 1 : 0
111
+ end
112
+ end
113
+
114
+ def import(args)
115
+ options = { from: nil, config: nil, out: nil }
116
+ parser = OptionParser.new do |o|
117
+ o.on("--from FORMAT") { |f| options[:from] = f }
118
+ o.on("--config PATH") { |p| options[:config] = p }
119
+ o.on("-o PATH", "--out PATH") { |p| options[:out] = p }
120
+ end
121
+ begin
122
+ files = parser.parse(args)
123
+ rescue OptionParser::ParseError => e
124
+ return usage_error(e.message)
125
+ end
126
+ return usage_error("--from FORMAT is required (known: #{Importers.names.join(', ')})") unless options[:from]
127
+ return usage_error("exactly one source file required") unless files.size == 1
128
+
129
+ source = read_json(files.first)
130
+ return source if source.is_a?(Integer)
131
+ config = nil
132
+ if options[:config]
133
+ config = read_json(options[:config])
134
+ return config if config.is_a?(Integer)
135
+ end
136
+
137
+ begin
138
+ result = Importers.import(options[:from], source, config: config)
139
+ rescue Importers::SourceError => e
140
+ return usage_error(e.message)
141
+ end
142
+ result.notes.each { |n| @stderr.puts "import note: #{n}" }
143
+ json = JSON.pretty_generate(result.doc)
144
+ options[:out] ? File.write(options[:out], json + "\n") : @stdout.puts(json)
145
+ 0
146
+ end
147
+
148
+ # Artifact goes to --out (or stdout); EXPORT- findings go to stderr.
149
+ # Exit 1 when any EXPORT-001 (item cannot exist under the pinned draft).
150
+ def export(args)
151
+ options = { from: nil, config: nil, out: nil, reference_time: Time.now.utc }
152
+ parser = OptionParser.new do |o|
153
+ o.on("--from FORMAT") { |f| options[:from] = f }
154
+ o.on("--config PATH") { |p| options[:config] = p }
155
+ o.on("-o PATH", "--out PATH") { |p| options[:out] = p }
156
+ o.on("--reference-time TIME") do |t|
157
+ options[:reference_time] = Time.iso8601(t)
158
+ rescue ArgumentError
159
+ return usage_error("--reference-time must be ISO 8601 (got #{t.inspect})")
160
+ end
161
+ end
162
+ begin
163
+ files = parser.parse(args)
164
+ rescue OptionParser::ParseError => e
165
+ return usage_error(e.message)
166
+ end
167
+ return usage_error("exactly one menu file required") unless files.size == 1
168
+
169
+ doc = read_json(files.first)
170
+ return doc if doc.is_a?(Integer)
171
+ if options[:from]
172
+ config = nil
173
+ if options[:config]
174
+ config = read_json(options[:config])
175
+ return config if config.is_a?(Integer)
176
+ end
177
+ begin
178
+ result = Importers.import(options[:from], doc, config: config)
179
+ rescue Importers::SourceError => e
180
+ return usage_error(e.message)
181
+ end
182
+ result.notes.each { |n| @stderr.puts "import note: #{n}" }
183
+ doc = result.doc
184
+ end
185
+
186
+ engine = Engine.new
187
+ schema_gate = engine.run(doc, reference_time: options[:reference_time])
188
+ if schema_gate.any? { |f| f.rule == "STRUCT-001" }
189
+ @stderr.puts "menuconform: document fails IR schema validation; fix STRUCT-001 before exporting"
190
+ return 1
191
+ end
192
+
193
+ exporter = UcpExporter.new(catalog: engine.catalog)
194
+ result = exporter.call(doc, reference_time: options[:reference_time])
195
+
196
+ result[:findings].each do |f|
197
+ @stderr.puts "#{f.rule} [#{f.severity}] #{f.entity_type}/#{f.entity_id}: #{f.message}"
198
+ end
199
+ errors = result[:findings].count { |f| f.severity == "error" }
200
+ warns = result[:findings].count { |f| f.severity == "warn" }
201
+ exported = result[:artifact]["catalog"]["products"].size
202
+ @stderr.puts "exported #{exported} product(s) against UCP #{UcpExporter::UCP_SPEC_PIN}; " \
203
+ "#{errors} unrepresentable item(s), #{warns} lossy construct(s)"
204
+
205
+ json = JSON.pretty_generate(result[:artifact])
206
+ options[:out] ? File.write(options[:out], json + "\n") : @stdout.puts(json)
207
+ errors.positive? ? 1 : 0
208
+ end
209
+
210
+ # Returns the parsed document, or an Integer exit code on failure.
211
+ def read_json(path)
212
+ JSON.parse(File.read(path, encoding: "UTF-8"))
213
+ rescue Errno::ENOENT, Errno::EACCES => e
214
+ usage_error("cannot read #{path}: #{e.message}")
215
+ rescue JSON::ParserError => e
216
+ usage_error("#{path} is not valid JSON: #{e.message[0, 120]}")
217
+ end
218
+
219
+ def render(report)
220
+ h = report.to_h
221
+ menu = h["menu"]
222
+ @stdout.puts "menuconform #{h['menuconform_version']} · rules #{h['rules_version']} · reference time #{h['reference_time']}"
223
+ @stdout.puts "Menu: #{menu['name']} (IR #{menu['ir_version']}, #{menu['currency']}, #{menu['timezone']})"
224
+ counts = h["severity_counts"]
225
+ @stdout.puts "Score: #{h['score']}/100 errors: #{counts['error']} warns: #{counts['warn']} infos: #{counts['info']}"
226
+ h["score_breakdown"]["hard_caps"].each { |c| @stdout.puts " capped at #{c['cap']}: #{c['reason']}" }
227
+ @stdout.puts
228
+
229
+ if h["findings"].empty?
230
+ @stdout.puts "No findings. This menu is agent-ready under the implemented rule set."
231
+ return
232
+ end
233
+
234
+ h["findings"].each do |f|
235
+ entity = f["entity"]
236
+ @stdout.puts "#{f['rule']} [#{f['severity']}] #{entity['type']}/#{entity['id']}"
237
+ @stdout.puts " #{f['message']}"
238
+ @stdout.puts " fix: #{f['fix_hint']}"
239
+ end
240
+ end
241
+
242
+ def rules
243
+ catalog = JSON.parse(File.read(Engine::DEFAULT_CATALOG, encoding: "UTF-8"))
244
+ @stdout.puts "rules #{catalog['rules_version']}"
245
+ catalog["rules"].each do |r|
246
+ @stdout.puts "#{r['id'].ljust(13)} #{r['severity'].ljust(5)} #{r['title']}"
247
+ end
248
+ 0
249
+ end
250
+
251
+ def usage_error(message)
252
+ @stderr.puts "menuconform: #{message}"
253
+ 2
254
+ end
255
+ end
256
+ end