omena-query 0.3.0

Omena query boundary over CME producer query fragments
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
use super::*;

mod evaluator;

pub use evaluator::*;

/// Shannon entropy (in bits) of an empirical value-frequency histogram.
///
/// `H(p) = -Σ p_i · log2(p_i)` over the normalised non-zero bins. A uniform
/// histogram maximises entropy (`log2(k)` for `k` distinct symbols); a peaked /
/// more-compressible histogram lowers it. Empty / single-symbol histograms have
/// zero entropy. Deterministic and dependency-light (std `f64::log2` only).
fn value_distribution_entropy_bits(value_frequencies: &[usize]) -> f64 {
    let total: usize = value_frequencies.iter().copied().sum();
    if total == 0 {
        return 0.0;
    }
    let total = total as f64;
    value_frequencies
        .iter()
        .copied()
        .filter(|&count| count > 0)
        .map(|count| {
            let p = count as f64 / total;
            -p * p.log2()
        })
        .sum()
}

/// Compute a genuine two-part minimum-description-length code for a design system.
///
/// claim_level: algorithm (real entropy/log code length, not theorem). This is an
/// honest information-theoretic two-part code, NOT a normalized-maximum-likelihood
/// optimality proof.
///
/// - `model_bits` is the structural code length: each of `rule_count` rules costs
///   `log2(alphabet_size)` bits to point into the distinct value-symbol alphabet
///   (`alphabet_size` = number of non-empty histogram bins). This is a real `log2`,
///   not a count.
/// - `residual_bits` is the multinomial description length of the observations
///   given the model: `observation_count · H(p)` where `H(p)` is the Shannon
///   entropy of `value_frequencies`. Lower-entropy (more compressible) value
///   distributions cost fewer residual bits.
///
/// `total_bits` is therefore a non-linear function of the model structure (`log2`
/// and entropy terms), so it is NOT reproducible by `rule_count + observation_count`.
pub fn summarize_omena_query_design_system_minimum_description(
    source_uri: impl Into<String>,
    source_hash: impl Into<String>,
    rule_count: usize,
    observation_count: usize,
    value_frequencies: &[usize],
) -> DesignSystemMinimumDescriptionV0 {
    let alphabet_size = value_frequencies.iter().filter(|&&count| count > 0).count();
    // Structural code: bits to address each rule's value symbol in the alphabet.
    let model_bits = if alphabet_size > 1 {
        rule_count as f64 * (alphabet_size as f64).log2()
    } else {
        0.0
    };
    // Residual code: multinomial description length of the observations given the
    // empirical value distribution. Uniform distributions cost more than peaked ones.
    let entropy_bits = value_distribution_entropy_bits(value_frequencies);
    let residual_bits = observation_count as f64 * entropy_bits;
    let model_class = if alphabet_size > 1 {
        ModelClassV0::TwoPartMultinomial
    } else {
        ModelClassV0::TwoPartUniform
    };
    DesignSystemMinimumDescriptionV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.design-system-minimum-description",
        layer_marker: "mdl-bits",
        feature_gate: "mdl",
        model_bits,
        residual_bits,
        total_bits: model_bits + residual_bits,
        unit: "bit",
        model_class,
        rule_count,
        observation_count,
        canonical_form_present: false,
        cascade_proof_obligation_count: 0,
        sass_namespace_partition: SassNamespaceBitsV0 {
            namespace_count: 0,
            partition_count: 0,
            deterministic_partition: true,
        },
        generated_at_iso: "deterministic-v0",
        source_pin: SourcePinV0 {
            source_uri: source_uri.into(),
            source_hash: source_hash.into(),
        },
        weights_calibration_pin: "uniform-v0",
        weights_version: "0",
        semiring_instance: "tropical",
    }
}

pub struct OmenaQueryCanonicalFormInput {
    pub pass_id: &'static str,
    pub before: String,
    pub canonical_after: String,
    pub fallback_after: String,
    pub mdl_bits: f64,
    pub ast_size_bits: f64,
    pub iteration_count: usize,
    pub eclass_count: usize,
    pub enode_count: usize,
}

pub fn summarize_omena_query_canonical_form(
    input: OmenaQueryCanonicalFormInput,
) -> CanonicalFormV0 {
    let canonical_matches_fallback = input.canonical_after == input.fallback_after;
    let bits_saved_vs_fallback = input.ast_size_bits - input.mdl_bits;
    CanonicalFormV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.canonical-form",
        layer_marker: "mdl-bits",
        feature_gate: "mdl",
        pass_id: input.pass_id,
        before: input.before,
        canonical_after: input.canonical_after,
        fallback_after: input.fallback_after,
        canonical_matches_fallback,
        bits_saved_vs_fallback,
        mdl_bits: input.mdl_bits,
        ast_size_bits: input.ast_size_bits,
        unit: "bit",
        iteration_count: input.iteration_count,
        eclass_count: input.eclass_count,
        enode_count: input.enode_count,
        cascade_safe_witness: "cascade proof obligation remains conservative",
        egg_analysis_witness: "extracted canonical form is compared against fallback output",
    }
}

pub fn summarize_omena_query_boundary(input: &EngineInputV2) -> OmenaQueryBoundarySummaryV0 {
    let fragment_bundle = summarize_omena_query_fragment_bundle(input);
    let expression_semantics_query_count = fragment_bundle.expression_semantics.fragments.len();
    let source_resolution_query_count = fragment_bundle.source_resolution.fragments.len();
    let selector_usage_query_count = fragment_bundle.selector_usage.fragments.len();

    OmenaQueryBoundarySummaryV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.boundary",
        query_engine_name: "omena-query",
        schema_version_policy: summarize_omena_query_schema_version_policy(),
        input_version: input.version.clone(),
        abstract_value_domain: summarize_omena_query_core_abstract_value_domain(),
        selected_query_adapter_capabilities:
            summarize_omena_query_selected_query_adapter_capabilities(),
        delegated_fragment_products: vec![
            "engine-input-producers.expression-semantics-query-fragments",
            "engine-input-producers.source-resolution-query-fragments",
            "omena-resolver.boundary",
            "omena-resolver.source-resolution-runtime-index",
            "engine-input-producers.selector-usage-query-fragments",
            "engine-input-producers.expression-domain-flow-analysis",
            "engine-input-producers.expression-domain-control-flow-analysis",
            "engine-input-producers.expression-domain-call-site-flow-analysis",
            "engine-input-producers.expression-domain-provenance-explanations",
            "engine-input-producers.expression-domain-reduced-product-iteration",
            "omena-query.expression-domain-incremental-flow-analysis",
            "omena-query.expression-domain-selector-projection",
            "omena-parser.style-facts",
            "omena-query-checker-orchestrator.cascade-gate",
            "omena-query-transform-runner.boundary",
            "omena-transform-bundle.source",
            "omena-transform-target.plan",
            "omena-transform-egg.plan",
            "omena-transform-egg.execution",
            "omena-transform-print.artifact",
            "omena-transform-passes.plan",
            "omena-transform-passes.execution",
            "omena-cascade.custom-property-least-fixed-point",
            "omena-semantic.style-context-index",
            "omena-query.transform-execute",
            "omena-query.transform-context-from-engine-input",
            "omena-query.consumer-check-style-source",
            "omena-query.consumer-build-style-source",
            "omena-query.static-stylesheet-evaluator",
            "omena-scss-eval.oracle",
            "omena-scss-eval.static-value-resolution",
            "omena-query.scss-evaluator-control-flow",
            "omena-query.native-css-evaluator",
            "omena-scss-eval.native-css-function-surface",
            "omena-scss-eval.native-css-if-function-decisions",
            "omena-scss-eval.control-flow-ir",
            "omena-scss-eval.control-flow-value-analysis",
            "omena-scss-eval.call-return-ir",
            "omena-query.static-lif-exports",
            "omena-query.scss-evaluator-control-flow-oracle-corpus",
            "omena-scss-eval.control-flow-oracle-corpus",
            "omena-query.evaluation-runtime",
            "omena-query.fast-facts",
            "omena-query.analyzed-graph",
            "omena-query.custom-property-annotations",
            "omena-query.design-system-minimum-description",
            "omena-abstract-value.polynomial-provenance",
        ],
        expression_semantics_query_count,
        source_resolution_query_count,
        selector_usage_query_count,
        total_query_count: expression_semantics_query_count
            + source_resolution_query_count
            + selector_usage_query_count,
        ready_surfaces: vec![
            "queryFragmentBundle",
            "abstractValueProjectionContract",
            "abstractValueReducedProductAlgebra",
            "sourceResolutionResolverBoundary",
            "sourceResolutionRuntimeIndex",
            "expressionDomainFlowAnalysisBoundary",
            "expressionDomainControlFlowAnalysisBoundary",
            "expressionDomainCallSiteFlowAnalysisBoundary",
            "expressionDomainProvenanceExplanations",
            "expressionDomainReducedProductIteration",
            "expressionDomainSalsaRuntime",
            "expressionDomainSelectorProjection",
            "styleHoverRenderParts",
            "styleMissingCustomPropertyDiagnostics",
            "styleDiagnosticsForFile",
            "sourceDiagnosticsForFile",
            "crossLanguageDiagnostics",
            "cascadeAwareDiagnostics",
            "completionAt",
            "refsForClass",
            "renamePlan",
            "readCascadeAtPosition",
            "readStyleContextIndex",
            "readCascadeCustomPropertyLeastFixedPoint",
            "sourceMissingSelectorDiagnostics",
            "sourceProviderCandidateResolution",
            "selectorRenameEditPlanning",
            "sassSymbolResolutionPrimitives",
            "staticStylesheetEvaluatorOracle",
            "staticStylesheetEvaluatorOracleCorpus",
            "scssEvaluatorControlFlowOracle",
            "nativeCssEvaluatorOracle",
            "staticLifExportsBoundary",
            "scssEvaluatorControlFlowOracleCorpus",
            "sassModuleSourceSelection",
            "omenaParserStyleFactExtraction",
            "queryCheckerOrchestratorBoundary",
            "queryTransformRunnerBoundary",
            "transformPlanFacade",
            "transformEggExecutionWitnesses",
            "transformExecutionRuntime",
            "transformExecutionRunner",
            "semanticReachabilityTransformContext",
            "consumerCheckFacade",
            "consumerBuildFacade",
            "consumerTransformPassListFacade",
            "queryBoundarySummary",
            "selectedQueryBackendAdapter",
            "queryEvaluationRuntime",
            "omenaParserStyleDocumentSummary",
            "omenaParserPublicContractTypes",
            "fastFactsV0",
            "analyzedGraphV0",
            "customPropertyAnnotations",
            "designSystemMinimumDescription",
            "polynomialProvenanceDiagnostics",
        ],
        style_completion_consumer_decisions: style_completion_consumer_decisions(),
        cme_coupled_surfaces: vec!["EngineInputV2", "producerQueryFragments"],
        next_decoupling_targets: Vec::new(),
    }
}

pub fn summarize_omena_query_sass_module_conformance_v0() -> OmenaQuerySassModuleConformanceReportV0
{
    let rows = sass_module_conformance_rows();
    let modeled_count = rows.iter().filter(|row| row.status == "modeled").count();
    let gap_count = rows.iter().filter(|row| row.status == "gap").count();
    let decided_out_count = rows.iter().filter(|row| row.status == "decidedOut").count();
    let policy_count = rows.iter().filter(|row| row.status == "policy").count();
    OmenaQuerySassModuleConformanceReportV0 {
        schema_version: "0",
        product: "omena-query.sass-module-conformance",
        claim_level: "boundedStaticAnalysisCoverageLedger",
        theorem_claimed: false,
        normative_source: "https://github.com/sass/sass/blob/main/accepted/module-system.md",
        modeled_count,
        gap_count,
        decided_out_count,
        policy_count,
        rows,
        ready_surfaces: vec![
            "sassModuleConformanceLedger",
            "mandatoryPolicyRows",
            "gapRowsExplicit",
            "noSassRuntimeEquivalenceClaim",
        ],
    }
}

fn sass_module_conformance_rows() -> Vec<OmenaQuerySassModuleConformanceRowV0> {
    vec![
        OmenaQuerySassModuleConformanceRowV0 {
            key: "useNamespaceVisibility",
            category: "visibility",
            status: "modeled",
            normative_anchor: "module-system.md: @use makes members available through a namespace or as *; private members are not visible through @use",
            implementation: "collect_visible_sass_symbol_keys + collect_exported_sass_symbol_keys",
            witness: "style diagnostics and LSP completion witnesses for namespaced, wildcard, builtin, and hidden Sass symbols",
            decision: "Static member-name visibility is modeled; value execution is not claimed.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "forwardPrefixShowHide",
            category: "forwarding",
            status: "modeled",
            normative_anchor: "module-system.md: @forward exposes another module API; show/hide filters and as-prefix alter forwarded member names",
            implementation: "apply_sass_forward_prefix + sass_forward_filter_allows_symbol",
            witness: "style_diagnostics_respect_prefixed_forward_show_filters and cross-file Sass completion visible-set equality",
            decision: "Forwarded public API names are modeled for static symbol consumers.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "configurationWithDefaultVariables",
            category: "configuration",
            status: "modeled",
            normative_anchor: "module-system.md: with may configure variables defined by or forwarded by a module only when those variables are !default",
            implementation: "derive_sass_module_rule_variable_overrides_at_ordinal + sass_module_configuration_variables_are_valid",
            witness: "style_diagnostics_query_identity_reports_non_default_sass_module_configuration and build scss-module-mode fixtures",
            decision: "Static configuration validity is modeled for known workspace module facts.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "forwardedConfigurationPropagation",
            category: "configuration",
            status: "modeled",
            normative_anchor: "module-system.md: @forward can expose configurable variables and downstream configuration may flow through forwarded APIs",
            implementation: "derive_sass_module_forward_effective_variable_overrides_at_ordinal",
            witness: "style_diagnostics_query_identity_uses_downstream_forward_default_configuration and path-mapped forwarded configuration tests",
            decision: "Forwarded !default configuration is modeled for static graph closure.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "canonicalModuleInstanceIdentity",
            category: "identity",
            status: "modeled",
            normative_anchor: "module-system.md: a module is produced by executing the source file identified by canonical URL with a configuration",
            implementation: "summarize_sass_module_instance_identity_key",
            witness: "sassModuleInstanceIdentity and sassModuleSymlinkResolution diagnostics via omena style-diagnostics",
            decision: "Canonical path plus static configuration signature is the product identity key.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "reconfigurationConflict",
            category: "configuration",
            status: "modeled",
            normative_anchor: "module-system.md: loading an already-executed file with non-empty configuration is an error",
            implementation: "resolve_sass_module_effective_variable_overrides + emitted_module_identity_keys conflict checks",
            witness: "style_diagnostics_query_identity_reports_conflicting_sass_module_configurations and repeated-forward conflict tests",
            decision: "Conflicting static configurations surface through existing Sass module identity diagnostics.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "importContextInterop",
            category: "import",
            status: "modeled",
            normative_anchor: "module-system.md: @import uses a mutable import context and can add imported public API members to the importing stylesheet",
            implementation: "resolve_import_inline_replacement_for_transform_context applies use-aware static module source before importer evaluation",
            witness: "imports_scss_module_public_variables_from_used_imported_file plus omena build product witness",
            decision: "Imported files that use configured modules contribute static public variables and CSS to the importing stylesheet.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "loadPathRelativeIdentityCoherence",
            category: "identity",
            status: "modeled",
            normative_anchor: "module-system.md: module identity is based on canonical URL, not the syntactic route that reached it",
            implementation: "resolve_sass_module_effective_variable_overrides + summarize_sass_module_instance_identity_key",
            witness: "shares_scss_module_identity_across_relative_and_load_path_routes plus omena build product witness",
            decision: "Relative and load-path routes share the canonical configured module instance and emit side-effect CSS once.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "metaLoadCssRuntimeConfiguration",
            category: "runtime",
            status: "decidedOut",
            normative_anchor: "module-system.md: meta.load-css dynamically loads CSS and accepts a $with configuration map without exposing members",
            implementation: "not evaluated by omena-query static Sass module semantics",
            witness: "ledger row only",
            decision: "Runtime CSS inclusion is outside the static member-visibility and identity diagnostic contract.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "importContextMixinFunctionExecution",
            category: "runtime",
            status: "decidedOut",
            normative_anchor: "module-system.md: an imported stylesheet can expose mixins and functions through the import context",
            implementation: "not evaluated by omena-query static stylesheet evaluation",
            witness: "ledger row only",
            decision: "Sass mixin/function execution remains outside the static variable/CSS evaluation contract.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "yarnPnpImporterRuntime",
            category: "resolver",
            status: "decidedOut",
            normative_anchor: "module-system.md: implementations load URLs through importer semantics; package manager runtime hooks are implementation-specific",
            implementation: "resolver policy models package manifests, path mappings, local filesystem candidates, and explicit SIF boundaries",
            witness: "resolution-policy report",
            decision: "Yarn PnP runtime importer emulation is out of scope for this static analyzer.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "deprecatedSassImportPolicy",
            category: "policy",
            status: "policy",
            normative_anchor: "module-system.md: @use/@forward are intended to replace @import; import compatibility remains transitional",
            implementation: "deprecatedSassImport diagnostic",
            witness: "style_diagnostics_for_file_suppresses_sass_builtins_and_hints_imports",
            decision: "Keep the hint on by default at information severity; users can suppress diagnostics without opting into a new setting.",
        },
        OmenaQuerySassModuleConformanceRowV0 {
            key: "aliasExtractionFallbackPolicy",
            category: "policy",
            status: "policy",
            normative_anchor: "module-system.md: loading is importer-defined; omena's resolver policy fixes local precedence without network fetches",
            implementation: "resolution-policy report plus source/style diagnostics for unresolved imports",
            witness: "check-rust-omena-cli-resolution-policy",
            decision: "Use explicit path-mapping/package-manifest settings as the primary fallback; surface graceful unresolved-import diagnostics rather than guessing.",
        },
    ]
}

fn style_completion_consumer_decisions() -> Vec<OmenaQueryStyleCompletionConsumerDecisionV0> {
    vec![
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "omena-lsp-server",
            surface: "textDocument/completion",
            decision: "adoptWorkspaceVisibleSassSymbols",
            rationale: "The Rust LSP owns workspace state and can route style completion through the memoized workspace substrate.",
        },
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "engine-shadow-runner",
            surface: "completion-at",
            decision: "adoptWorkspaceVisibleSassSymbolsWhenStylesProvided",
            rationale: "The selected-query runner already accepts a styles corpus for completion-at and now forwards it to the workspace entry.",
        },
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "server/lsp-server",
            surface: "style-completion-query",
            decision: "staySingleFilePayload",
            rationale: "The TypeScript host currently sends only the active style document to the runner; cross-file adoption belongs at the Rust LSP workspace owner.",
        },
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "omena-napi",
            surface: "read_style_completion_at_position_summary",
            decision: "staySingleFileApi",
            rationale: "The published NAPI facade exposes a stateless single-source API with no workspace resolution input contract.",
        },
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "omena-wasm",
            surface: "read_style_completion_at_position_summary",
            decision: "staySingleFileApi",
            rationale: "The published WASM facade exposes a stateless single-source API with no workspace resolution input contract.",
        },
        OmenaQueryStyleCompletionConsumerDecisionV0 {
            consumer: "omena-cli",
            surface: "omena style-completion",
            decision: "staySingleFileCommand",
            rationale: "The CLI command is a single-file inspection surface; workspace completion should use the selected-query runner or LSP.",
        },
    ]
}

pub fn summarize_omena_query_evaluation_runtime(
    input: &EngineInputV2,
    runtime: &mut OmenaQueryExpressionDomainFlowRuntimeV0,
) -> OmenaQueryEvaluationRuntimeSummaryV0 {
    let selected_query_adapter_capabilities =
        summarize_omena_query_selected_query_adapter_capabilities();
    let source_resolution_runtime = summarize_omena_query_source_resolution_runtime(input);
    let expression_domain_runtime =
        summarize_omena_query_expression_domain_incremental_flow_analysis(input, runtime);

    OmenaQueryEvaluationRuntimeSummaryV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.evaluation-runtime",
        input_version: input.version.clone(),
        selected_query_adapter_capabilities,
        runtime_products: vec![
            source_resolution_runtime.product,
            expression_domain_runtime.product,
            "omena-query.style-document-summary",
        ],
        source_resolution_expression_count: source_resolution_runtime.expression_count,
        source_resolution_unresolved_expression_count: source_resolution_runtime
            .unresolved_expression_count,
        expression_domain_revision: expression_domain_runtime.revision,
        expression_domain_graph_count: expression_domain_runtime.graph_count,
        expression_domain_dirty_graph_count: expression_domain_runtime.dirty_graph_count,
        expression_domain_reused_graph_count: expression_domain_runtime.reused_graph_count,
        style_document_summary_source: "omena-parser.style-facts",
        ready_surfaces: vec![
            "selectedQueryBackendAdapter",
            "sourceResolutionRuntimeIndex",
            "expressionDomainSalsaRuntime",
            "expressionDomainSelectorProjection",
            "omenaParserStyleDocumentSummary",
            "omenaParserPublicContractTypes",
        ],
        retired_couplings: vec![
            "engineStyleParserStyleDocumentSummary",
            "engineStyleParserQueryPublicTypes",
        ],
    }
}

pub fn summarize_omena_query_selected_query_adapter_capabilities()
-> SelectedQueryAdapterCapabilitiesV0 {
    SelectedQueryAdapterCapabilitiesV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.selected-query-adapter-capabilities",
        default_candidate_backend: "rust-selected-query",
        schema_version_policy: summarize_omena_query_schema_version_policy(),
        schema_version_checks: vec![
            check_omena_query_schema_version(Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION)),
            check_omena_query_schema_version(Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION_LABEL)),
            check_omena_query_schema_version(Some("1")),
            check_omena_query_schema_version(None),
        ],
        backend_kinds: vec![
            SelectedQueryBackendCapabilityV0 {
                backend_kind: "typescript-current",
                source_resolution: false,
                expression_semantics: false,
                selector_usage: false,
                style_semantic_graph: false,
            },
            SelectedQueryBackendCapabilityV0 {
                backend_kind: "rust-source-resolution",
                source_resolution: true,
                expression_semantics: false,
                selector_usage: false,
                style_semantic_graph: false,
            },
            SelectedQueryBackendCapabilityV0 {
                backend_kind: "rust-expression-semantics",
                source_resolution: false,
                expression_semantics: true,
                selector_usage: false,
                style_semantic_graph: false,
            },
            SelectedQueryBackendCapabilityV0 {
                backend_kind: "rust-selector-usage",
                source_resolution: false,
                expression_semantics: false,
                selector_usage: true,
                style_semantic_graph: false,
            },
            SelectedQueryBackendCapabilityV0 {
                backend_kind: "rust-selected-query",
                source_resolution: true,
                expression_semantics: true,
                selector_usage: true,
                style_semantic_graph: true,
            },
        ],
        runner_commands: vec![
            SelectedQueryRunnerCommandV0 {
                surface: "queryEvaluationRuntime",
                command: "input-omena-query-evaluation-runtime",
                input_contract: "EngineInputV2 + OmenaQueryExpressionDomainFlowRuntimeV0",
                output_product: "omena-query.evaluation-runtime",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "sourceResolution",
                command: "input-source-resolution-canonical-producer",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.source-resolution-canonical-producer",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "sourceResolutionRuntime",
                command: "input-omena-resolver-source-resolution-runtime",
                input_contract: "EngineInputV2",
                output_product: "omena-resolver.source-resolution-runtime-index",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionSemantics",
                command: "input-expression-semantics-canonical-producer",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-semantics-canonical-producer",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainFlowAnalysis",
                command: "input-expression-domain-flow-analysis",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-domain-flow-analysis",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainControlFlowAnalysis",
                command: "input-expression-domain-control-flow-analysis",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-domain-control-flow-analysis",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainCallSiteFlowAnalysis",
                command: "input-expression-domain-call-site-flow-analysis",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-domain-call-site-flow-analysis",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainProvenanceExplanations",
                command: "input-expression-domain-provenance-explanations",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-domain-provenance-explanations",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainReducedProductIteration",
                command: "input-expression-domain-reduced-product-iteration",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.expression-domain-reduced-product-iteration",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainIncrementalFlowAnalysis",
                command: "input-expression-domain-incremental-flow-analysis",
                input_contract: "EngineInputV2 + OmenaQueryExpressionDomainFlowRuntimeV0",
                output_product: "omena-query.expression-domain-incremental-flow-analysis",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "expressionDomainSelectorProjection",
                command: "input-expression-domain-selector-projection",
                input_contract: "EngineInputV2",
                output_product: "omena-query.expression-domain-selector-projection",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "scssEvaluatorControlFlow",
                command: "input-scss-evaluator-control-flow",
                input_contract: "EngineInputV2 + targetStylePath",
                output_product: "omena-query.scss-evaluator-control-flow",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "scssEvaluatorControlFlowOracleCorpus",
                command: "input-scss-evaluator-control-flow-oracle-corpus",
                input_contract: "none",
                output_product: "omena-query.scss-evaluator-control-flow-oracle-corpus",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "nativeCssEvaluator",
                command: "input-native-css-evaluator",
                input_contract: "EngineInputV2 + targetStylePath",
                output_product: "omena-query.native-css-evaluator",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "staticStylesheetEvaluator",
                command: "input-static-stylesheet-evaluator",
                input_contract: "EngineInputV2 + targetStylePath",
                output_product: "omena-query.static-stylesheet-evaluator",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "staticStylesheetEvaluatorOracleCorpus",
                command: "input-static-stylesheet-evaluator-oracle-corpus",
                input_contract: "none",
                output_product: "omena-query.static-stylesheet-evaluator-oracle-corpus",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "staticLifExports",
                command: "input-static-lif-exports",
                input_contract: "EngineInputV2 + targetStylePath",
                output_product: "omena-query.static-lif-exports",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "selectorUsage",
                command: "input-selector-usage-canonical-producer",
                input_contract: "EngineInputV2",
                output_product: "engine-input-producers.selector-usage-canonical-producer",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "omenaParserStyleFacts",
                command: "omena-parser-style-facts",
                input_contract: "OmenaParserStyleFactsInputV0",
                output_product: "omena-parser.style-facts",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "styleSemanticGraph",
                command: "style-semantic-graph",
                input_contract: "StyleSemanticGraphInputV0",
                output_product: "omena-semantic.style-semantic-graph",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "readCascadeAtPosition",
                command: "read-cascade-at-position",
                input_contract: "ReadCascadeAtPositionInputV0",
                output_product: "omena-query.read-cascade-at-position",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "styleDiagnosticsForFile",
                command: "style-diagnostics-for-file",
                input_contract: "StyleDiagnosticsForFileInputV0",
                output_product: "omena-query.diagnostics-for-file",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "sourceDiagnosticsForFile",
                command: "source-diagnostics-for-file",
                input_contract: "SourceDiagnosticsForFileInputV0",
                output_product: "omena-query.diagnostics-for-file",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "completionAt",
                command: "completion-at",
                input_contract: "CompletionAtInputV0",
                output_product: "omena-query.completion-at",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "styleCodeActions",
                command: "style-code-actions",
                input_contract: "StyleCodeActionsInputV0",
                output_product: "omena-query.code-actions",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "refsForClass",
                command: "refs-for-class",
                input_contract: "RefsForClassInputV0",
                output_product: "omena-query.refs-for-class",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "renamePlan",
                command: "rename-plan",
                input_contract: "RenamePlanInputV0",
                output_product: "omena-query.rename-plan",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "readStyleContextIndex",
                command: "read-style-context-index",
                input_contract: "ReadStyleContextIndexInputV0",
                output_product: "omena-query.style-context-index",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "styleSemanticGraphBatch",
                command: "style-semantic-graph-batch",
                input_contract: "StyleSemanticGraphBatchInputV0",
                output_product: "omena-semantic.style-semantic-graph-batch",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "transformPlan",
                command: "transform-plan",
                input_contract: "TransformPlanInputV0",
                output_product: "omena-query.transform-plan",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "transformContext",
                command: "transform-context",
                input_contract: "TransformContextInputV0",
                output_product: "omena-query.transform-context",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "semanticReachabilityTransformContext",
                command: "transform-context-from-engine-input",
                input_contract: "EngineInputV2 + targetStylePath + closedStyleWorld",
                output_product: "omena-query.transform-context-from-engine-input",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "transformExecute",
                command: "transform-execute",
                input_contract: "TransformExecuteInputV0",
                output_product: "omena-query.transform-execute",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "consumerCheckStyleSource",
                command: "consumer-check-style-source",
                input_contract: "ConsumerStyleSourceInputV0",
                output_product: "omena-query.consumer-check-style-source",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "consumerBuildStyleSource",
                command: "consumer-build-style-source",
                input_contract: "ConsumerStyleSourceBuildInputV0",
                output_product: "omena-query.consumer-build-style-source",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "consumerBuildStyleSources",
                command: "consumer-build-style-sources",
                input_contract: "ConsumerStyleSourcesBuildInputV0",
                output_product: "omena-query.consumer-build-style-source",
            },
            SelectedQueryRunnerCommandV0 {
                surface: "consumerTransformPassList",
                command: "consumer-transform-pass-list",
                input_contract: "None",
                output_product: "omena-query.transform-pass-list",
            },
        ],
        expression_semantics_payload_contracts: vec![
            "valueDomainKind",
            "valueDomainDerivation",
            "valueDomainProvenanceTree",
        ],
        required_input_contracts: vec![
            "EngineInputV2",
            "StyleSemanticGraphInputV0",
            "ReadCascadeAtPositionInputV0",
            "StyleDiagnosticsForFileInputV0",
            "SourceDiagnosticsForFileInputV0",
            "CompletionAtInputV0",
            "StyleCodeActionsInputV0",
            "RefsForClassInputV0",
            "RenamePlanInputV0",
            "ReadStyleContextIndexInputV0",
            "StyleSemanticGraphBatchInputV0",
            "OmenaParserStyleFactsInputV0",
            "TransformPlanInputV0",
            "TransformContextInputV0",
            "TransformContextFromEngineInputV0",
            "TransformExecuteInputV0",
            "ConsumerStyleSourceInputV0",
            "ConsumerStyleSourceBuildInputV0",
            "ConsumerStyleSourcesBuildInputV0",
        ],
        adapter_readiness: vec![
            "backendCapabilityMatrix",
            "canonicalProducerWrapperBoundary",
            "styleSemanticGraphBridgeBoundary",
            "runnerCommandContract",
            "fragmentBundleBoundary",
            "sourceResolutionRuntimeIndex",
            "expressionSemanticsDerivationPayload",
            "expressionDomainFlowAnalysisRunner",
            "expressionDomainControlFlowAnalysisRunner",
            "expressionDomainCallSiteFlowAnalysisRunner",
            "expressionDomainProvenanceExplanationRunner",
            "expressionDomainSalsaRuntime",
            "expressionDomainSelectorProjection",
            "omenaParserStyleFactExtraction",
            "readCascadeAtPosition",
            "readCascadeCustomPropertyLeastFixedPoint",
            "styleDiagnosticsForFileRunner",
            "sourceDiagnosticsForFileRunner",
            "completionAtRunner",
            "styleCodeActionsRunner",
            "refsForClassRunner",
            "renamePlanRunner",
            "readStyleContextIndexRunner",
            "transformPlanRunner",
            "transformEggExecutionWitnesses",
            "transformContextProducer",
            "semanticReachabilityTransformContext",
            "transformExecutionRunner",
            "consumerCheckFacade",
            "consumerBuildFacade",
            "consumerTransformPassListFacade",
            "staticStylesheetEvaluatorFacade",
            "staticStylesheetEvaluatorOracleCorpusFacade",
            "scssEvaluatorControlFlowFacade",
            "nativeCssEvaluatorFacade",
            "scssEvaluatorControlFlowOracleCorpusFacade",
            "queryEvaluationRuntime",
        ],
        routing_status: "runtimeBacked",
    }
}

pub fn summarize_omena_query_schema_version_policy() -> OmenaQuerySchemaVersionPolicyV0 {
    OmenaQuerySchemaVersionPolicyV0 {
        schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        product: "omena-query.schema-version-policy",
        current_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
        current_version_label: OMENA_QUERY_CURRENT_SCHEMA_VERSION_LABEL,
        accepted_versions: vec![OMENA_QUERY_CURRENT_SCHEMA_VERSION],
        deprecated_versions: Vec::new(),
        rejected_version_policy: "rejectUnknownVersionsBeforeExecution",
        missing_version_policy: "rejectMissingSchemaVersionOnExternalInputs",
        migration_policy: vec![
            "new versions require additive reader before writer",
            "old and new versions must run through the same omena-query facade during migration",
            "schema gate must include current accepted, missing, label-only, and future-version checks",
            "breaking payload changes require a new numeric schemaVersion and explicit migration adapter",
        ],
        compatibility_gate: "rust/omena-query/adapter-capabilities",
    }
}

pub fn check_omena_query_schema_version(
    requested_version: Option<&str>,
) -> OmenaQuerySchemaVersionCheckV0 {
    match requested_version {
        Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION) => OmenaQuerySchemaVersionCheckV0 {
            schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            product: "omena-query.schema-version-check",
            requested_version: Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION.to_string()),
            current_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            accepted: true,
            status: "current",
            migration_action: "executeCurrentFacade",
            reason: "requested schemaVersion is the current numeric wire version",
        },
        Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION_LABEL) => OmenaQuerySchemaVersionCheckV0 {
            schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            product: "omena-query.schema-version-check",
            requested_version: Some(OMENA_QUERY_CURRENT_SCHEMA_VERSION_LABEL.to_string()),
            current_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            accepted: false,
            status: "labelOnlyVersionRejected",
            migration_action: "sendNumericSchemaVersion",
            reason: "V0 is a Rust type label; external payloads must use numeric schemaVersion 0",
        },
        Some(version) => OmenaQuerySchemaVersionCheckV0 {
            schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            product: "omena-query.schema-version-check",
            requested_version: Some(version.to_string()),
            current_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            accepted: false,
            status: "unsupportedVersion",
            migration_action: "rejectBeforeExecution",
            reason: "no migration adapter is registered for this schemaVersion",
        },
        None => OmenaQuerySchemaVersionCheckV0 {
            schema_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            product: "omena-query.schema-version-check",
            requested_version: None,
            current_version: OMENA_QUERY_CURRENT_SCHEMA_VERSION,
            accepted: false,
            status: "missingVersion",
            migration_action: "rejectBeforeExecution",
            reason: "external payloads must carry schemaVersion explicitly",
        },
    }
}