File size: 63,708 Bytes
f3429ed
617cddd
0831f73
 
 
76e6245
1f489b4
a61d93b
2460c83
0831f73
6c26cfe
4a4fff2
 
 
 
 
6c26cfe
0831f73
a61d93b
1f489b4
dcc9c31
72d6be4
a8d33ef
1f489b4
dcc9c31
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
617cddd
 
 
 
 
 
 
 
 
f3429ed
 
 
0831f73
 
 
 
 
617cddd
 
 
 
 
 
 
 
38be297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72d6be4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2311ff9
 
 
 
 
 
 
 
 
76e6245
2311ff9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38be297
 
 
 
2311ff9
 
 
 
 
 
 
 
 
 
 
 
 
38be297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2311ff9
 
 
 
76e6245
38be297
 
2311ff9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f489b4
 
 
 
 
 
 
 
 
 
 
76e6245
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
dcc9c31
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
2311ff9
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
1f489b4
76e6245
 
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
1f489b4
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
76e6245
1f489b4
76e6245
2311ff9
 
4a4fff2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
0831f73
4a4fff2
 
0831f73
 
 
617cddd
0831f73
38be297
0831f73
 
38be297
 
 
617cddd
 
 
 
0831f73
 
617cddd
 
 
 
 
 
 
 
0831f73
 
617cddd
0831f73
a61d93b
0831f73
 
4a4fff2
617cddd
0831f73
 
4a4fff2
38be297
617cddd
 
 
 
38be297
0831f73
 
 
 
 
 
 
 
 
4a4fff2
617cddd
0831f73
 
4a4fff2
617cddd
38be297
617cddd
 
 
 
38be297
 
 
7dc6f47
0831f73
 
 
 
d28ed33
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc6f47
 
 
 
12e7005
 
 
 
38be297
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
4a4fff2
 
 
 
 
 
 
 
 
 
 
 
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4a4fff2
12e7005
 
 
 
 
 
 
 
 
d28ed33
12e7005
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
 
 
 
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
12e7005
4a4fff2
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
 
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
7dc6f47
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
12e7005
 
0831f73
 
51096c9
617cddd
12e7005
 
51096c9
0831f73
 
 
 
 
 
 
 
 
617cddd
 
38be297
 
 
 
0831f73
 
617cddd
 
 
 
 
 
0831f73
617cddd
 
 
 
 
 
0831f73
 
617cddd
0831f73
 
 
 
 
 
617cddd
 
 
38be297
 
 
 
617cddd
 
38be297
 
617cddd
 
 
0831f73
 
38be297
 
 
 
 
 
 
 
 
 
0831f73
617cddd
 
0831f73
 
 
617cddd
 
 
 
 
 
 
 
d28ed33
0831f73
617cddd
 
 
 
 
 
0831f73
 
 
 
 
76e6245
0831f73
617cddd
 
 
0831f73
 
 
6c26cfe
76e6245
6c26cfe
76e6245
 
 
6c26cfe
 
617cddd
76e6245
617cddd
 
 
 
 
 
6c26cfe
 
 
617cddd
 
 
 
6c26cfe
617cddd
76e6245
617cddd
 
76e6245
617cddd
 
 
 
6c26cfe
 
 
 
 
 
 
 
 
 
 
 
617cddd
 
6c26cfe
0831f73
 
 
 
 
 
 
 
617cddd
38be297
0831f73
 
38be297
 
 
617cddd
 
 
 
 
0831f73
 
6ce52dc
617cddd
6ce52dc
 
 
 
617cddd
6ce52dc
617cddd
 
 
 
 
 
6ce52dc
 
 
6c26cfe
 
4a4fff2
0831f73
a8d33ef
72d6be4
617cddd
0831f73
 
f3429ed
a61d93b
0831f73
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
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
# -*- coding: utf-8 -*-
"""Qualitative evidence preparation for SmartPaper's ASQ-oriented track."""

from __future__ import annotations

import hashlib
import json
import logging
import re

from config import APP_CONFIG
from core.study_design_contract import (
    STUDY_DESIGN_CONTRACT_VERSION,
    build_qualitative_contract,
    build_user_research_intent,
)


class QualitativeEngine:
    QUALITATIVE_APPENDIX_MANIFEST_VERSION = "qualitative-appendix-manifest-v1"
    TARGET_APPENDIX_BINDING_VERSION = "target-qualitative-appendix-binding-v2"
    SEMANTIC_CLAIM_FRAME_VERSION = "smartpaper-core-semantic-claim-frame-v1"
    STUDY_DESIGN_CONTRACT_VERSION = STUDY_DESIGN_CONTRACT_VERSION
    APPENDIX_FIELDS = ("theme", "concept", "stage", "case_label", "evidence_role")
    APPENDIX_CANONICAL_LABEL_FIELDS = ("theme", "concept")
    APPENDIX_HEADERS = (
        "Higher-order Theme", "Empirical Concept", "Process Stage",
        "Case/Actor", "Evidence Role", "Representative Quote",
    )
    _TARGET_APPENDIX_LOCALIZATION = {
        "en": {
            "heading": "Appendix: Data Structure and Evidence",
            "headers": APPENDIX_HEADERS,
        },
        "zh": {
            "heading": "附录:数据结构与证据",
            "headers": ("高阶主题", "经验概念", "过程阶段", "案例/参与者", "证据角色", "代表性引文"),
        },
        "ru": {
            "heading": "Приложение: Структура данных и доказательства",
            "headers": ("Тема высшего порядка", "Эмпирическое понятие", "Этап процесса", "Случай/участник", "Роль доказательства", "Репрезентативная цитата"),
        },
        "kk": {
            "heading": "Қосымша: Деректер құрылымы және дәлелдер",
            "headers": ("Жоғары деңгейлі тақырып", "Эмпирикалық ұғым", "Процесс кезеңі", "Кейс/қатысушы", "Дәлел рөлі", "Репрезентативті дәйексөз"),
        },
    }

    ALLOWED_ANALYTIC_DESIGNS = {
        "Process analysis",
        "Comparative case analysis",
        "Grounded theory",
        "Gioia-style inductive coding",
        "Longitudinal qualitative analysis",
        "Iterative thematic/process analysis",
    }

    def __init__(self, agent):
        self.agent = agent

    @staticmethod
    def _clean_cell(value, default="Not specified"):
        cleaned = str(value or default).replace("\n", " ").strip()
        return cleaned or default

    @classmethod
    def _normalize_analytic_design(cls, value):
        cleaned = re.sub(r"\s+", " ", str(value or "")).strip()
        if not cleaned:
            return "Iterative thematic/process analysis"
        lookup = {item.lower(): item for item in cls.ALLOWED_ANALYTIC_DESIGNS}
        return lookup.get(cleaned.lower(), "Iterative thematic/process analysis")

    @classmethod
    def _normalize_string_list(cls, values):
        if values is None:
            return []
        if not isinstance(values, list):
            values = [values]
        out = []
        for value in values:
            cleaned = cls._clean_cell(value, "")
            if cleaned and cleaned.casefold() != "not specified" and cleaned not in out:
                out.append(cleaned)
        return out

    @classmethod
    def _normalize_data_source_roles(cls, values):
        rows = []
        for item in values or []:
            if not isinstance(item, dict):
                continue
            actor_role = cls._clean_cell(item.get("actor_role"), "")
            data_source = cls._clean_cell(item.get("data_source"), "")
            count = item.get("count")
            if not actor_role or not data_source:
                continue
            if count is not None and (not isinstance(count, int) or count <= 0):
                continue
            row = {"actor_role": actor_role, "data_source": data_source, "count": count}
            if row not in rows:
                rows.append(row)
        return rows

    @classmethod
    def build_qualitative_semantic_claim_frame(cls, metadata):
        """Freeze actor/source, process-evidence, and quote identities in one frame.

        The frame is server-side authority.  It contains no model-inferred prose
        meaning and no verbatim quotation payload, only typed identities/hashes.
        """
        meta = dict(metadata or {})
        facts = dict(meta.get("study_facts") or {})
        relations = []
        for row in cls._normalize_data_source_roles(facts.get("data_source_roles") or []):
            actor = cls._clean_cell(row.get("actor_role"), "")
            source = cls._clean_cell(row.get("data_source"), "")
            folded = source.casefold()
            if "interview" in folded:
                family = "interview"
            elif "focus" in folded and "group" in folded:
                family = "focus_group"
            elif "observ" in folded:
                family = "observation"
            elif "log" in folded:
                family = "log"
            elif "document" in folded or "archiv" in folded or "record" in folded:
                family = "document"
            else:
                family = "other"
            relation = {
                "actor_role": actor,
                "data_source": source,
                "source_family": family,
                "count": row.get("count"),
                "relation": "EVIDENCED_BY",
            }
            relation_id_payload = json.dumps(relation, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
            relation["relation_id"] = hashlib.sha256(relation_id_payload.encode("utf-8")).hexdigest()[:16]
            relations.append(relation)

        quotes = []
        for item in meta.get("evidence") or []:
            if not isinstance(item, dict):
                continue
            quote_id = str(item.get("tag") or "").strip()
            if not re.fullmatch(r"QUOTE-\d+", quote_id):
                continue
            quote_hash = str(item.get("quote_hash") or "").strip()
            if not quote_hash and str(item.get("quote") or "").strip():
                normalized = re.sub(r"\s+", " ", str(item.get("quote") or "")).strip()
                quote_hash = hashlib.sha256(normalized.encode("utf-8")).hexdigest()
            quotes.append({
                "quote_id": quote_id,
                "quote_hash": quote_hash,
                "theme_id": str(item.get("theme_id") or "").strip(),
                "stage": cls._clean_cell(item.get("stage")),
                "case_label": cls._clean_cell(item.get("case_label")),
                "evidence_role": str(item.get("evidence_role") or "typical").strip().lower(),
            })

        process_evidence = []
        for theme in meta.get("themes") or []:
            if not isinstance(theme, dict):
                continue
            theme_id = str(theme.get("theme_id") or "").strip()
            if not theme_id:
                continue
            process_evidence.append({
                "theme_id": theme_id,
                "stages": [cls._clean_cell(x, "") for x in (theme.get("stages") or []) if cls._clean_cell(x, "")],
                "has_deviant_evidence": bool(theme.get("has_deviant_evidence")),
                "quote_ids": [
                    str(row.get("tag") or "").strip()
                    for row in (theme.get("evidence") or []) if isinstance(row, dict) and str(row.get("tag") or "").strip()
                ],
            })

        frame = {
            "version": cls.SEMANTIC_CLAIM_FRAME_VERSION,
            "mode": "qualitative",
            "actor_data_source_relations": sorted(relations, key=lambda row: (row["actor_role"].casefold(), row["data_source"].casefold())),
            "process_evidence": sorted(process_evidence, key=lambda row: row["theme_id"]),
            "quote_identities": sorted(quotes, key=lambda row: row["quote_id"]),
        }
        canonical = json.dumps(frame, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
        frame["frame_hash"] = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
        return frame

    @classmethod
    def build_scoped_evidence_md(
        cls,
        metadata,
        *,
        include_themes=True,
        theme_titles=None,
        assigned_evidence=None,
        include_quotes=False,
        include_quote_ids=True,
    ):
        """Render the minimum qualitative evidence needed by one drafting unit.

        Study facts/theme summaries are an internal empirical channel. Verbatim
        quotations are a separate channel and are exposed only to their owning
        Findings unit (or the final appendix when explicitly requested by the
        caller). This prevents a quotation visible in one unit from being
        opportunistically reused elsewhere and keeps external literature from
        becoming evidence for this study's own facts.
        """
        metadata = metadata or {}
        facts = metadata.get("study_facts") or {}
        sources = facts.get("data_sources") or ["Not specified"]
        if not isinstance(sources, list):
            sources = [sources]
        clean_sources = [cls._clean_cell(item) for item in sources]
        participants = facts.get("participant_count")
        interviews = facts.get("interview_count")
        analytic_design = cls._normalize_analytic_design(
            facts.get("analytic_design") or facts.get("analysis_method")
        )
        analytic_logic = cls._clean_cell(
            facts.get("analytic_logic"),
            "Iteratively compare empirical observations to refine a process/mechanism explanation.",
        )
        temporal_structure = cls._clean_cell(facts.get("temporal_structure"))
        case_structure = cls._clean_cell(facts.get("case_structure"))
        setting = cls._clean_cell(facts.get("research_setting"))
        data_source_roles = cls._normalize_data_source_roles(facts.get("data_source_roles") or [])
        trustworthiness = cls._normalize_string_list(facts.get("trustworthiness_procedures"))
        ethics = cls._normalize_string_list(facts.get("ethics_procedures"))
        reflexivity = cls._normalize_string_list(facts.get("reflexivity_procedures"))

        lines = [
            "### Frozen Qualitative Study Facts",
            "| Field | Frozen value |",
            "| :--- | :--- |",
            f"| Research setting | {setting} |",
            f"| Data sources | {', '.join(clean_sources)} |",
            f"| Participants | {participants if participants is not None else 'Not specified'} |",
            f"| Interviews | {interviews if interviews is not None else 'Not specified'} |",
            f"| Analytic design | {analytic_design} |",
            f"| Analytic logic | {analytic_logic} |",
            f"| Temporal structure | {temporal_structure} |",
            f"| Case structure | {case_structure} |",
            f"| Trustworthiness procedures | {'; '.join(trustworthiness) if trustworthiness else 'Not specified'} |",
            f"| Ethics procedures | {'; '.join(ethics) if ethics else 'Not specified'} |",
            f"| Reflexivity procedures | {'; '.join(reflexivity) if reflexivity else 'Not specified'} |",
        ]
        if data_source_roles:
            lines.extend([
                "",
                "### Frozen Actor / Data-Source Relations",
                "| Actor role | Data source | Count |",
                "| :--- | :--- | :--- |",
            ])
            lines.extend(
                f"| {row['actor_role']} | {row['data_source']} | {row['count'] if row['count'] is not None else 'Not specified'} |"
                for row in data_source_roles
            )
        lines.extend([
            "",
            "[QUALITATIVE EVIDENCE CHANNELS]",
            "1. STUDY FACTS and THEME SUMMARIES below are this study's internal empirical evidence. Never attach an external [CITE-XX] tag to a sentence merely because it reports or interprets these frozen facts.",
            "2. External literature may support only prior-theory, prior-evidence, or methodological-rationale claims. Keep those claims in distinct sentences from this study's setting, sample, data, events, quotations, and findings.",
            "3. ASSIGNED QUOTATIONS, when present, are analysis-only verbatim evidence owned by the current stable theme. Do not reproduce the verbatim wording or any internal quotation identifier in generated prose; the Executor renders frozen quotations deterministically after narrative QA.",
            "4. Study-owned trustworthiness, ethics, reflexivity, recruitment, consent, observation, or audit procedures may be stated as performed only when explicitly frozen above. Never convert general methodological best practice into a fact about this study.",
        ])

        allowed_theme_titles = None
        if theme_titles:
            allowed_theme_titles = {
                re.sub(r"\s+", " ", str(item or "")).strip().casefold()
                for item in theme_titles
                if str(item or "").strip()
            }

        if include_themes:
            theme_rows = []
            for theme in metadata.get("themes") or []:
                if not isinstance(theme, dict):
                    continue
                title = cls._clean_cell(theme.get("title"), "Emergent pattern")
                if allowed_theme_titles is not None and title.casefold() not in allowed_theme_titles:
                    continue
                concepts = ", ".join(
                    cls._clean_cell(item, "")
                    for item in (theme.get("concepts") or [])
                    if cls._clean_cell(item, "")
                ) or "Not specified"
                stages = ", ".join(
                    cls._clean_cell(item, "")
                    for item in (theme.get("stages") or [])
                    if cls._clean_cell(item, "") and cls._clean_cell(item, "") != "Not specified"
                ) or "Not specified"
                deviant = "yes" if theme.get("has_deviant_evidence") else "no"
                theme_rows.append((title, concepts, stages, deviant))
            if theme_rows:
                lines.extend([
                    "",
                    "### Frozen Qualitative Theme Summary",
                    "| Higher-order Theme | Empirical Concepts | Process Stages | Deviant/Boundary Evidence Present |",
                    "| :--- | :--- | :--- | :--- |",
                ])
                lines.extend(
                    f"| {title} | {concepts} | {stages} | {deviant} |"
                    for title, concepts, stages, deviant in theme_rows
                )

        if include_quotes:
            evidence_items = assigned_evidence
            if evidence_items is None:
                evidence_items = metadata.get("evidence") or []
            quote_rows = []
            for item in evidence_items or []:
                if not isinstance(item, dict):
                    continue
                tag = cls._clean_cell(item.get("tag"), "")
                quote = cls._clean_cell(item.get("quote"), "").replace('"', "'")
                if not tag or not quote:
                    continue
                stage = cls._clean_cell(item.get("stage"))
                case_label = cls._clean_cell(item.get("case_label"))
                evidence_role = str(item.get("evidence_role") or "typical").strip().lower()
                if evidence_role not in {"typical", "deviant"}:
                    evidence_role = "typical"
                quote_rows.append((tag, stage, case_label, evidence_role, quote))
            if quote_rows:
                lines.extend(["", "### Assigned Qualitative Quotations"])
                if include_quote_ids:
                    lines.extend([
                        "| Tag | Process Stage | Case/Actor | Evidence Role | Verbatim Quote |",
                        "| :--- | :--- | :--- | :--- | :--- |",
                    ])
                    lines.extend(
                        f'| {tag} | {stage} | {case_label} | {role} | "{quote}" |'
                        for tag, stage, case_label, role, quote in quote_rows
                    )
                else:
                    lines.extend([
                        "| Process Stage | Case/Actor | Evidence Role | Verbatim Quote |",
                        "| :--- | :--- | :--- | :--- |",
                    ])
                    lines.extend(
                        f'| {stage} | {case_label} | {role} | "{quote}" |'
                        for _tag, stage, case_label, role, quote in quote_rows
                    )

        return "\n".join(lines).strip()

    @staticmethod
    def _appendix_target_language_code(target_lang):
        value = str(target_lang or "").strip().casefold().replace("_", "-")
        if value.startswith("zh") or "chinese" in value or "中文" in value or "简体" in value:
            return "zh"
        if value.startswith("ru") or "russian" in value or "рус" in value:
            return "ru"
        if value.startswith("kk") or value.startswith("kz") or "kazakh" in value or "қазақ" in value:
            return "kk"
        return "en"

    @classmethod
    def build_appendix_manifest(cls, metadata):
        """Freeze Appendix row/cell identity before any target-language operation."""
        rows = []
        seen = set()
        for index, item in enumerate((metadata or {}).get("evidence") or [], start=1):
            if not isinstance(item, dict):
                continue
            quote = cls._clean_cell(item.get("quote"), "")
            if not quote:
                continue
            quote_id = str(item.get("tag") or "").strip().upper()
            if not re.fullmatch(r"QUOTE-\d+", quote_id) or quote_id in seen:
                return {}
            seen.add(quote_id)
            row = {
                "row_id": quote_id,
                "quote_id": quote_id,
                "quote_hash": hashlib.sha256(re.sub(r"\s+", " ", quote).strip().encode("utf-8")).hexdigest(),
                "theme": cls._clean_cell(item.get("theme"), "Emergent pattern"),
                "concept": cls._clean_cell(item.get("concept"), "Empirical observation"),
                "stage": cls._clean_cell(item.get("stage")),
                "case_label": cls._clean_cell(item.get("case_label")),
                "evidence_role": cls._clean_cell(
                    str(item.get("evidence_role") or "typical").strip().lower(), "typical"
                ),
                "quote": quote,
            }
            rows.append(row)
        if not rows:
            return {}
        manifest = {
            "version": cls.QUALITATIVE_APPENDIX_MANIFEST_VERSION,
            "columns": list(cls.APPENDIX_HEADERS),
            "rows": rows,
        }
        manifest["manifest_hash"] = cls.appendix_manifest_hash(manifest)
        return manifest

    @classmethod
    def appendix_manifest_hash(cls, manifest):
        record = dict(manifest or {})
        record.pop("manifest_hash", None)
        payload = json.dumps(record, ensure_ascii=False, sort_keys=True, separators=(",", ":"))
        return hashlib.sha256(payload.encode("utf-8")).hexdigest()

    @classmethod
    def appendix_translation_cells(cls, manifest):
        """Return typed non-quote Appendix cells; IDs stay server-side."""
        cells = {}
        for row in (manifest or {}).get("rows") or []:
            if not isinstance(row, dict):
                continue
            row_id = str(row.get("row_id") or "").strip()
            if not row_id:
                continue
            for field in cls.APPENDIX_FIELDS:
                value = cls._clean_cell(row.get(field), "Not specified")
                cells[f"{row_id}:{field}"] = value
        return cells

    @classmethod
    def appendix_translation_plan(cls, manifest, glossary=None):
        """Split Appendix cells into server-bound labels and model-owned surfaces.

        Theme/concept cells are frozen research labels.  When the task-level
        canonical glossary already owns their target identity, the translation
        model must not rewrite those labels or their internal anchors.  Remaining
        ordinary cells (stage/case/evidence-role) continue through the typed
        translation compiler and are rebound by server-side cell ID.
        """
        expected = cls.appendix_translation_cells(manifest)
        glossary_value = dict(glossary or {})
        folded_glossary = {
            str(key or '').strip().casefold(): str(value or '').strip()
            for key, value in glossary_value.items() if str(key or '').strip() and str(value or '').strip()
        }
        prebound = {}
        model_cells = {}
        for cell_id, source in expected.items():
            field = str(cell_id or '').rsplit(':', 1)[-1]
            canonical_target = str(glossary_value.get(source) or '').strip()
            if not canonical_target:
                canonical_target = folded_glossary.get(str(source or '').strip().casefold(), '')
            if field in cls.APPENDIX_CANONICAL_LABEL_FIELDS and canonical_target:
                prebound[cell_id] = canonical_target
            else:
                model_cells[cell_id] = source
        if set(prebound) & set(model_cells) or set(prebound) | set(model_cells) != set(expected):
            raise RuntimeError("qualitative_appendix_translation_plan_identity_mismatch")
        return prebound, model_cells

    @staticmethod
    def _escape_appendix_markdown_cell(value):
        return re.sub(r"\s+", " ", str(value or "").strip()).replace("|", r"\|")

    @classmethod
    def _validate_appendix_manifest(cls, manifest):
        record = dict(manifest or {})
        if record.get("version") != cls.QUALITATIVE_APPENDIX_MANIFEST_VERSION:
            return False
        if list(record.get("columns") or []) != list(cls.APPENDIX_HEADERS):
            return False
        rows = [row for row in (record.get("rows") or []) if isinstance(row, dict)]
        ids = [str(row.get("row_id") or "") for row in rows]
        quote_ids = [str(row.get("quote_id") or "") for row in rows]
        if not rows or len(ids) != len(set(ids)) or ids != quote_ids:
            return False
        if any(not re.fullmatch(r"QUOTE-\d+", item) for item in ids):
            return False
        expected_hash = str(record.get("manifest_hash") or "")
        return bool(expected_hash) and expected_hash == cls.appendix_manifest_hash(record)

    @classmethod
    def bind_target_language_appendix(cls, manifest, target_lang, cell_translations, quote_translations):
        """Render one six-column target Appendix from frozen semantic objects.

        Markdown structure, row identity, column identity, and quote identity are
        program-owned.  The translation model may supply only ordinary cell
        surfaces through ``cell_translations``.
        """
        if not cls._validate_appendix_manifest(manifest):
            raise RuntimeError("target_qualitative_appendix_manifest_invalid")
        expected_cells = cls.appendix_translation_cells(manifest)
        translations = dict(cell_translations or {})
        if set(translations) != set(expected_cells):
            missing = sorted(set(expected_cells) - set(translations))
            extra = sorted(set(translations) - set(expected_cells))
            raise RuntimeError(
                f"target_qualitative_appendix_cell_identity_mismatch:missing={missing[:4]} extra={extra[:4]}"
            )
        quote_map = dict(quote_translations or {})
        required_quotes = {str(row.get("quote_id") or "") for row in manifest.get("rows") or []}
        missing_quotes = sorted(tag for tag in required_quotes if not str(quote_map.get(tag) or "").strip())
        if missing_quotes:
            raise RuntimeError(f"target_qualitative_appendix_quote_identity_missing:{missing_quotes[:6]}")

        code = cls._appendix_target_language_code(target_lang)
        profile = dict(cls._TARGET_APPENDIX_LOCALIZATION.get(code) or cls._TARGET_APPENDIX_LOCALIZATION["en"])
        headers = list(profile.get("headers") or cls.APPENDIX_HEADERS)
        heading = str(profile.get("heading") or cls._TARGET_APPENDIX_LOCALIZATION["en"]["heading"])
        lines = [
            "| " + " | ".join(cls._escape_appendix_markdown_cell(item) for item in headers) + " |",
            "| :--- | :--- | :--- | :--- | :--- | :--- |",
        ]
        for row in manifest.get("rows") or []:
            row_id = str(row.get("row_id") or "")
            values = [translations[f"{row_id}:{field}"] for field in cls.APPENDIX_FIELDS]
            values.append(quote_map[str(row.get("quote_id") or "")])
            lines.append(
                "| " + " | ".join(cls._escape_appendix_markdown_cell(value) for value in values) + " |"
            )
        rendered = f"# {heading}\n\n" + "\n".join(lines)
        cls.validate_bound_target_appendix(rendered, manifest, target_lang)
        return rendered.strip()

    @classmethod
    def validate_bound_target_appendix(cls, text, manifest, target_lang):
        """Fail before DOCX packaging if semantic Appendix identity drifted."""
        if not cls._validate_appendix_manifest(manifest):
            raise RuntimeError("target_qualitative_appendix_manifest_invalid")
        code = cls._appendix_target_language_code(target_lang)
        profile = dict(cls._TARGET_APPENDIX_LOCALIZATION.get(code) or cls._TARGET_APPENDIX_LOCALIZATION["en"])
        heading = str(profile.get("heading") or "")
        headers = list(profile.get("headers") or cls.APPENDIX_HEADERS)
        value = str(text or "")
        heading_pattern = re.compile(rf"(?m)^#\s+{re.escape(heading)}\s*$")
        matches = list(heading_pattern.finditer(value))
        if len(matches) != 1:
            raise RuntimeError("target_qualitative_appendix_heading_identity_missing_or_ambiguous")
        tail = value[matches[0].end():]
        table_blocks = re.findall(r"(?m)(?:^[ \t]*\|[^\n]+\|[ \t]*$\n?)+", tail)
        valid_blocks = []
        for block in table_blocks:
            lines = [line.strip() for line in block.splitlines() if line.strip().startswith("|")]
            if not lines:
                continue
            if all(len(re.findall(r"(?<!\\)\|", line)) == 7 for line in lines):
                valid_blocks.append(lines)
        if len(valid_blocks) != 1:
            raise RuntimeError("target_qualitative_appendix_semantic_table_identity_missing_or_ambiguous")
        lines = valid_blocks[0]
        expected_rows = len(manifest.get("rows") or []) + 2
        if len(lines) != expected_rows:
            raise RuntimeError(
                f"target_qualitative_appendix_row_identity_mismatch:expected={expected_rows} got={len(lines)}"
            )
        expected_header = "| " + " | ".join(cls._escape_appendix_markdown_cell(item) for item in headers) + " |"
        if lines[0] != expected_header or not re.fullmatch(
            r"\|\s*:---\s*\|\s*:---\s*\|\s*:---\s*\|\s*:---\s*\|\s*:---\s*\|\s*:---\s*\|",
            lines[1],
        ):
            raise RuntimeError("target_qualitative_appendix_column_identity_mismatch")
        if re.search(r"\bQUOTE-\d+\b", "\n".join(lines), flags=re.I):
            raise RuntimeError("target_qualitative_appendix_internal_quote_id_leak")
        return True

    @classmethod
    def build_appendix_evidence_md(cls, metadata):
        """Render the reader-facing English Appendix from the same frozen manifest."""
        manifest = cls.build_appendix_manifest(metadata)
        if not cls._validate_appendix_manifest(manifest):
            raise RuntimeError("qualitative_appendix_manifest_invalid")
        lines = [
            "| " + " | ".join(cls.APPENDIX_HEADERS) + " |",
            "| :--- | :--- | :--- | :--- | :--- | :--- |",
        ]
        for row in manifest.get("rows") or []:
            values = [row.get(field) for field in cls.APPENDIX_FIELDS] + [f'"{row.get("quote")}"']
            lines.append(
                "| " + " | ".join(cls._escape_appendix_markdown_cell(value) for value in values) + " |"
            )
        return "\n".join(lines).strip()

    @staticmethod
    def _intent_data_source_family(value):
        folded = re.sub(r"\s+", " ", str(value or "")).strip().casefold()
        if re.search(r"interview|访谈|интервью|сұхбат", folded):
            return "interview"
        if re.search(r"focus.{0,4}(?:group|групп|топ)|焦点小组", folded):
            return "focus_group"
        if re.search(r"observ|观察|наблюден|бақылау", folded):
            return "observation"
        if re.search(r"archiv|document|档案|文档|文件|архив|документ|мұрағат|құжат", folded):
            return "document"
        if re.search(r"field.{0,4}note|田野笔记|полев.{0,6}замет|далалық.{0,6}жазб", folded):
            return "field_note"
        if re.search(r"digital.{0,4}trace|数字痕迹|цифров.{0,6}след|цифрлық.{0,6}із", folded):
            return "digital_trace"
        if re.search(r"\blog(?:s)?\b|日志|\bлог\b", folded):
            return "log"
        return "other"

    def _build_request(self, topic, keywords, raw_interviews):
        user_intent = build_user_research_intent(topic, keywords, mode="qualitative")
        intent_block = json.dumps(user_intent, ensure_ascii=False)
        schema = """Return ONLY one valid JSON object with this schema:
{
  "study_facts": {
    "research_setting": "string or Not specified",
    "data_sources": ["string"],
    "data_source_roles": [{"actor_role":"string", "data_source":"string", "count":integer or null}],
    "participant_count": integer or null,
    "interview_count": integer or null,
    "trustworthiness_procedures": ["explicitly supported/frozen procedure"],
    "ethics_procedures": ["explicitly supported/frozen procedure"],
    "reflexivity_procedures": ["explicitly supported/frozen procedure"],
    "analytic_design": "one allowed design",
    "analytic_logic": "one concise sentence",
    "temporal_structure": "string or Not specified",
    "case_structure": "string or Not specified"
  },
  "evidence": [
    {
      "theme": "higher-order pattern/theme",
      "concept": "empirical concept",
      "quote": "verbatim quotation",
      "stage": "temporal/process stage or Not specified",
      "case_label": "generic case/actor label or Not specified",
      "evidence_role": "typical or deviant"
    }
  ]
}
Allowed analytic designs: Process analysis; Comparative case analysis; Grounded theory; Gioia-style inductive coding; Longitudinal qualitative analysis; Iterative thematic/process analysis.
"""
        if raw_interviews and len(raw_interviews) > 100:
            return f"""Topic: {topic}
Keywords: {keywords}
<USER_RESEARCH_INTENT>{intent_block}</USER_RESEARCH_INTENT>
Analyze the supplied interview or field material for an ASQ-oriented qualitative manuscript.

Rules:
0. USER RESEARCH INTENT AUTHORITY: Preserve the user's research phenomenon, explicitly requested qualitative design, data-source family, temporal scope, actor/population, and context when the supplied material supports them. Never silently substitute a different method or phenomenon merely because literature or a generic template is easier. If the supplied material genuinely conflicts with the requested design, preserve evidence truth rather than inventing support; the deterministic validator will surface the conflict.
1. Treat the supplied material as the only source of study facts. Use null, empty arrays, or "Not specified" for any setting, sample, count, date, case, actor/data-source relation, trustworthiness procedure, ethics procedure, reflexivity procedure, or data source not explicitly supported by the material.
2. Extract 8-15 representative quotations VERBATIM. Never repair, paraphrase, translate, combine, or invent a quotation.
3. Choose the analytic design that best fits the actual material. Do NOT default to Gioia. Use Gioia-style coding only if the evidence structure genuinely warrants it.
4. Organize evidence around a central organizational puzzle and, when the material supports it, preserve temporal stages, actor/case contrasts, process transitions, and at least one deviant or boundary observation.
5. Do not manufacture a longitudinal sequence when the material is cross-sectional, and do not manufacture multiple cases when only one is present.
6. Freeze actor-to-data-source relations explicitly in data_source_roles whenever the material supports them (for example extension officers -> interviews; farmers -> focus groups). Never infer that an actor participated in a data source not supported by the material. The study_facts object and quotations will become the frozen single source of truth for the entire manuscript.

{schema}
<QUALITATIVE_MATERIAL>
{raw_interviews[:30000]}
</QUALITATIVE_MATERIAL>
"""

        return f"""Topic: {topic}
Keywords: {keywords}
<USER_RESEARCH_INTENT>{intent_block}</USER_RESEARCH_INTENT>
Construct one internally coherent qualitative evidence packet for a complete ASQ-oriented manuscript because no interview material was supplied.

Rules:
0. USER RESEARCH INTENT AUTHORITY: The topic/keywords define what the study is asked to investigate. If they explicitly request an analytic design (for example grounded theory, thematic analysis, comparative case, process, longitudinal, or Gioia) or a data-source family (for example interviews, focus groups, observation, documents), preserve that request in the generated evidence packet. Sparse literature is not a reason to substitute another method.
1. Choose one generic organizational research setting directly relevant to the topic and keep it fixed. Do not name a real organization, institution, or identifiable person.
2. Freeze one participant count, interview count, data-source set, actor-to-data-source relation map, analytic design, temporal/case structure, and analytic logic. Keep them internally consistent. Every actor/data-source relationship later stated in the paper must be represented in data_source_roles.
3. Produce exactly 12 natural representative quotations distributed across at least three higher-order themes. Quotations must sound like distinct participants rather than repeated template variants.
4. Choose the analytic design that best fits the constructed evidence; do NOT default to Gioia. Use process, comparative-case, grounded-theory, longitudinal, or Gioia-style logic only when the packet supports it.
5. Include at least one clearly labelled deviant/boundary observation so the eventual theory is not built only from confirming examples.
6. The evidence should support a process/mechanism explanation, not merely descriptive topic categories.
7. Freeze concise, internally coherent trustworthiness, ethics, and reflexivity procedures in their typed arrays so later Methods prose has an explicit study-owned source. Do not name a real ethics board, institution, vendor, approval number, or identifiable organization.
8. The study_facts object and evidence packet will become the frozen single source of truth for the entire manuscript.
9. Avoid decorative language, generic AI phrasing, and repetitive quotation patterns.
10. Keep the JSON compact: each representative quotation should be one concise complete sentence; keep labels short, analytic_logic to one sentence, and each procedure array to at most three concise items. Do not add explanatory prose outside the required fields.

{schema}
"""

    @staticmethod
    def _quote_has_substantive_content(value):
        """Language-aware minimum-content gate for participant quotations.

        The previous whitespace-token rule rejected ordinary Chinese sentences
        because an entire CJK sentence can contain zero spaces.  Article Agent
        supports Chinese/English/Russian/Kazakh, so accept either four or more
        whitespace-delimited tokens or a substantive CJK character sequence.
        """
        quote = re.sub(r"\s+", " ", str(value or "")).strip()
        if not quote:
            return False
        if len(quote.split()) >= 4:
            return True
        cjk_chars = re.findall(r"[\u3400-\u4dbf\u4e00-\u9fff]", quote)
        return len(cjk_chars) >= 8

    def _study_facts_validation_error(self, facts, *, has_user_data, user_intent=None):
        """Validate frozen qualitative study facts without repairing model output."""
        if not isinstance(facts, dict):
            return "invalid_study_facts_schema"
        for key in ("participant_count", "interview_count"):
            value = facts.get(key)
            if value is not None and (not isinstance(value, int) or value <= 0):
                return f"invalid_{key}"
        raw_relations = facts.get("data_source_roles") or []
        if raw_relations and not isinstance(raw_relations, list):
            return "invalid_data_source_roles"
        declared_sources = [
            re.sub(r"\s+", " ", str(item or "")).strip().casefold()
            for item in (facts.get("data_sources") or [])
            if str(item or "").strip()
        ]
        for item in raw_relations:
            if not isinstance(item, dict) or not str(item.get("actor_role") or "").strip() or not str(item.get("data_source") or "").strip():
                return "invalid_data_source_role_item"
            count = item.get("count")
            if count is not None and (not isinstance(count, int) or count <= 0):
                return "invalid_data_source_role_count"
            relation_source = re.sub(r"\s+", " ", str(item.get("data_source") or "")).strip().casefold()
            if declared_sources and not any(
                relation_source == source or relation_source in source or source in relation_source
                for source in declared_sources
            ):
                return "data_source_role_not_in_declared_sources"
        for key in ("trustworthiness_procedures", "ethics_procedures", "reflexivity_procedures"):
            value = facts.get(key) or []
            if not isinstance(value, list):
                return f"invalid_{key}"
            if any(not str(item or "").strip() for item in value):
                return f"invalid_{key}"
        if not has_user_data:
            if not raw_relations:
                return "generated_packet_missing_data_source_roles"
            for key in ("trustworthiness_procedures", "ethics_procedures", "reflexivity_procedures"):
                if not (facts.get(key) or []):
                    return f"generated_packet_missing_{key}"

        intent = dict(user_intent or {})
        requested_design = str(intent.get("qualitative_design") or "").strip()
        if requested_design:
            observed_design = self._normalize_analytic_design(facts.get("analytic_design") or facts.get("analysis_method"))
            if observed_design.casefold() != requested_design.casefold():
                return f"user_intent_analytic_design_mismatch:{observed_design}->{requested_design}"
        requested_sources = set(intent.get("qualitative_data_source_families") or [])
        if requested_sources:
            observed_sources = {self._intent_data_source_family(item) for item in (facts.get("data_sources") or [])}
            missing_sources = sorted(requested_sources - observed_sources)
            if missing_sources:
                return "user_intent_data_source_mismatch:" + ",".join(missing_sources)
        return ""

    def _qualitative_packet_validation_error(self, data, *, has_user_data, user_intent=None):
        """Return a bounded local validation reason, or an empty string when safe.

        The validator never repairs JSON, invents quotations, or mutates model
        output.  A completed but unsafe response is discarded and, when
        appropriate, regenerated through smaller structured stages.
        """
        if not isinstance(data, dict):
            return "packet_not_json_object"

        facts = data.get("study_facts") or {}
        evidence = data.get("evidence") or data.get("quotes") or []
        if not isinstance(facts, dict) or not isinstance(evidence, list):
            return "invalid_packet_schema"

        facts_reason = self._study_facts_validation_error(
            facts,
            has_user_data=has_user_data,
            user_intent=user_intent,
        )
        if facts_reason:
            return facts_reason

        seen_quotes = set()
        theme_keys = set()
        retained = 0
        has_deviant = False
        for item in evidence[:15]:
            if not isinstance(item, dict):
                continue
            quote = self._clean_cell(item.get("quote"), "").replace('"', "'")
            normalized_quote = re.sub(r"\s+", " ", quote).strip().casefold()
            if not self._quote_has_substantive_content(quote) or normalized_quote in seen_quotes:
                continue
            seen_quotes.add(normalized_quote)
            retained += 1
            theme = self._clean_cell(item.get("theme"), "Emergent pattern")
            theme_keys.add(re.sub(r"\s+", " ", theme).strip().casefold())
            if str(item.get("evidence_role") or "typical").strip().lower() == "deviant":
                has_deviant = True

        validation = APP_CONFIG.get("manuscript_validation", {})
        minimum_themes = int(validation.get("minimum_qualitative_themes", 3))
        minimum_quotes = int(validation.get("minimum_qualitative_quotes", 8))
        if len(theme_keys) < minimum_themes or retained < minimum_quotes:
            return f"incomplete_packet_themes_{len(theme_keys)}_quotes_{retained}"
        if not has_user_data and not has_deviant:
            return "generated_packet_missing_deviant_evidence"
        return ""

    @staticmethod
    def _theme_plan_validation_error(value):
        if not isinstance(value, list):
            return "invalid_theme_plan"
        cleaned = [re.sub(r"\s+", " ", str(item or "")).strip() for item in value]
        cleaned = [item for item in cleaned if item]
        unique = {item.casefold() for item in cleaned}
        if len(unique) < 3:
            return "incomplete_theme_plan"
        return ""

    def _call_qualitative_json(self, system_prompt, prompt, *, max_tokens):
        """Make one bounded structured call and parse it strictly; never repair JSON."""
        response = self.agent.call_deepseek(
            system_prompt,
            prompt,
            max_tokens=max_tokens,
            temp=0.0,
            model_role="reasoning",
            thinking=False,
            allow_fallback=False,
            response_format={"type": "json_object"},
            logical_node="structured_json",
        )
        response = re.sub(
            r"<think>.*?</think>",
            "",
            str(response or ""),
            flags=re.DOTALL,
        ).strip()
        return self.agent._extract_json_from_text(response)

    def _build_study_facts_stage_request(self, topic, keywords, raw_interviews, user_intent):
        intent_block = json.dumps(user_intent, ensure_ascii=False)
        facts_schema = """Return ONLY one valid JSON object with this schema:
{
  "study_facts": {
    "research_setting": "string or Not specified",
    "data_sources": ["string"],
    "data_source_roles": [{"actor_role":"string", "data_source":"string", "count":integer or null}],
    "participant_count": integer or null,
    "interview_count": integer or null,
    "trustworthiness_procedures": ["concise procedure"],
    "ethics_procedures": ["concise procedure"],
    "reflexivity_procedures": ["concise procedure"],
    "analytic_design": "one allowed design",
    "analytic_logic": "one concise sentence",
    "temporal_structure": "string or Not specified",
    "case_structure": "string or Not specified"
  },
  "theme_plan": ["concise theme 1", "concise theme 2", "concise theme 3"]
}
Allowed analytic designs: Process analysis; Comparative case analysis; Grounded theory; Gioia-style inductive coding; Longitudinal qualitative analysis; Iterative thematic/process analysis.
"""
        if raw_interviews and len(raw_interviews) > 100:
            material_block = f"""Use ONLY the supplied qualitative material as the source of study facts. Use null, empty arrays, or \"Not specified\" when the material does not support a fact. Preserve the user's requested design/data-source family only when evidence truth permits it. Do not invent actors, counts, procedures, cases, dates, or settings. The theme_plan must contain at least three concise evidence-grounded higher-order themes and must not contain quotations.

<QUALITATIVE_MATERIAL>
{raw_interviews[:30000]}
</QUALITATIVE_MATERIAL>"""
        else:
            material_block = """No interview material was supplied. Construct one generic, internally coherent organizational qualitative study directly relevant to the topic. Do not name a real organization or identifiable person. Freeze one coherent setting, sample/data-source structure, analytic design, procedures, temporal/case structure, and at least three concise higher-order themes. Keep every field compact."""
        return f"""Topic: {topic}
Keywords: {keywords}
<USER_RESEARCH_INTENT>{intent_block}</USER_RESEARCH_INTENT>

This is FALLBACK STAGE A. Produce STUDY FACTS and a compact THEME PLAN only. Do not produce quotations or an evidence array.

{material_block}

{facts_schema}
"""

    def _build_evidence_stage_request(
        self,
        topic,
        keywords,
        raw_interviews,
        user_intent,
        *,
        facts,
        theme_plan,
        prior_reason="",
    ):
        intent_block = json.dumps(user_intent, ensure_ascii=False)
        facts_block = json.dumps(facts, ensure_ascii=False, separators=(",", ":"))
        themes_block = json.dumps(theme_plan, ensure_ascii=False)
        retry_note = (
            f"\nThe previous completed Stage B response failed deterministic validation with reason={prior_reason}. "
            "Generate a fresh evidence object from the same frozen facts and original inputs; do not repair or continue the previous response."
            if prior_reason
            else ""
        )
        if raw_interviews and len(raw_interviews) > 100:
            evidence_rules = f"""Use ONLY the supplied qualitative material. Return 8-12 representative quotations VERBATIM; never repair, paraphrase, translate, combine, or invent a quotation. Use at least three themes from the frozen theme plan when supported. Preserve stage/case labels only when supported by the material.

<QUALITATIVE_MATERIAL>
{raw_interviews[:30000]}
</QUALITATIVE_MATERIAL>"""
        else:
            evidence_rules = """Generate exactly 12 concise natural representative quotations distributed across at least three themes from the frozen theme plan. Quotations must sound like distinct participants, each should be one concise complete sentence, and at least one evidence item must be clearly labelled deviant. Do not change or contradict any frozen study fact."""
        return f"""Topic: {topic}
Keywords: {keywords}
<USER_RESEARCH_INTENT>{intent_block}</USER_RESEARCH_INTENT>

This is FALLBACK STAGE B. The study facts below are frozen authority and MUST NOT be changed.
<FROZEN_STUDY_FACTS>{facts_block}</FROZEN_STUDY_FACTS>
<FROZEN_THEME_PLAN>{themes_block}</FROZEN_THEME_PLAN>

{evidence_rules}
{retry_note}

Return ONLY one valid JSON object with this schema:
{{
  "evidence": [
    {{
      "theme": "one frozen theme",
      "concept": "concise empirical concept",
      "quote": "representative quotation",
      "stage": "temporal/process stage or Not specified",
      "case_label": "generic case/actor label or Not specified",
      "evidence_role": "typical or deviant"
    }}
  ]
}}
No Markdown and no explanatory prose.
"""

    def _generate_staged_qualitative_packet(
        self,
        topic,
        keywords,
        raw_interviews,
        *,
        has_user_data,
        user_intent,
        trigger_reason,
    ):
        """Bounded small-JSON fallback after a completed unsafe full packet."""
        system_prompt = (
            "You are a rigorous qualitative research analyst. "
            "Evidence fidelity has priority over narrative completeness."
        )
        facts_data = None
        facts = None
        theme_plan = None
        facts_reason = "packet_not_json_object"
        facts_prompt = self._build_study_facts_stage_request(
            topic, keywords, raw_interviews, user_intent
        )
        for attempt in range(2):
            prompt = facts_prompt
            if attempt:
                prompt += (
                    "\n\nLOCAL STAGE-A RETRY: The previous completed response failed deterministic "
                    f"validation with reason={facts_reason}. Generate a fresh complete Stage A JSON object "
                    "from the ORIGINAL inputs. Do not repair or continue the previous response."
                )
            facts_data = self._call_qualitative_json(
                system_prompt,
                prompt,
                max_tokens=2600,
            )
            if not isinstance(facts_data, dict):
                facts_reason = "packet_not_json_object"
                continue
            facts = facts_data.get("study_facts")
            theme_plan = facts_data.get("theme_plan")
            facts_reason = self._study_facts_validation_error(
                facts,
                has_user_data=has_user_data,
                user_intent=user_intent,
            ) or self._theme_plan_validation_error(theme_plan)
            if not facts_reason:
                break
            logging.warning(
                "Qualitative staged fallback facts retry | attempt=%s/2 | trigger=%s | reason=%s",
                attempt + 1,
                trigger_reason,
                facts_reason,
            )
        if facts_reason:
            raise RuntimeError(
                "Qualitative evidence facts fallback failed deterministic validation: "
                f"{facts_reason}."
            )

        evidence_reason = "packet_not_json_object"
        for attempt in range(2):
            evidence_prompt = self._build_evidence_stage_request(
                topic,
                keywords,
                raw_interviews,
                user_intent,
                facts=facts,
                theme_plan=theme_plan,
                prior_reason=evidence_reason if attempt else "",
            )
            evidence_data = self._call_qualitative_json(
                system_prompt,
                evidence_prompt,
                max_tokens=4600,
            )
            evidence = evidence_data.get("evidence") if isinstance(evidence_data, dict) else None
            merged = {"study_facts": facts, "evidence": evidence}
            evidence_reason = self._qualitative_packet_validation_error(
                merged,
                has_user_data=has_user_data,
                user_intent=user_intent,
            )
            if not evidence_reason:
                return merged
            logging.warning(
                "Qualitative staged fallback evidence retry | attempt=%s/2 | trigger=%s | reason=%s",
                attempt + 1,
                trigger_reason,
                evidence_reason,
            )
        raise RuntimeError(
            "Qualitative evidence fallback failed deterministic validation after bounded regeneration: "
            f"{evidence_reason}."
        )

    def _generate_qualitative_packet(self, topic, keywords, raw_interviews, *, has_user_data):
        """Generate one compact packet, then fall back to bounded smaller JSON stages."""
        system_prompt = (
            "You are a rigorous qualitative research analyst. "
            "Evidence fidelity has priority over narrative completeness."
        )
        user_intent = build_user_research_intent(topic, keywords, mode="qualitative")
        base_prompt = self._build_request(topic, keywords, raw_interviews)
        data = self._call_qualitative_json(
            system_prompt + "\n\nDIRECT OUTPUT MODE: Produce the complete compact evidence packet directly without extended hidden reasoning.",
            base_prompt,
            max_tokens=8000,
        )
        reason = self._qualitative_packet_validation_error(
            data,
            has_user_data=has_user_data,
            user_intent=user_intent,
        )
        if not reason:
            return data

        logging.warning(
            "Qualitative evidence full packet unsafe; entering staged fallback | reason=%s",
            reason,
        )
        return self._generate_staged_qualitative_packet(
            topic,
            keywords,
            raw_interviews,
            has_user_data=has_user_data,
            user_intent=user_intent,
            trigger_reason=reason,
        )

    def resolve_qualitative_data(self, topic, keywords, raw_interviews=""):
        has_user_data = bool(raw_interviews and len(raw_interviews) > 100)
        # R3-Free engine code is headless. Streamlit rendering belongs to app.py;
        # this method only produces frozen evidence + metadata.
        data = self._generate_qualitative_packet(
            topic, keywords, raw_interviews, has_user_data=has_user_data
        )

        facts = data.get("study_facts") or {}
        evidence = data.get("evidence") or data.get("quotes") or []

        data_sources = facts.get("data_sources") or ["Not specified"]
        if not isinstance(data_sources, list):
            data_sources = [data_sources]

        setting = self._clean_cell(facts.get("research_setting"))
        clean_sources = [self._clean_cell(item) for item in data_sources]
        sources = ", ".join(clean_sources)
        data_source_roles = self._normalize_data_source_roles(facts.get("data_source_roles") or [])
        trustworthiness = self._normalize_string_list(facts.get("trustworthiness_procedures"))
        ethics = self._normalize_string_list(facts.get("ethics_procedures"))
        reflexivity = self._normalize_string_list(facts.get("reflexivity_procedures"))
        participants = facts.get("participant_count")
        interviews = facts.get("interview_count")
        analytic_design = self._normalize_analytic_design(
            facts.get("analytic_design") or facts.get("analysis_method")
        )
        analytic_logic = self._clean_cell(
            facts.get("analytic_logic"),
            "Iteratively compare empirical observations to refine a process/mechanism explanation.",
        )
        temporal_structure = self._clean_cell(facts.get("temporal_structure"))
        case_structure = self._clean_cell(facts.get("case_structure"))

        for value, label in ((participants, "participant_count"), (interviews, "interview_count")):
            if value is not None and (not isinstance(value, int) or value <= 0):
                raise RuntimeError(f"Qualitative evidence packet has invalid {label}.")

        md = (
            "### Frozen Qualitative Study Design\n"
            "| Field | Frozen value |\n"
            "| :--- | :--- |\n"
            f"| Research setting | {setting} |\n"
            f"| Data sources | {sources} |\n"
            f"| Participants | {participants if participants is not None else 'Not specified'} |\n"
            f"| Interviews | {interviews if interviews is not None else 'Not specified'} |\n"
            f"| Analytic design | {analytic_design} |\n"
            f"| Analytic logic | {analytic_logic} |\n"
            f"| Temporal structure | {temporal_structure} |\n"
            f"| Case structure | {case_structure} |\n"
            f"| Trustworthiness procedures | {'; '.join(trustworthiness) if trustworthiness else 'Not specified'} |\n"
            f"| Ethics procedures | {'; '.join(ethics) if ethics else 'Not specified'} |\n"
            f"| Reflexivity procedures | {'; '.join(reflexivity) if reflexivity else 'Not specified'} |\n\n"
            "[QUALITATIVE EVIDENCE CONTRACT]\n"
            "Use the frozen design summary and tagged evidence below as the only source of this study's empirical facts. "
            "Do not change the setting, sample, interview count, data sources, actor/data-source relations, analytic design, temporal structure, cases, procedures, or quotations. "
            "Do not infer an event sequence, actor comparison, trustworthiness/ethics/reflexivity procedure, negative case, or quotation that is absent from this packet.\n\n"
            "### Table: Qualitative Evidence Structure\n"
            "| Higher-order Theme | Empirical Concept | Process Stage | Case/Actor | Evidence Role | Representative Quote |\n"
            "| :--- | :--- | :--- | :--- | :--- | :--- |\n"
        )

        if data_source_roles:
            md += (
                "### Frozen Actor / Data-Source Relations\n"
                "| Actor role | Data source | Count |\n"
                "| :--- | :--- | :--- |\n"
            )
            for row in data_source_roles:
                md += f"| {row['actor_role']} | {row['data_source']} | {row['count'] if row['count'] is not None else 'Not specified'} |\n"
            md += "\n"

        clean_evidence = []
        seen_quotes = set()
        for item in evidence[:15]:
            if not isinstance(item, dict):
                continue
            quote = self._clean_cell(item.get("quote"), "").replace('"', "'")
            concept = self._clean_cell(item.get("concept"), "Empirical observation")
            theme = self._clean_cell(item.get("theme"), "Emergent pattern")
            stage = self._clean_cell(item.get("stage"))
            case_label = self._clean_cell(item.get("case_label"))
            evidence_role = str(item.get("evidence_role") or "typical").strip().lower()
            if evidence_role not in {"typical", "deviant"}:
                evidence_role = "typical"
            normalized_quote = re.sub(r"\s+", " ", quote).strip().lower()
            if not self._quote_has_substantive_content(quote) or normalized_quote in seen_quotes:
                continue
            seen_quotes.add(normalized_quote)
            tag = f"QUOTE-{len(clean_evidence) + 1:02d}"
            md += (
                f'| {theme} | {concept} | {stage} | {case_label} | {evidence_role} | '
                f'"{quote}" [{tag}] |\n'
            )
            clean_evidence.append(
                {
                    "theme": theme,
                    "concept": concept,
                    "quote": quote,
                    "quote_hash": hashlib.sha256(re.sub(r"\s+", " ", quote).strip().encode("utf-8")).hexdigest(),
                    "tag": tag,
                    "stage": stage,
                    "case_label": case_label,
                    "evidence_role": evidence_role,
                }
            )

        theme_map = {}
        theme_ids = {}
        for item in clean_evidence:
            theme_key = re.sub(r"\s+", " ", item["theme"]).strip().casefold()
            theme_id = theme_ids.setdefault(theme_key, f"THEME-{len(theme_ids) + 1:02d}")
            item["theme_id"] = theme_id
            theme_entry = theme_map.setdefault(
                item["theme"],
                {
                    "theme_id": theme_id,
                    "title": item["theme"],
                    "concepts": [],
                    "evidence": [],
                    "stages": [],
                    "has_deviant_evidence": False,
                },
            )
            if item["concept"] not in theme_entry["concepts"]:
                theme_entry["concepts"].append(item["concept"])
            if item["stage"] != "Not specified" and item["stage"] not in theme_entry["stages"]:
                theme_entry["stages"].append(item["stage"])
            if item["evidence_role"] == "deviant":
                theme_entry["has_deviant_evidence"] = True
            theme_entry["evidence"].append(
                {
                    "theme_id": item["theme_id"],
                    "tag": item["tag"],
                    "quote": item["quote"],
                    "quote_hash": item["quote_hash"],
                    "stage": item["stage"],
                    "case_label": item["case_label"],
                    "evidence_role": item["evidence_role"],
                }
            )

        themes = list(theme_map.values())
        validation = APP_CONFIG.get("manuscript_validation", {})
        minimum_themes = int(validation.get("minimum_qualitative_themes", 3))
        minimum_quotes = int(validation.get("minimum_qualitative_quotes", 8))
        if len(themes) < minimum_themes or len(clean_evidence) < minimum_quotes:
            raise RuntimeError(
                "Qualitative evidence packet is incomplete: "
                f"themes={len(themes)}, quotes={len(clean_evidence)}; "
                f"required themes>={minimum_themes}, quotes>={minimum_quotes}."
            )
        if not has_user_data and not any(item["evidence_role"] == "deviant" for item in clean_evidence):
            raise RuntimeError("Generated qualitative evidence packet lacks a deviant/boundary observation.")

        metadata = {
            "mode": "qualitative",
            "source_type": (
                "user_provided" if has_user_data else "system_generated"
            ),
            "disclosure_required": not has_user_data,
            "study_facts": {
                "research_setting": setting,
                "data_sources": clean_sources,
                "data_source_roles": data_source_roles,
                "participant_count": participants,
                "interview_count": interviews,
                "trustworthiness_procedures": trustworthiness,
                "ethics_procedures": ethics,
                "reflexivity_procedures": reflexivity,
                "analytic_design": analytic_design,
                "analysis_method": analytic_design,
                "analytic_logic": analytic_logic,
                "temporal_structure": temporal_structure,
                "case_structure": case_structure,
            },
            "evidence_count": len(clean_evidence),
            "generation_parameters": {
                "analytic_design": analytic_design,
                "requested_quote_count_when_generated": 12,
                "maximum_retained_quotes": 15,
                "minimum_themes": minimum_themes,
                "minimum_quotes": minimum_quotes,
                "requires_generated_deviant_evidence": not has_user_data,
                "consistency_constraints": [
                    "one frozen research setting",
                    "one frozen participant count",
                    "one frozen interview count",
                    "one frozen data-source set",
                    "one frozen analytic design",
                    "no unsupported temporal or case structure",
                    "quotation tags must remain unique",
                ],
            },
            "evidence": clean_evidence,
            "themes": themes,
            "user_research_intent": build_user_research_intent(topic, keywords, mode="qualitative"),
        }
        metadata["study_design_contract"] = build_qualitative_contract(topic, keywords, metadata)
        metadata["semantic_claim_frame"] = self.build_qualitative_semantic_claim_frame(metadata)
        status_message = "✅ 定性研究事实、分析设计与证据结构已冻结。"
        return md, status_message, metadata


def get_qualitative_engine(agent):
    return QualitativeEngine(agent)