File size: 8,012 Bytes
6d3aa82
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
LOGOS Dissolution Engine (Protocol 38)
The "Gemma" Processor - Automatic Type Detection & Routing

Philosophy: "Computing a value IS routing it"
- Uses GCD (AND gate) to detect data type factors
- Uses NOT gate to steer to appropriate processors
- Multi-casts to all matching processors based on prime factors

Genesis Data Types (Material Definitions):
- [17] = IMAGE (Visual Data)
- [19] = TEXT (Linguistic Data)
- [23] = AUDIO (Acoustic Data)
- [29] = SIGNAL (Raw Data/Sensor)
- [7]  = PERSIST (Storage Flag)
"""

from logos.mtl.interpreter import MTLInterpreter
import math
import os


class DissolutionEngine:
    """
    The Factory that dissolves raw atoms and routes them to processors.
    """
    
    # Domain Endpoints (Processing Destinations)
    VISUAL_CORTEX = 17 * 100  # [1700] - Image Processing Domain
    TEXT_ENGINE = 19 * 100    # [1900] - Language Processing Domain  
    AUDIO_CORTEX = 23 * 100   # [2300] - Audio Processing Domain
    DEEP_STORAGE = 42         # [42] - Persistent Storage
    SIGNAL_BUS = 29 * 10      # [290] - Raw Signal Processing
    
    # Type Primes (From Genesis Block)
    TYPE_PRIMES = {
        17: 'IMAGE',
        19: 'TEXT', 
        23: 'AUDIO',
        29: 'SIGNAL',
        7: 'PERSIST'
    }
    
    def __init__(self):
        genesis_path = os.path.join(os.path.dirname(__file__), '..', 'mtl', 'genesis.json')
        self.mtl = MTLInterpreter(genesis_path)
        self.routing_log = []
        
    def detect_types(self, atom: int) -> dict:
        """
        Uses GCD (AND gate) to detect which type factors are present.
        Returns dict of detected types with boolean flags.
        """
        detected = {}
        for prime, type_name in self.TYPE_PRIMES.items():
            # GCD reveals if this prime is a factor
            gcd_result = math.gcd(atom, prime)
            detected[type_name] = (gcd_result == prime)
        return detected
    
    def dissolve_and_route(self, atom: int, source: str = "UNKNOWN") -> dict:
        """
        The Core Dissolution Protocol:
        1. Analyze atom factors via GCD
        2. Route to all matching processors
        3. Apply persistence if flagged
        """
        print(f"\nπŸ”¬ [DISSOLUTION] Processing Atom: {atom} (Source: {source})")
        print(f"   Prime Factors: {self._factorize(atom)}")
        
        # 1. DETECT TYPES
        types = self.detect_types(atom)
        active_types = [t for t, v in types.items() if v]
        print(f"   Detected Types: {active_types if active_types else ['GENERIC']}")
        
        routes = []
        
        # 2. MULTI-CAST ROUTING (Using NOT gate logic)
        
        # Visual Data β†’ Visual Cortex
        if types['IMAGE']:
            self.mtl.execute(f'(domain [{self.VISUAL_CORTEX}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('VISUAL_CORTEX', self.VISUAL_CORTEX))
            print(f"   πŸ“· Routed to VISUAL_CORTEX [{self.VISUAL_CORTEX}]")
        
        # Text Data β†’ Text Engine
        if types['TEXT']:
            self.mtl.execute(f'(domain [{self.TEXT_ENGINE}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('TEXT_ENGINE', self.TEXT_ENGINE))
            print(f"   πŸ“ Routed to TEXT_ENGINE [{self.TEXT_ENGINE}]")
        
        # Audio Data β†’ Audio Cortex
        if types['AUDIO']:
            self.mtl.execute(f'(domain [{self.AUDIO_CORTEX}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('AUDIO_CORTEX', self.AUDIO_CORTEX))
            print(f"   πŸ”Š Routed to AUDIO_CORTEX [{self.AUDIO_CORTEX}]")
        
        # Signal Data β†’ Signal Bus
        if types['SIGNAL']:
            self.mtl.execute(f'(domain [{self.SIGNAL_BUS}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('SIGNAL_BUS', self.SIGNAL_BUS))
            print(f"   πŸ“‘ Routed to SIGNAL_BUS [{self.SIGNAL_BUS}]")
        
        # 3. PERSISTENCE CHECK
        if types['PERSIST']:
            self.mtl.execute(f'(domain [{self.DEEP_STORAGE}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('DEEP_STORAGE', self.DEEP_STORAGE))
            print(f"   πŸ’Ύ Burned to DEEP_STORAGE [{self.DEEP_STORAGE}]")
        
        # 4. Generic fallthrough (no type detected)
        if not active_types:
            # Route to origin * 10 as generic holding
            generic_domain = (atom % 100) * 10 or 100
            self.mtl.execute(f'(domain [{generic_domain}])')
            self.mtl.execute(f'(store atom_{atom} {atom})')
            routes.append(('GENERIC', generic_domain))
            print(f"   πŸ“¦ Routed to GENERIC [{generic_domain}]")
        
        # Log the routing
        log_entry = {
            'atom': atom,
            'source': source,
            'types': active_types,
            'routes': routes,
            'factors': self._factorize(atom)
        }
        self.routing_log.append(log_entry)
        
        return log_entry
    
    def _factorize(self, n: int) -> list:
        """Return prime factors of n."""
        if n <= 1:
            return [n]
        factors = []
        d = 2
        temp = n
        while d * d <= temp:
            while temp % d == 0:
                factors.append(d)
                temp //= d
            d += 1
        if temp > 1:
            factors.append(temp)
        return factors
    
    def encode_file_type(self, extension: str) -> int:
        """
        Encodes a file extension to its LOGOS atom.
        Returns the product of relevant type primes.
        """
        ext_map = {
            # Image types
            '.jpg': 17, '.jpeg': 17, '.png': 17, '.gif': 17, '.webp': 17, '.bmp': 17,
            # Text types
            '.txt': 19, '.md': 19, '.json': 19, '.xml': 19, '.csv': 19,
            # Code (Text + Mechanism)
            '.py': 19 * 2, '.js': 19 * 2, '.ts': 19 * 2, '.html': 19 * 2,
            # Audio types
            '.mp3': 23, '.wav': 23, '.ogg': 23, '.flac': 23,
            # Video (Image + Audio + Mechanism)
            '.mp4': 17 * 23 * 2, '.webm': 17 * 23 * 2, '.mkv': 17 * 23 * 2,
            # Documents (Text + Image)
            '.pdf': 17 * 19, '.docx': 17 * 19,
            # Data (Signal)
            '.bin': 29, '.dat': 29,
        }
        return ext_map.get(extension.lower(), 29)  # Default to SIGNAL
    
    def dissolve_file(self, filepath: str) -> dict:
        """
        Dissolves a file by encoding its type and routing.
        """
        import os
        _, ext = os.path.splitext(filepath)
        atom = self.encode_file_type(ext)
        return self.dissolve_and_route(atom, source=filepath)
    
    def get_domain_map(self) -> dict:
        """Returns all populated domains."""
        return {k: v for k, v in self.mtl.domains.items() if v}


# === STANDALONE TEST ===
if __name__ == "__main__":
    print("=" * 60)
    print("   LOGOS DISSOLUTION ENGINE TEST")
    print("=" * 60)
    
    engine = DissolutionEngine()
    
    # Test 1: Pure Image Atom [17]
    engine.dissolve_and_route(17, source="pure_image.jpg")
    
    # Test 2: Pure Text Atom [19]
    engine.dissolve_and_route(19, source="pure_text.txt")
    
    # Test 3: Composite: Visual Text [323 = 17 * 19] (e.g., PDF)
    engine.dissolve_and_route(323, source="document.pdf")
    
    # Test 4: Video [782 = 17 * 23 * 2] (Image + Audio + Mechanism)
    engine.dissolve_and_route(17 * 23 * 2, source="video.mp4")
    
    # Test 5: Persistent Text [133 = 7 * 19]
    engine.dissolve_and_route(7 * 19, source="saved_note.txt")
    
    # Test 6: Unknown/Generic
    engine.dissolve_and_route(101, source="unknown.dat")
    
    # Summary
    print("\n" + "=" * 60)
    print("   DOMAIN MAP (After Dissolution)")
    print("=" * 60)
    for domain, contents in engine.get_domain_map().items():
        print(f"   [{domain:5d}] {contents}")
    
    print("\nβœ… DISSOLUTION ENGINE OPERATIONAL")