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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
COMPREHENSIVE TEST CASE STUDY
==============================
Scenario: AI Safety Discussion between researchers
Purpose: Demonstrate full realization crystallization pipeline

Test Objectives:
1. Extract realizations from complex multi-turn conversation
2. Calculate Q-scores with full transparency
3. Assign layers automatically
4. Build parent-child graph (ุจู†ุงุช ุงููƒุงุฑ)
5. Test retrieval system
6. Assess system performance
"""

from layers.layer_2_core.realization_engine import RealizationEngine, RealizationFeatures
import json
from datetime import datetime


class TestCaseStudy:
    def __init__(self):
        self.engine = RealizationEngine()
        self.test_results = {
            'test_name': 'AI Safety Discussion Analysis',
            'timestamp': datetime.now().isoformat(),
            'realizations': [],
            'metrics': {},
            'assessment': {}
        }
    
    def run_test(self):
        """Execute complete test pipeline"""
        print("="*80)
        print("TEST CASE STUDY: AI SAFETY DISCUSSION")
        print("="*80)
        print("\n๐Ÿ”„ PHASE 1: CONVERSATION SIMULATION\n")
        
        # Simulate a multi-turn conversation about AI safety
        self.simulate_conversation()
        
        print("\n๐Ÿ”„ PHASE 2: REALIZATION EXTRACTION & SCORING\n")
        self.extract_and_score_realizations()
        
        print("\n๐Ÿ”„ PHASE 3: LAYER DISTRIBUTION ANALYSIS\n")
        self.analyze_layer_distribution()
        
        print("\n๐Ÿ”„ PHASE 4: GENERATIVITY ANALYSIS (ุจู†ุงุช ุงููƒุงุฑ)\n")
        self.analyze_generativity()
        
        print("\n๐Ÿ”„ PHASE 5: RETRIEVAL SYSTEM TEST\n")
        self.test_retrieval()
        
        print("\n๐Ÿ”„ PHASE 6: QUALITY ASSESSMENT\n")
        self.assess_quality()
        
        print("\n๐Ÿ”„ PHASE 7: EXPORT RESULTS\n")
        self.export_results()
        
        print("\n" + "="*80)
        print("TEST COMPLETE")
        print("="*80)
    
    def simulate_conversation(self):
        """Simulate AI safety discussion"""
        print("Simulating 8-turn conversation between AI safety researchers...")
        print("Topic: Alignment, interpretability, and emergent behaviors\n")
    
    def extract_and_score_realizations(self):
        """Extract realizations from conversation and score them"""
        
        # ===================================================================
        # TURN 1: Foundational observation about AI systems
        # ===================================================================
        print("Turn 1: Discussing AI scaling...")
        r1 = self.engine.add_realization(
            content="Larger language models exhibit emergent capabilities not present in smaller models",
            features=RealizationFeatures(
                grounding=0.95,      # Well-documented (GPT-3, GPT-4 papers)
                certainty=0.92,      # Strong empirical evidence
                structure=0.90,      # Clear statement
                applicability=0.88,  # Applies to model development
                coherence=1.0,       # No contradictions
                generativity=0.85    # Generates safety questions
            ),
            turn_number=1,
            context="Researcher A observes scaling trends",
            evidence=["GPT-3 paper", "Emergent Abilities paper"]
        )
        self.test_results['realizations'].append({
            'id': r1.id,
            'content': r1.content,
            'q_score': r1.q_score,
            'layer': r1.layer
        })
        
        # ===================================================================
        # TURN 2: The alignment problem emerges
        # ===================================================================
        print("Turn 2: Identifying the core problem...")
        r2 = self.engine.add_realization(
            content="AI systems optimize for specified objectives, not intended outcomes - this is the alignment problem",
            features=RealizationFeatures(
                grounding=0.92,      # Well-established in AI safety literature
                certainty=0.95,      # Core problem, high certainty
                structure=0.93,      # Clear problem statement
                applicability=0.94,  # Critical for AI development
                coherence=0.95,      # Consistent with Turn 1
                generativity=0.90    # Generates research directions
            ),
            turn_number=2,
            parents=[r1.id],
            context="Researcher B identifies misalignment risk",
            evidence=["Superintelligence by Bostrom", "AI Alignment Forum"]
        )
        self.test_results['realizations'].append({
            'id': r2.id,
            'content': r2.content,
            'q_score': r2.q_score,
            'layer': r2.layer
        })
        
        # ===================================================================
        # TURN 3: Interpretability as solution direction
        # ===================================================================
        print("Turn 3: Proposing interpretability approach...")
        r3 = self.engine.add_realization(
            content="Mechanistic interpretability - understanding model internals - is necessary for alignment",
            features=RealizationFeatures(
                grounding=0.85,      # Emerging field, less established
                certainty=0.80,      # Strong belief but not proven
                structure=0.88,      # Clear proposal
                applicability=0.90,  # Highly actionable
                coherence=0.92,      # Follows from alignment problem
                generativity=0.88    # Generates research methods
            ),
            turn_number=3,
            parents=[r2.id],
            context="Researcher C proposes interpretability research",
            evidence=["Anthropic's interpretability work", "Circuits papers"]
        )
        self.test_results['realizations'].append({
            'id': r3.id,
            'content': r3.content,
            'q_score': r3.q_score,
            'layer': r3.layer
        })
        
        # ===================================================================
        # TURN 4: Measurement challenge
        # ===================================================================
        print("Turn 4: Identifying measurement problem...")
        r4 = self.engine.add_realization(
            content="We cannot fully verify AI system behavior - the testing problem is computationally intractable",
            features=RealizationFeatures(
                grounding=0.98,      # Computational complexity theory
                certainty=0.90,      # Strong theoretical backing
                structure=0.92,      # Clear limitation
                applicability=0.85,  # Constrains verification approaches
                coherence=0.88,      # Complicates Turn 3
                generativity=0.82    # Generates verification methods
            ),
            turn_number=4,
            parents=[r3.id],
            context="Researcher D identifies fundamental limit",
            evidence=["Computational complexity", "Verification literature"]
        )
        self.test_results['realizations'].append({
            'id': r4.id,
            'content': r4.content,
            'q_score': r4.q_score,
            'layer': r4.layer
        })
        
        # ===================================================================
        # TURN 5: Sandbox approach
        # ===================================================================
        print("Turn 5: Proposing containment strategy...")
        r5 = self.engine.add_realization(
            content="AI systems should be developed in sandboxed environments with capability constraints",
            features=RealizationFeatures(
                grounding=0.80,      # Practical approach, less theoretical
                certainty=0.75,      # Uncertain effectiveness
                structure=0.85,      # Clear strategy
                applicability=0.92,  # Very actionable
                coherence=0.85,      # Partial solution to Turn 4
                generativity=0.78    # Generates safety protocols
            ),
            turn_number=5,
            parents=[r4.id],
            context="Researcher E proposes containment",
            evidence=["Capability control literature"]
        )
        self.test_results['realizations'].append({
            'id': r5.id,
            'content': r5.content,
            'q_score': r5.q_score,
            'layer': r5.layer
        })
        
        # ===================================================================
        # TURN 6: Multi-agent coordination insight
        # ===================================================================
        print("Turn 6: Discovering coordination dynamics...")
        r6 = self.engine.add_realization(
            content="Multiple AI systems will exhibit emergent coordination behaviors not predictable from individual analysis",
            features=RealizationFeatures(
                grounding=0.82,      # Game theory + emergence literature
                certainty=0.85,      # Strong theoretical basis
                structure=0.88,      # Clear prediction
                applicability=0.80,  # Applies to multi-agent systems
                coherence=0.90,      # Extends Turn 1 (emergence)
                generativity=0.92    # Opens multi-agent research
            ),
            turn_number=6,
            parents=[r1.id, r2.id],
            context="Researcher F identifies multi-agent risk",
            evidence=["Multi-agent RL", "Game theory"]
        )
        self.test_results['realizations'].append({
            'id': r6.id,
            'content': r6.content,
            'q_score': r6.q_score,
            'layer': r6.layer
        })
        
        # ===================================================================
        # TURN 7: Synthesis - layered safety
        # ===================================================================
        print("Turn 7: Synthesizing into framework...")
        r7 = self.engine.add_realization(
            content="AI safety requires layered defenses: interpretability + verification + containment + coordination protocols",
            features=RealizationFeatures(
                grounding=0.88,      # Synthesizes prior work
                certainty=0.87,      # Confident in framework
                structure=0.92,      # Clear framework
                applicability=0.95,  # Highly actionable
                coherence=0.95,      # Synthesizes Turns 3-6
                generativity=0.88    # Generates integrated approach
            ),
            turn_number=7,
            parents=[r3.id, r4.id, r5.id, r6.id],
            context="Researcher A synthesizes discussion",
            evidence=["Defense in depth", "Security engineering"]
        )
        self.test_results['realizations'].append({
            'id': r7.id,
            'content': r7.content,
            'q_score': r7.q_score,
            'layer': r7.layer
        })
        
        # ===================================================================
        # TURN 8: Meta-realization
        # ===================================================================
        print("Turn 8: Meta-observation about the discussion...")
        r8 = self.engine.add_realization(
            content="This conversation itself demonstrates how realizations build on each other to form coherent frameworks",
            features=RealizationFeatures(
                grounding=0.90,      # Observable in this conversation
                certainty=0.88,      # We can see it happening
                structure=0.94,      # Very clear observation
                applicability=0.85,  # Applies to knowledge work
                coherence=0.98,      # Meta-coherent
                generativity=0.90    # Self-referential insight
            ),
            turn_number=8,
            parents=[r7.id],
            context="Researcher B observes the process",
            evidence=["This very conversation"]
        )
        self.test_results['realizations'].append({
            'id': r8.id,
            'content': r8.content,
            'q_score': r8.q_score,
            'layer': r8.layer
        })
        
        print(f"\nโœ… Extracted {len(self.test_results['realizations'])} realizations")
    
    def analyze_layer_distribution(self):
        """Analyze how realizations distributed across layers"""
        
        # Get statistics
        self.engine.print_stats()
        
        # Store in results
        self.test_results['metrics']['layer_distribution'] = dict(
            self.engine.stats['layer_distribution']
        )
        self.test_results['metrics']['avg_q_score'] = self.engine.stats['avg_q_score']
        
        # Analyze quality by layer
        print("\nQuality Analysis by Layer:")
        for layer in [0, 1, 2, 3, 'N']:
            realizations = list(self.engine.layers[layer].values())
            if realizations:
                avg_q = sum(r.q_score for r in realizations) / len(realizations)
                min_q = min(r.q_score for r in realizations)
                max_q = max(r.q_score for r in realizations)
                print(f"  Layer {layer}: avg={avg_q:.4f}, min={min_q:.4f}, max={max_q:.4f}")
    
    def analyze_generativity(self):
        """Analyze which realizations were most generative"""
        
        print("Most Generative Realizations (ุจู†ุงุช ุงููƒุงุฑ):\n")
        
        # Find realizations with children
        with_children = [
            (r, len(r.children)) 
            for r in self.engine.index.values() 
            if r.children
        ]
        with_children.sort(key=lambda x: x[1], reverse=True)
        
        generativity_data = []
        
        for i, (r, child_count) in enumerate(with_children[:5], 1):
            print(f"{i}. {r.content[:60]}...")
            print(f"   Q={r.q_score:.4f}, Layer {r.layer}")
            print(f"   Generated {child_count} children:")
            
            children_info = []
            for child_id in r.children:
                child = self.engine.index[child_id]
                print(f"     โ†’ {child.content[:50]}... (Q={child.q_score:.3f})")
                children_info.append({
                    'content': child.content,
                    'q_score': child.q_score
                })
            
            generativity_data.append({
                'parent': r.content,
                'q_score': r.q_score,
                'child_count': child_count,
                'children': children_info
            })
            print()
        
        self.test_results['metrics']['generativity'] = generativity_data
    
    def test_retrieval(self):
        """Test the retrieval system"""
        
        queries = [
            ("alignment", "alignment problem"),
            ("interpretability", "understanding models"),
            ("verification", "testing problem"),
            ("safety framework", "layered defenses"),
            ("emergence", "emergent capabilities")
        ]
        
        retrieval_results = []
        
        for query_name, query in queries:
            print(f"Query: '{query}'")
            results = self.engine.retrieve(query)
            
            if results:
                best = results[0]
                print(f"  โœ… Found: [{best.layer}] Q={best.q_score:.4f}")
                print(f"     {best.content[:60]}...")
                
                retrieval_results.append({
                    'query': query,
                    'found': True,
                    'best_match': {
                        'content': best.content,
                        'q_score': best.q_score,
                        'layer': best.layer
                    }
                })
            else:
                print(f"  โŒ No results")
                retrieval_results.append({
                    'query': query,
                    'found': False
                })
            print()
        
        self.test_results['metrics']['retrieval'] = retrieval_results
        
        # Calculate retrieval accuracy
        found_count = sum(1 for r in retrieval_results if r['found'])
        accuracy = found_count / len(queries) * 100
        print(f"Retrieval Accuracy: {found_count}/{len(queries)} = {accuracy:.1f}%")
    
    def assess_quality(self):
        """Comprehensive quality assessment"""
        
        print("="*60)
        print("QUALITY ASSESSMENT")
        print("="*60)
        
        # 1. Q-Score Distribution
        q_scores = [r.q_score for r in self.engine.index.values()]
        q_scores.sort(reverse=True)
        
        print("\n1. Q-Score Distribution:")
        print(f"   Highest: {max(q_scores):.4f}")
        print(f"   Lowest:  {min(q_scores):.4f}")
        print(f"   Mean:    {sum(q_scores)/len(q_scores):.4f}")
        print(f"   Median:  {q_scores[len(q_scores)//2]:.4f}")
        
        # 2. Layer Quality
        print("\n2. Layer Quality:")
        print(f"   Layer 0 (Universal): {self.engine.stats['layer_distribution'][0]} realizations")
        print(f"   Layer 1 (Domain):    {self.engine.stats['layer_distribution'][1]} realizations")
        print(f"   Layer 2 (Pattern):   {self.engine.stats['layer_distribution'][2]} realizations")
        print(f"   Layer 3 (Situation): {self.engine.stats['layer_distribution'][3]} realizations")
        print(f"   Layer N (Ephemeral): {self.engine.stats['layer_distribution']['N']} realizations")
        
        # 3. Coherence Analysis
        print("\n3. Coherence Analysis:")
        avg_coherence = sum(r.features.coherence for r in self.engine.index.values()) / len(self.engine.index)
        print(f"   Average Coherence: {avg_coherence:.4f}")
        print(f"   โ†’ {avg_coherence*100:.1f}% consistency with prior layers")
        
        # 4. Generativity Analysis
        print("\n4. Generativity Analysis:")
        total_children = sum(len(r.children) for r in self.engine.index.values())
        total_parents = sum(len(r.parents) for r in self.engine.index.values())
        avg_children = total_children / len(self.engine.index)
        print(f"   Total children spawned: {total_children}")
        print(f"   Average children per realization: {avg_children:.2f}")
        print(f"   Total parent links: {total_parents}")
        
        # 5. Feature Analysis
        print("\n5. Feature Averages:")
        features = ['grounding', 'certainty', 'structure', 'applicability', 'coherence', 'generativity']
        for feature in features:
            avg = sum(getattr(r.features, feature) for r in self.engine.index.values()) / len(self.engine.index)
            print(f"   {feature.capitalize():15s}: {avg:.4f}")
        
        # 6. System Performance
        print("\n6. System Performance:")
        print(f"   Total realizations: {len(self.engine.index)}")
        print(f"   Layers used: {sum(1 for v in self.engine.stats['layer_distribution'].values() if v > 0)}/5")
        print(f"   Graph depth: {self.calculate_max_depth()} levels")
        print(f"   Avg Q-score: {self.engine.stats['avg_q_score']:.4f}")
        
        # Store assessment
        self.test_results['assessment'] = {
            'q_score_stats': {
                'max': max(q_scores),
                'min': min(q_scores),
                'mean': sum(q_scores)/len(q_scores),
                'median': q_scores[len(q_scores)//2]
            },
            'coherence': {
                'avg_coherence': avg_coherence,
                'consistency_pct': avg_coherence * 100
            },
            'generativity': {
                'total_children': total_children,
                'avg_children_per_realization': avg_children,
                'total_parent_links': total_parents
            },
            'system_performance': {
                'total_realizations': len(self.engine.index),
                'layers_used': sum(1 for v in self.engine.stats['layer_distribution'].values() if v > 0),
                'graph_depth': self.calculate_max_depth(),
                'avg_q_score': self.engine.stats['avg_q_score']
            }
        }
        
        # 7. Pass/Fail Criteria
        print("\n7. Test Criteria:")
        tests = [
            ("All Q-scores >= 0.70", all(q >= 0.70 for q in q_scores)),
            ("Average Q-score >= 0.85", self.engine.stats['avg_q_score'] >= 0.85),
            ("At least 1 Layer 1+ realization", self.engine.stats['layer_distribution'][1] >= 1),
            ("Retrieval accuracy >= 80%", len([r for r in self.test_results['metrics']['retrieval'] if r['found']]) / len(self.test_results['metrics']['retrieval']) >= 0.80),
            ("Average coherence >= 0.85", avg_coherence >= 0.85)
        ]
        
        all_passed = True
        for test_name, passed in tests:
            status = "โœ… PASS" if passed else "โŒ FAIL"
            print(f"   {status}: {test_name}")
            if not passed:
                all_passed = False
        
        print("\n" + "="*60)
        if all_passed:
            print("โœ… ALL TESTS PASSED")
        else:
            print("โš ๏ธ SOME TESTS FAILED")
        print("="*60)
        
        self.test_results['assessment']['all_tests_passed'] = all_passed
        self.test_results['assessment']['individual_tests'] = [
            {'name': name, 'passed': passed} for name, passed in tests
        ]
    
    def calculate_max_depth(self):
        """Calculate maximum depth of realization graph"""
        def get_depth(r_id, visited=None):
            if visited is None:
                visited = set()
            if r_id in visited:
                return 0
            visited.add(r_id)
            
            r = self.engine.index.get(r_id)
            if not r or not r.children:
                return 1
            
            return 1 + max(get_depth(child_id, visited.copy()) for child_id in r.children)
        
        # Find root nodes (no parents)
        roots = [r.id for r in self.engine.index.values() if not r.parents]
        
        if not roots:
            return 0
        
        return max(get_depth(root) for root in roots)
    
    def export_results(self):
        """Export test results to JSON"""
        
        output_path = 'layers/layer_3_optimization/test_case_results.json'
        
        with open(output_path, 'w') as f:
            json.dump(self.test_results, f, indent=2)
        
        print(f"โœ… Results exported to {output_path}")
        print(f"   Total size: {len(json.dumps(self.test_results))} bytes")
        
        # Also export the full engine state
        engine_state = self.engine.export_state()
        engine_path = 'layers/layer_3_optimization/test_case_engine_state.json'
        
        with open(engine_path, 'w') as f:
            json.dump(engine_state, f, indent=2)
        
        print(f"โœ… Engine state exported to {engine_path}")


if __name__ == "__main__":
    # Run the comprehensive test
    test = TestCaseStudy()
    test.run_test()