File size: 42,978 Bytes
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75b0ca
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b60c31
6dfee1e
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75b0ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9fb9acb
 
 
 
 
 
6dfee1e
 
9fb9acb
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
69d7bba
 
6dfee1e
 
 
2b60c31
 
6dfee1e
 
 
 
 
 
 
 
12634a1
 
 
6dfee1e
 
12634a1
69d7bba
12634a1
6dfee1e
 
 
 
 
 
 
69d7bba
 
 
9fb9acb
 
 
 
 
 
 
69d7bba
9fb9acb
 
 
 
 
 
69d7bba
5d22400
69d7bba
 
 
 
 
9fb9acb
 
 
 
 
 
 
 
6dfee1e
 
 
 
 
 
 
9fb9acb
 
5d22400
69d7bba
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
69d7bba
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
9fb9acb
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
69d7bba
 
 
 
6dfee1e
69d7bba
 
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
2b60c31
e75b0ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75b0ca
 
 
 
 
 
 
 
2b60c31
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e75b0ca
 
 
 
 
2b60c31
e75b0ca
2b60c31
e75b0ca
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
e75b0ca
 
6dfee1e
 
2b60c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6dfee1e
 
69d7bba
e75b0ca
 
 
12634a1
69d7bba
2b60c31
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
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Divid Teacher - Deterministic Question Executor

Strategic rule:
- Qwen owns semantic/linguistic content only.
- The platform owns deterministic mechanics.
- Contract / Recipe / Schema are authoritative.
- Never guess missing semantic truth.

This pure executor compiles model semantic content into the canonical mechanics
expected by question_interaction_contract. It does not select skills, recipes,
diagnostic conditions, models, media, or student progress.
"""
from __future__ import annotations

import copy
import hashlib
import json
import re
from typing import Any, Dict, List, Tuple

from question_interaction_contract import (
    VERSION as INTERACTION_CONTRACT_VERSION,
    canonical_family,
    canonicalize_question,
)

VERSION = "deterministic_question_executor_v7_hidden_audio_sequence_units"


def _text(value: Any) -> str:
    return str(value or "").strip()


def _lower(value: Any) -> str:
    return _text(value).lower()


def _as_dict(value: Any) -> Dict[str, Any]:
    return dict(value) if isinstance(value, dict) else {}


def _as_list(value: Any) -> List[Any]:
    if value in (None, ""):
        return []
    if isinstance(value, list):
        return list(value)
    if isinstance(value, (tuple, set)):
        return list(value)
    return [value]


def _norm(value: Any) -> str:
    if isinstance(value, (dict, list, tuple, set)):
        try:
            value = json.dumps(value, ensure_ascii=False, sort_keys=True, default=str)
        except Exception:
            value = str(value)
    text = _text(value).casefold().replace("ـ", "")
    text = text.replace("أ", "ا").replace("إ", "ا").replace("آ", "ا")
    text = text.replace("ة", "ه").replace("ى", "ي")
    return re.sub(r"\s+", " ", text).strip()


def _label(value: Any) -> str:
    if isinstance(value, dict):
        return _text(
            value.get("label_ar")
            or value.get("label")
            or value.get("text")
            or value.get("semantic_value")
            or value.get("value")
            or value.get("id")
            or value.get("key")
        )
    return _text(value)


def _semantic_key(value: Any) -> str:
    if isinstance(value, dict):
        return _text(
            value.get("semantic_value")
            or value.get("value")
            or value.get("id")
            or value.get("key")
            or _label(value)
        )
    return _text(value)


def _record(value: Any, index: int, prefix: str) -> Dict[str, Any]:
    if isinstance(value, dict):
        out = copy.deepcopy(value)
        label = _label(value)
        semantic = _semantic_key(value) or label
        rid = _text(value.get("id") or value.get("key"))
        if not rid:
            rid = f"{prefix}_{index + 1}"
        out["id"] = rid
        if label:
            out["label"] = label
            out.setdefault("label_ar", label)
        out["semantic_value"] = semantic or rid
        out.setdefault("value", semantic or rid)
        return out
    label = _text(value)
    return {
        "id": f"{prefix}_{index + 1}",
        "label": label,
        "label_ar": label,
        "semantic_value": label,
        "value": label,
    }


def _records(values: Any, prefix: str) -> List[Dict[str, Any]]:
    rows = _as_list(values)
    out: List[Dict[str, Any]] = []
    seen = set()
    for idx, row in enumerate(rows):
        rec = _record(row, idx, prefix)
        key = _norm(rec.get("semantic_value") or rec.get("label") or rec.get("id"))
        if not key or key in seen:
            continue
        seen.add(key)
        out.append(rec)
    return out


def _relation_rows(value: Any) -> List[Tuple[Any, Any]]:
    rows: List[Tuple[Any, Any]] = []
    for row in _as_list(value):
        if isinstance(row, dict):
            left = (
                row.get("left")
                or row.get("source")
                or row.get("item")
                or row.get("from")
                or row.get("key")
            )
            right = (
                row.get("right")
                or row.get("target")
                or row.get("match")
                or row.get("to")
                or row.get("value")
            )
            if left not in (None, "", [], {}) and right not in (None, "", [], {}):
                rows.append((copy.deepcopy(left), copy.deepcopy(right)))
        elif isinstance(row, (list, tuple)) and len(row) >= 2:
            rows.append((copy.deepcopy(row[0]), copy.deepcopy(row[1])))
    return rows


def _mapping_rows(value: Any) -> List[Tuple[Any, Any]]:
    if isinstance(value, dict):
        return [
            (copy.deepcopy(k), copy.deepcopy(v))
            for k, v in value.items()
            if _text(k) and _text(v)
        ]
    return _relation_rows(value)


def _lookup(records: List[Dict[str, Any]]) -> Dict[str, str]:
    out: Dict[str, str] = {}
    for rec in records:
        rid = _text(rec.get("id"))
        for value in (
            rec.get("id"),
            rec.get("key"),
            rec.get("semantic_value"),
            rec.get("value"),
            rec.get("label"),
            rec.get("label_ar"),
            rec.get("text"),
        ):
            key = _norm(value)
            if key and rid:
                out.setdefault(key, rid)
    return out


def _ensure_record(
    records: List[Dict[str, Any]],
    value: Any,
    prefix: str,
) -> Dict[str, Any]:
    key = _norm(_semantic_key(value) or _label(value))
    existing = _lookup(records)
    if key and key in existing:
        rid = existing[key]
        return next(rec for rec in records if _text(rec.get("id")) == rid)
    rec = _record(value, len(records), prefix)
    records.append(rec)
    return rec


def _stable_shuffle(records: List[Dict[str, Any]], seed: str) -> List[Dict[str, Any]]:
    if len(records) < 2:
        return copy.deepcopy(records)
    decorated = []
    for index, rec in enumerate(records):
        raw = f"{seed}|{index}|{_text(rec.get('id'))}|{_text(rec.get('semantic_value'))}"
        digest = hashlib.sha256(raw.encode("utf-8")).hexdigest()
        decorated.append((digest, index, copy.deepcopy(rec)))
    shuffled = [row[2] for row in sorted(decorated)]
    if [_text(x.get("id")) for x in shuffled] == [_text(x.get("id")) for x in records]:
        shuffled = shuffled[1:] + shuffled[:1]
    return shuffled


def build_semantic_model_schema(
    final_schema: Dict[str, Any],
    ownership: Dict[str, Any],
    *,
    family: str,
    recipe: Dict[str, Any] | None = None,
) -> Dict[str, Any]:
    """Build the model-facing semantic schema.

    Final mechanics are intentionally absent for pair/sequence. The executor
    compiles them after Qwen returns semantic content.
    """
    final = copy.deepcopy(final_schema or {})
    ownership = copy.deepcopy(ownership or {})
    writable = set(str(x) for x in (ownership.get("model_writable_fields") or []))
    final_props = final.get("properties") if isinstance(final.get("properties"), dict) else {}

    props: Dict[str, Any] = {}
    required: List[str] = []

    # Common semantic fields that may already exist in the final schema.
    for key in ("question", "audio_text", "stimulus"):
        if key in writable:
            props[key] = copy.deepcopy(final_props.get(key) or {"type": "string"})
            if key in (final.get("required") or []):
                required.append(key)

    family = _lower(family)
    recipe = _as_dict(recipe)
    response_contract = _as_dict(recipe.get("response_contract"))
    response_kind = _lower(response_contract.get("kind"))
    allowed_visual_tokens = [
        _text(x)
        for x in _as_list(response_contract.get("allowed_visual_tokens"))
        if _text(x)
    ]
    system_visual_word_mechanics = bool(
        family == "pair"
        and response_kind in {
            "visual_word_segmentation_mapping",
            "visual_word_boundary_mapping",
            "visual_word_unit_mapping",
        }
        and response_contract.get("text_word_options_forbidden") is True
        and allowed_visual_tokens
    )

    if family == "pair" and system_visual_word_mechanics:
        # Qwen generates linguistic stimulus only. The platform derives all visible
        # tokens and pair mechanics from the declared Recipe.
        props.pop("stimulus", None)
        required = [x for x in required if x != "stimulus"]

    elif family == "pair":
        # Qwen supplies semantic relationships; platform creates ids, payload and mapping.
        props["pairs"] = {
            "type": "array",
            "minItems": 1,
            "description": (
                "العلاقات الدلالية الصحيحة فقط. كل عنصر يحتوي left وright. "
                "لا تنشئ interaction_payload أو mapping ids."
            ),
            "items": {
                "type": "object",
                "required": ["left", "right"],
                "properties": {
                    "left": {},
                    "right": {},
                },
                "additionalProperties": False,
            },
        }
        props["items"] = {
            "type": "array",
            "description": "محتوى العناصر اليسرى إن احتجت بيانات عرض إضافية.",
            "items": {},
        }
        props["targets"] = {
            "type": "array",
            "description": "محتوى الأهداف اليمنى إن احتجت بيانات عرض إضافية.",
            "items": {},
        }
        required.append("pairs")

    elif family == "sequence":
        hidden_audio_sequence = bool(
            ownership.get("hidden_audio_sequence_scope_guard") is True
            or (
                ownership.get("stimulus_audio_text_required") is True
                and "items" not in writable
            )
        )
        if not hidden_audio_sequence:
            props["items"] = {
                "type": "array",
                "minItems": 2,
                "description": (
                    "العناصر الدلالية بالترتيب الصحيح. النظام ينشئ IDs ويخلط ترتيب العرض "
                    "ويحفظ correct_order."
                ),
                "items": {},
            }
            required.append("items")
        # Hidden-audio sequences are different: Qwen supplies audio_text only.
        # The deterministic executor derives internal spoken units after submission.

    elif family in {"single_choice", "multi_choice"}:
        # Options and semantic answer remain model content unless the Recipe made them system-owned.
        if "options" in writable:
            props["options"] = copy.deepcopy(final_props.get("options") or {"type": "array"})
            required.append("options")
        elif "choices" in writable:
            props["choices"] = {"type": "array"}
            required.append("choices")
        if "correct_answer" in writable:
            props["correct_answer"] = copy.deepcopy(final_props.get("correct_answer") or {})
            required.append("correct_answer")

    elif family in {"numeric", "text"}:
        if "correct_answer" in writable:
            props["correct_answer"] = copy.deepcopy(final_props.get("correct_answer") or {})
            required.append("correct_answer")

    elif family in {"oral", "external"}:
        # Preserve an explicitly allowed semantic payload only for families whose
        # evaluator/tool state is inherently external.
        if "interaction_payload" in writable:
            props["interaction_payload"] = copy.deepcopy(
                final_props.get("interaction_payload") or {"type": "object"}
            )

    # Audio text can be mandatory even if the final mechanical schema does not
    # explicitly make the model responsible for anything else.
    if ownership.get("stimulus_audio_text_required") and "audio_text" in writable:
        props.setdefault("audio_text", {"type": "string"})
        if "audio_text" not in required:
            required.append("audio_text")

    return {
        "type": "object",
        "required": list(dict.fromkeys(required)),
        "properties": props,
        "additionalProperties": False,
        "model_output_scope": ownership.get("scope", "bounded_question_content"),
        "semantic_contract_input": True,
        "mechanics_compiled_by_system": True,
        "response_family": family,
        "response_kind": response_kind,
        "system_visual_word_mechanics": system_visual_word_mechanics,
    }



_ARABIC_DIACRITICS_RE = re.compile(r"[\u064b-\u065f\u0670]")


def _spoken_words(value: Any) -> List[str]:
    """Whitespace lexical units for already-generated spoken stimulus.

    This is a deterministic mechanical count only. It does not create or correct
    linguistic content.
    """
    text = _text(value)
    if not text:
        return []
    text = _ARABIC_DIACRITICS_RE.sub("", text)
    # Strip punctuation at token boundaries but preserve letters/numbers.
    raw = re.split(r"\s+", text)
    out: List[str] = []
    for token in raw:
        cleaned = re.sub(r"^[^\w\u0600-\u06FF]+|[^\w\u0600-\u06FF]+$", "", token, flags=re.UNICODE)
        if cleaned:
            out.append(cleaned)
    return out


def _visual_pattern(unit: str, boundary: str, count: int) -> str:
    count = max(1, int(count or 1))
    if count == 1:
        return unit
    return f" {boundary} ".join([unit] * count)


def _visual_pattern_without_one_boundary(unit: str, boundary: str, count: int) -> str:
    """A merge-error distractor using only declared visual tokens."""
    count = max(2, int(count or 2))
    parts = [unit] * count
    # Merge first two word tokens by omitting one boundary.
    merged_head = unit + unit
    if count == 2:
        return merged_head
    return merged_head + f" {boundary} " + f" {boundary} ".join(parts[2:])


def _token_only_visual(value: Any, allowed_tokens: List[str]) -> bool:
    """True only when visible text is composed exclusively of declared tokens."""
    text = _text(value)
    if not text:
        return True
    remainder = re.sub(r"\s+", "", text)
    for token in sorted([x for x in allowed_tokens if x], key=len, reverse=True):
        remainder = remainder.replace(token, "")
    return remainder == ""


def _compile_declared_visual_word_mapping(
    q: Dict[str, Any],
    *,
    response: Dict[str, Any],
    stimulus_contract: Dict[str, Any],
    audit: Dict[str, Any],
) -> Tuple[Dict[str, Any], List[str]]:
    """Compile spoken-word visual mapping from Recipe declarations only.

    No written stimulus words are exposed. The semantic sentence remains in
    audio_text for media generation; the student sees only allowed_visual_tokens.
    """
    out = copy.deepcopy(q)
    errors: List[str] = []

    allowed = [
        _text(x)
        for x in _as_list(response.get("allowed_visual_tokens"))
        if _text(x)
    ]
    if not allowed:
        return out, ["contract_visual_tokens_missing"]

    unit = next((x for x in allowed if x != "|"), allowed[0])
    boundary = "|" if "|" in allowed else (allowed[1] if len(allowed) > 1 else allowed[0])

    words = _spoken_words(out.get("audio_text"))
    word_count = len(words)

    min_words = int(
        stimulus_contract.get("spoken_phrase_words_min")
        or stimulus_contract.get("word_count_min")
        or 1
    )
    max_words_raw = (
        stimulus_contract.get("spoken_phrase_words_max")
        or stimulus_contract.get("word_count_max")
        or 0
    )
    max_words = int(max_words_raw or 0)

    if not words:
        errors.append("semantic_required:audio_text")
        return out, errors
    if word_count < min_words:
        errors.append(f"stimulus_word_count_below_min:{word_count}<{min_words}")
        return out, errors
    if max_words and word_count > max_words:
        errors.append(f"stimulus_word_count_above_max:{word_count}>{max_words}")
        return out, errors

    correct_pattern = _visual_pattern(unit, boundary, word_count)
    diagnostic_condition = _lower(out.get("diagnostic_condition"))

    # V6: the diagnostic condition must change the observable probe operation.
    # Previously correct/merge/split conditions all compiled to the same target set,
    # so different slot names could masquerade as independent evidence.
    operation_id = "segment_spoken_sentence"
    distractors: List[str] = []

    if diagnostic_condition == "merge_error_candidate":
        operation_id = "discriminate_merged_word_boundary"
        if word_count >= 2:
            distractors.append(
                _visual_pattern_without_one_boundary(unit, boundary, word_count)
            )
        # Strong merge: all spoken units shown with no boundaries.
        distractors.append(unit * max(2, word_count))
    elif diagnostic_condition == "split_error_candidate":
        operation_id = "discriminate_oversegmented_word_boundary"
        distractors.append(_visual_pattern(unit, boundary, word_count + 1))
        distractors.append(_visual_pattern(unit, boundary, word_count + 2))
    else:
        # Baseline / general segmentation keeps balanced merge + split alternatives.
        if word_count >= 2:
            distractors.append(
                _visual_pattern_without_one_boundary(unit, boundary, word_count)
            )
        distractors.append(_visual_pattern(unit, boundary, word_count + 1))
        if word_count >= 3:
            distractors.append(_visual_pattern(unit, boundary, max(1, word_count - 1)))

    visible_patterns: List[str] = []
    for pattern in [correct_pattern] + distractors:
        if pattern and pattern not in visible_patterns:
            visible_patterns.append(pattern)
    if len(visible_patterns) < 2:
        errors.append("contract_visual_distractors_insufficient")
        return out, errors

    source = {
        "id": "stimulus_audio",
        "label": "🔊 الجملة المسموعة",
        "label_ar": "🔊 الجملة المسموعة",
        "semantic_value": "audio_stimulus",
        "value": "audio_stimulus",
        "audio_asset_role": "prompt_audio",
    }

    targets: List[Dict[str, Any]] = []
    correct_target_id = ""
    for index, pattern in enumerate(visible_patterns):
        target_id = f"target_{index + 1}"
        if index == 0:
            correct_target_id = target_id
        targets.append({
            "id": target_id,
            # Keep structural identity separate from student-facing meaning.
            # QuestionInteractionEngine uses semantic_value when it canonicalizes
            # pair-zone display, so target_1/target_2 must never live there.
            "label": pattern,
            "label_ar": pattern,
            "semantic_value": pattern,
            "value": target_id,
            "internal_id": target_id,
        })

    # Stable deterministic shuffle for presentation while preserving target IDs.
    seed = _text(out.get("audio_text")) + "|" + _text(out.get("diagnostic_condition"))
    targets = _stable_shuffle(targets, seed)

    mapping = {"stimulus_audio": correct_target_id}

    response_kind = _lower(response.get("kind"))
    if response_kind == "visual_word_segmentation_mapping":
        if diagnostic_condition == "merge_error_candidate":
            instruction = "استمع واختر الفصل دون دمج الكلمات."
        elif diagnostic_condition == "split_error_candidate":
            instruction = "استمع واختر الفصل دون تقسيم زائد."
        else:
            # Six Arabic whitespace tokens exactly.
            instruction = "استمع واختر شكل فصل الكلمات الصحيح."
    elif response_kind == "visual_word_boundary_mapping":
        if diagnostic_condition == "merge_error_candidate":
            instruction = "استمع واختر الحدود دون دمج الكلمات."
        elif diagnostic_condition == "split_error_candidate":
            instruction = "استمع واختر الحدود دون تقسيم زائد."
        else:
            instruction = "استمع واختر شكل حدود الكلمات الصحيح."
    else:
        instruction = "استمع واختر تمثيل الكلمات الصحيح."

    out["question"] = instruction
    out["prompt"] = instruction
    out["text"] = instruction

    if operation_id == "discriminate_merged_word_boundary":
        student_help = "اختر الشكل الذي يحافظ على كل حدود الكلمات."
    elif operation_id == "discriminate_oversegmented_word_boundary":
        student_help = "اختر الشكل دون إضافة فاصل زائد."
    else:
        student_help = "اختر الشكل الموافق للجملة المسموعة."

    out["evidence_operation_id"] = operation_id
    out["interaction_payload"] = {
        "left_items": [copy.deepcopy(source)],
        "drag_items": [copy.deepcopy(source)],
        "targets": copy.deepcopy(targets),
        "drop_zones": copy.deepcopy(targets),
        "mapping_answer": copy.deepcopy(mapping),
        "correct_mapping": copy.deepcopy(mapping),
        "evidence_operation_id": operation_id,
        "student_help": student_help,
        "student_legend": "● = كلمة، | = فاصل",
        "internal_labels_visible": False,
    }
    out["correct_mapping"] = copy.deepcopy(mapping)
    out["correct_answer"] = copy.deepcopy(mapping)
    out["correct_response"] = copy.deepcopy(mapping)
    out["answer"] = copy.deepcopy(mapping)

    # No model semantic pair/items/targets may leak into rendering.
    out.pop("pairs", None)
    out.pop("items", None)
    out.pop("targets", None)
    out["options"] = []
    out["choices"] = []

    # Only target answers must be token-only. The neutral source descriptor
    # does not reveal the hidden audio transcript.
    for record in targets:
        for key in ("label", "label_ar"):
            value = record.get(key)
            if not _token_only_visual(value, allowed):
                errors.append(f"visual_token_contract_violation:{key}")

    audit["compiled_fields"].extend([
        "interaction_payload", "correct_mapping",
        "correct_answer", "correct_response", "answer",
    ])
    audit["semantic_inputs_consumed"].append("audio_text")
    audit["visual_policy"] = {
        "kind": _text(response.get("kind")),
        "allowed_visual_tokens": allowed,
        "written_word_labels_exposed": False,
        "word_count": word_count,
        "diagnostic_condition": diagnostic_condition,
        "evidence_operation_id": operation_id,
    }
    return out, list(dict.fromkeys(errors))


def _validate_declared_visual_surface(
    q: Dict[str, Any],
    response: Dict[str, Any],
) -> List[str]:
    """Fail closed if forbidden written labels reach any visible interaction field."""
    allowed = [
        _text(x)
        for x in _as_list(response.get("allowed_visual_tokens"))
        if _text(x)
    ]
    if not allowed or response.get("text_word_options_forbidden") is not True:
        return []

    errors: List[str] = []
    payload = _as_dict(q.get("interaction_payload"))
    visible_records: List[Dict[str, Any]] = []
    for key in ("left_items", "drag_items", "targets", "drop_zones", "items"):
        for row in _as_list(payload.get(key)):
            if isinstance(row, dict):
                visible_records.append(row)

    for row in visible_records:
        is_audio_source = bool(
            _text(row.get("audio_asset_role")) == "prompt_audio"
            or _text(row.get("id")) in {"stimulus_audio", "stimulus_media"}
        )
        for key in ("label", "label_ar", "text", "visual_token"):
            if key not in row:
                continue
            if is_audio_source and key in {"label", "label_ar", "text"}:
                continue
            if not _token_only_visual(row.get(key), allowed):
                errors.append(f"visual_surface_forbidden_text:{key}")

    for key in ("options", "choices"):
        for value in _as_list(q.get(key)):
            label = _label(value)
            if label and not _token_only_visual(label, allowed):
                errors.append(f"visual_surface_forbidden_text:{key}")

    return list(dict.fromkeys(errors))



def _hidden_audio_sequence_enabled(
    *,
    family: str,
    ownership: Dict[str, Any],
    response: Dict[str, Any],
    stimulus_contract: Dict[str, Any],
    recipe: Dict[str, Any],
) -> bool:
    """Generic contract/ownership test for audio-only sequence mechanics."""
    if _lower(family) != "sequence":
        return False

    if ownership.get("hidden_audio_sequence_scope_guard") is True:
        return True

    writable = {
        str(x) for x in _as_list(ownership.get("model_writable_fields"))
        if _text(x)
    }
    audio_required = bool(
        ownership.get("stimulus_audio_text_required") is True
        or stimulus_contract.get("audio_text_required") is True
    )
    model_items_forbidden = bool(writable and "items" not in writable)

    # Declarative recipe signals. Keep these generic; no skill/template ids.
    hidden_text_flags = any(
        source.get(key) is True
        for source in (recipe, response, stimulus_contract)
        for key in (
            "reading_dependency_forbidden",
            "avoid_visual_text_dependency",
            "visible_orthographic_word_tokens_forbidden_when_decoding_not_target",
            "semantic_audio_labels_must_not_be_used_as_visible_mechanics",
            "visible_transcript_forbidden",
            "visible_audio_transcript_forbidden",
            "text_word_options_forbidden",
        )
        if isinstance(source, dict)
    )

    spoken_units = any(
        source.get(key) is True
        for source in (recipe, response, stimulus_contract)
        for key in (
            "spoken_word_units_required",
            "audio_for_word_units_required",
        )
        if isinstance(source, dict)
    )

    return bool(
        audio_required
        and (
            model_items_forbidden
            or hidden_text_flags
            or spoken_units
        )
    )


def _compile_hidden_audio_sequence(
    q: Dict[str, Any],
    *,
    src: Dict[str, Any],
    audit: Dict[str, Any],
) -> Tuple[Dict[str, Any], List[str]]:
    """Compile a spoken sentence into audio-only ordering units.

    Qwen owns the linguistic sentence in ``audio_text``.  The platform performs
    the deterministic split, creates internal ids, shuffles presentation order,
    and stores the correct id order.  Written stimulus words are never copied
    into any visible label/semantic_value/value field.

    Each ordering record retains its word only in ``audio_text`` so downstream
    media generation can synthesize/play the individual spoken unit.
    """
    out = copy.deepcopy(q)
    errors: List[str] = []

    words = _spoken_words(out.get("audio_text"))
    if len(words) < 2:
        return out, ["semantic_required:audio_text_sequence_units"]

    records: List[Dict[str, Any]] = []
    for index, word in enumerate(words):
        rid = f"audio_item_{index + 1}"
        records.append({
            "id": rid,
            # Neutral visible surface. No correct-position numbering and no
            # transcript word in renderer-facing semantic fields.
            "label": "🔊",
            "label_ar": "🔊",
            "semantic_value": rid,
            "value": rid,
            "visual_token": "🔊",
            # Hidden semantic/media source only.
            "audio_text": word,
            "audio_asset_role": "sequence_item_audio",
            "transcript_visible": False,
        })

    correct_ids = [_text(x.get("id")) for x in records]
    seed = _text(
        src.get("runtime_generation_seed")
        or src.get("seed")
        or _as_dict(src.get("assessment_generation_contract")).get("runtime_generation_seed")
        or src.get("skill_id")
        or out.get("audio_text")
        or "hidden_audio_sequence"
    )
    display_records = _stable_shuffle(records, seed)

    out["interaction_payload"] = {
        "ordering_items": copy.deepcopy(display_records),
        "items": copy.deepcopy(display_records),
        "correct_order": list(correct_ids),
        "audio_only_sequence": True,
        "visible_transcript": False,
        "internal_labels_visible": False,
    }
    out["correct_answer"] = list(correct_ids)
    out["correct_response"] = list(correct_ids)
    out["answer"] = list(correct_ids)

    # No semantic transport arrays may compete with deterministic mechanics.
    out.pop("items", None)
    out.pop("targets", None)
    out.pop("pairs", None)
    out["options"] = []
    out["choices"] = []

    audit["semantic_inputs_consumed"].append("audio_text")
    audit["compiled_fields"].extend([
        "interaction_payload", "correct_answer", "correct_response", "answer",
    ])
    audit["hidden_audio_sequence"] = {
        "enabled": True,
        "spoken_unit_count": len(records),
        "written_word_labels_exposed": False,
        "media_source_field": "ordering_items[].audio_text",
        "visible_token": "🔊",
    }

    return out, errors


def _validate_hidden_audio_sequence_surface(q: Dict[str, Any]) -> List[str]:
    """Fail closed if a hidden-audio sequence exposes transcript text visibly."""
    payload = _as_dict(q.get("interaction_payload"))
    if payload.get("audio_only_sequence") is not True:
        return []

    errors: List[str] = []
    for row in _as_list(payload.get("ordering_items") or payload.get("items")):
        if not isinstance(row, dict):
            continue

        hidden_audio = _text(row.get("audio_text"))
        hidden_norm = _norm(hidden_audio)
        for key in ("label", "label_ar", "text", "semantic_value", "value"):
            visible = _text(row.get(key))
            if not visible:
                continue
            # Internal ids are allowed in semantic/value; transcript words are not.
            if hidden_norm and _norm(visible) == hidden_norm:
                errors.append(f"hidden_audio_sequence_visible_transcript:{key}")

        if row.get("transcript_visible") is True:
            errors.append("hidden_audio_sequence_transcript_visible_flag")

    return list(dict.fromkeys(errors))


def execute(
    candidate: Dict[str, Any],
    payload: Dict[str, Any],
) -> Tuple[Dict[str, Any], List[str], Dict[str, Any]]:
    """Compile semantic model output into deterministic question mechanics.

    Returns: (compiled_question, errors, audit)
    Errors use ``semantic_required:<field>`` when only Qwen can supply missing
    semantic truth. Structural mechanics are never requested from Qwen.
    """
    q = copy.deepcopy(candidate if isinstance(candidate, dict) else {})
    src = dict(payload or {}) if isinstance(payload, dict) else {}
    recipe = (
        src.get("generation_recipe")
        or src.get("resolved_generation_recipe")
        or {}
    )
    recipe = recipe if isinstance(recipe, dict) else {}
    response = _as_dict(recipe.get("response_contract"))
    stimulus_contract = _as_dict(recipe.get("stimulus_contract"))
    response_kind = _lower(response.get("kind"))
    ownership = (
        src.get("model_output_ownership")
        if isinstance(src.get("model_output_ownership"), dict)
        else {}
    )
    system_values = _as_dict(ownership.get("system_owned_values"))

    # Immutable mechanics/identity.
    for key in ("template_id", "item_type", "difficulty", "response_mode", "scoring_mode"):
        if src.get(key) not in (None, ""):
            q[key] = copy.deepcopy(src.get(key))
    q["question_type"] = q.get("item_type")

    if system_values.get("question") not in (None, ""):
        instruction = _text(system_values.get("question"))
        q["question"] = instruction
        q["prompt"] = instruction
        q["text"] = instruction

    text_options_forbidden = bool(
        response.get("options_forbidden") is True
        or response.get("text_word_options_forbidden") is True
    )
    if text_options_forbidden:
        q["options"] = []
        q["choices"] = []

    family = canonical_family(
        q.get("response_family"),
        q.get("response_mode") or src.get("response_mode"),
        q.get("item_type") or src.get("item_type"),
        q.get("scoring_mode") or src.get("scoring_mode"),
    )
    q["response_family"] = family

    hidden_audio_sequence = _hidden_audio_sequence_enabled(
        family=family,
        ownership=ownership,
        response=response,
        stimulus_contract=stimulus_contract,
        recipe=recipe,
    )

    audit: Dict[str, Any] = {
        "executor_version": VERSION,
        "family": family,
        "mechanics_owner": "system",
        "semantic_owner": "qwen_or_authoritative_source",
        "compiled_fields": [],
        "semantic_inputs_consumed": [],
        "guessed_semantic_truth": False,
    }
    errors: List[str] = []

    declared_visual_word_mapping = bool(
        family == "pair"
        and response_kind in {
            "visual_word_segmentation_mapping",
            "visual_word_boundary_mapping",
            "visual_word_unit_mapping",
        }
        and response.get("text_word_options_forbidden") is True
        and _as_list(response.get("allowed_visual_tokens"))
    )

    if declared_visual_word_mapping:
        q, visual_errors = _compile_declared_visual_word_mapping(
            q,
            response=response,
            stimulus_contract=stimulus_contract,
            audit=audit,
        )
        errors.extend(visual_errors)

    elif family == "pair":
        existing_payload = _as_dict(q.get("interaction_payload"))
        left = _records(
            q.get("items")
            or existing_payload.get("drag_items")
            or existing_payload.get("left_items")
            or existing_payload.get("items")
            or [],
            "item",
        )
        targets = _records(
            q.get("targets")
            or existing_payload.get("drop_zones")
            or existing_payload.get("right_items")
            or existing_payload.get("targets")
            or [],
            "target",
        )

        relations = _relation_rows(q.get("pairs"))
        if relations:
            audit["semantic_inputs_consumed"].append("pairs")
        if not relations:
            relations = _mapping_rows(
                q.get("correct_mapping")
                or existing_payload.get("correct_mapping")
                or existing_payload.get("mapping_answer")
                or (
                    q.get("correct_answer")
                    if isinstance(q.get("correct_answer"), dict)
                    else {}
                )
            )
            if relations:
                audit["semantic_inputs_consumed"].append("existing_semantic_mapping")

        # A scalar answer can deterministically select one target only when there is
        # exactly one source item. The scalar itself is semantic truth supplied upstream.
        scalar_answer = q.get("correct_answer")
        if not relations and scalar_answer not in (None, "", [], {}) and not isinstance(scalar_answer, (dict, list, tuple, set)):
            if not left and _text(q.get("audio_text")):
                left = [{
                    "id": "stimulus_audio",
                    "label": "",
                    "label_ar": "",
                    "semantic_value": "audio_stimulus",
                    "value": "audio_stimulus",
                    "visual_token": "🔊",
                    "audio_asset_role": "prompt_audio",
                }]
            if len(left) == 1 and targets:
                relations = [(left[0].get("semantic_value") or left[0].get("id"), scalar_answer)]
                audit["semantic_inputs_consumed"].append("scalar_correct_answer")

        # Semantic pair rows can themselves create the content records.
        for lval, rval in relations:
            _ensure_record(left, lval, "item")
            _ensure_record(targets, rval, "target")

        if not relations:
            errors.append("semantic_required:pairs")
        if not left:
            errors.append("semantic_required:items")
        if len(targets) < 2:
            # Pair renderer requires at least two possible targets.
            errors.append("semantic_required:targets")

        if not errors:
            left_lookup = _lookup(left)
            target_lookup = _lookup(targets)
            mapping: Dict[str, str] = {}
            for lval, rval in relations:
                lid = left_lookup.get(_norm(_semantic_key(lval) or _label(lval)))
                tid = target_lookup.get(_norm(_semantic_key(rval) or _label(rval)))
                if not lid:
                    errors.append("semantic_relation_unknown:left")
                    continue
                if not tid:
                    errors.append("semantic_relation_unknown:right")
                    continue
                mapping[lid] = tid

            if not mapping:
                errors.append("semantic_required:pairs")
            elif set(mapping.keys()) != {_text(x.get("id")) for x in left}:
                errors.append("semantic_required:pairs_complete_coverage")
            else:
                payload_out = {
                    "left_items": copy.deepcopy(left),
                    "drag_items": copy.deepcopy(left),
                    "targets": copy.deepcopy(targets),
                    "drop_zones": copy.deepcopy(targets),
                    "mapping_answer": copy.deepcopy(mapping),
                    "correct_mapping": copy.deepcopy(mapping),
                }
                q["interaction_payload"] = payload_out
                q["correct_mapping"] = copy.deepcopy(mapping)
                q["correct_answer"] = copy.deepcopy(mapping)
                q["correct_response"] = copy.deepcopy(mapping)
                q["answer"] = copy.deepcopy(mapping)
                q["scoring_mode"] = q.get("scoring_mode") or "pair_match"
                audit["compiled_fields"].extend([
                    "interaction_payload", "correct_mapping",
                    "correct_answer", "correct_response", "answer",
                ])

    elif family == "sequence":
        if hidden_audio_sequence:
            q, sequence_errors = _compile_hidden_audio_sequence(
                q,
                src=src,
                audit=audit,
            )
            errors.extend(sequence_errors)
        else:
            semantic_items = q.get("items")
            if semantic_items in (None, "", [], {}):
                existing = _as_dict(q.get("interaction_payload"))
                semantic_items = (
                    existing.get("semantic_items")
                    or existing.get("ordering_items")
                    or q.get("correct_answer")
                    or []
                )
            records = _records(semantic_items, "item")
            if len(records) < 2:
                errors.append("semantic_required:items")
            else:
                correct_ids = [_text(x.get("id")) for x in records]
                seed = _text(
                    src.get("runtime_generation_seed")
                    or src.get("seed")
                    or _as_dict(src.get("assessment_generation_contract")).get("runtime_generation_seed")
                    or src.get("skill_id")
                    or "sequence"
                )
                display_records = _stable_shuffle(records, seed)
                q["interaction_payload"] = {
                    "ordering_items": copy.deepcopy(display_records),
                    "items": copy.deepcopy(display_records),
                    "correct_order": list(correct_ids),
                }
                q["correct_answer"] = list(correct_ids)
                q["correct_response"] = list(correct_ids)
                q["answer"] = list(correct_ids)
                audit["semantic_inputs_consumed"].append("items")
                audit["compiled_fields"].extend([
                    "interaction_payload", "correct_answer", "correct_response", "answer",
                ])

    elif family in {"single_choice", "multi_choice"}:
        opts = q.get("options")
        if opts in (None, "", [], {}):
            opts = q.get("choices")
        if isinstance(opts, dict):
            opts = list(opts.values())
        opts = list(opts) if isinstance(opts, list) else []
        if len(opts) < 2:
            errors.append("semantic_required:options")
        answer = q.get("correct_answer")
        if answer in (None, "", [], {}):
            errors.append("semantic_required:correct_answer")
        if not errors:
            q["options"] = copy.deepcopy(opts)
            q["choices"] = copy.deepcopy(opts)
            q["correct_response"] = copy.deepcopy(answer)
            q["answer"] = copy.deepcopy(answer)
            audit["compiled_fields"].extend(["options", "choices", "correct_response", "answer"])

    elif family in {"numeric", "text"}:
        answer = q.get("correct_answer")
        if answer in (None, "", [], {}):
            errors.append("semantic_required:correct_answer")
        else:
            q["correct_response"] = copy.deepcopy(answer)
            q["answer"] = copy.deepcopy(answer)
            audit["compiled_fields"].extend(["correct_response", "answer"])

    # oral/external mechanics are evaluator/tool-owned and need no fabricated answer.

    # Semantic-only transport fields never reach renderer/scoring as competing truth.
    for key in ("pairs", "items", "targets"):
        if key in q:
            q.pop(key, None)

    errors.extend(_validate_declared_visual_surface(q, response))
    if hidden_audio_sequence:
        errors.extend(_validate_hidden_audio_sequence_surface(q))
    errors = list(dict.fromkeys(errors))

    q = canonicalize_question(q)
    q["deterministic_executor_version"] = VERSION
    q["deterministic_mechanics_compiled"] = not bool(errors)
    return q, list(dict.fromkeys(errors)), audit


def summary() -> Dict[str, Any]:
    return {
        "success": True,
        "version": VERSION,
        "qwen_scope": "semantic_linguistic_content_only",
        "system_scope": "deterministic_mechanics",
        "families": [
            "single_choice", "multi_choice", "pair", "sequence",
            "numeric", "text", "oral", "external",
        ],
        "interaction_contract_version": INTERACTION_CONTRACT_VERSION,
        "zero_semantic_guess": True,
        "declared_visual_modality_guard": True,
        "written_word_label_leakage_forbidden": True,
        "student_facing_internal_ids_forbidden": True,
        "hidden_audio_sequence_from_audio_text": True,
        "hidden_audio_sequence_written_words_visible": False,
        "hidden_audio_sequence_item_media_field": "ordering_items[].audio_text",
        "pair_display_semantic_separate_from_structural_id": True,
        "clear_audio_source_descriptor": True,
    }