Spaces:
Runtime error
Runtime error
File size: 8,733 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 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
"""
LOGOS Harmonizer (Protocol 42)
The Immune System - Resonance-Based Noise Filtering
Philosophy: "Don't detect what's bad; only accept what matches the geometry."
Standard OS: Needs antivirus database to know what is "bad"
LOGOS: Accepts only what matches the Prime Modulo of the domain
Rule: If you are in Domain [P], you must be divisible by P.
Attack: Corrupted atom with wrong heat is arithmetically rejected.
Defense: heat % domain_prime != 0 -> REJECT
"""
from dataclasses import dataclass
from typing import List, Tuple, Dict
from logos.mtl.interpreter import MTLInterpreter
@dataclass
class Atom:
"""Minimal atom structure for harmonization testing."""
id: int
heat: int
payload: bytes
@property
def is_valid(self) -> bool:
return self.heat > 0
class Harmonizer:
"""
The SPCW Resonance Filter.
Filters atom streams based on prime domain membership.
"""
def __init__(self):
self.mtl = MTLInterpreter()
self.rejection_log = []
def filter_stream(self,
stream: List[Atom],
domain_prime: int,
verbose: bool = True) -> Tuple[List[Atom], List[Atom]]:
"""
Filter a stream of atoms for domain resonance.
Args:
stream: List of atoms to filter
domain_prime: The prime that defines the domain
verbose: Print filtering details
Returns:
Tuple of (resonant_atoms, dissonant_atoms)
"""
resonant = []
dissonant = []
if verbose:
print(f"\n[HARMONIZER] Filtering for Domain [{domain_prime}]...")
for atom in stream:
# The Core Test: Does this atom resonate with the domain?
if atom.heat % domain_prime == 0:
resonant.append(atom)
if verbose:
print(f" Atom {atom.id} (heat={atom.heat}) -> [OK] RESONANT")
else:
dissonant.append(atom)
self.rejection_log.append({
'atom_id': atom.id,
'heat': atom.heat,
'domain': domain_prime,
'remainder': atom.heat % domain_prime,
'reason': 'DISSONANCE'
})
if verbose:
print(f" Atom {atom.id} (heat={atom.heat}) -> [X] DISSONANT (rem={atom.heat % domain_prime})")
return resonant, dissonant
def multi_domain_filter(self,
stream: List[Atom],
domain_primes: List[int]) -> Dict[int, List[Atom]]:
"""
Route atoms to multiple domains based on resonance.
An atom can belong to multiple domains if it resonates with all.
"""
domain_buckets = {p: [] for p in domain_primes}
for atom in stream:
for prime in domain_primes:
if atom.heat % prime == 0:
domain_buckets[prime].append(atom)
return domain_buckets
def inject_noise(self,
stream: List[Atom],
indices: List[int],
corruption_delta: int = 1) -> List[Atom]:
"""
Artificially corrupt atoms at specified indices.
Used for testing the immune system.
"""
corrupted = []
for i, atom in enumerate(stream):
if i in indices:
# Corrupt by adding delta (breaks modulo alignment)
new_heat = atom.heat + corruption_delta
corrupted.append(Atom(atom.id, new_heat, atom.payload))
else:
corrupted.append(atom)
return corrupted
def calculate_stream_integrity(self,
original: List[Atom],
filtered: List[Atom]) -> float:
"""Calculate what percentage of original stream survived filtering."""
if not original:
return 0.0
return len(filtered) / len(original)
def get_rejection_summary(self) -> Dict:
"""Get summary of all rejections."""
return {
'total_rejections': len(self.rejection_log),
'by_domain': {},
'log': self.rejection_log
}
# ============================================
# STANDALONE TEST: The Immune System
# ============================================
if __name__ == "__main__":
harmonizer = Harmonizer()
print("="*60)
print(" SPCW HARMONIZATION TEST (The Immune System)")
print("="*60)
# ===== TEST 1: Basic Resonance Filter =====
print("\n[TEST 1] Basic Resonance Filter")
print("-"*40)
# Create clean stream of TEXT atoms [19]
stream = []
for i in range(5):
# Valid Heat: Must be divisible by 19
valid_heat = (i + 1) * 19
atom = Atom(id=i, heat=valid_heat, payload=f"Data_Chunk_{i}".encode())
stream.append(atom)
print(f"Original Stream Heats: {[a.heat for a in stream]}")
# Inject noise: Corrupt Atom #2
print("\n[INJECTION] Corrupting Atom #2...")
corrupted_stream = harmonizer.inject_noise(stream, indices=[2], corruption_delta=1)
print(f"Corrupted Stream Heats: {[a.heat for a in corrupted_stream]}")
# Filter
clean, rejected = harmonizer.filter_stream(corrupted_stream, domain_prime=19)
print(f"\n[REPORT]")
print(f" Input Size: {len(corrupted_stream)}")
print(f" Clean Output: {len(clean)}")
print(f" Rejected: {len(rejected)}")
if len(rejected) == 1 and rejected[0].id == 2:
print("[OK] TEST 1 PASSED: Dissonance filtered mathematically.")
else:
print("[X] TEST 1 FAILED")
# ===== TEST 2: Multi-Modal Corruption =====
print("\n[TEST 2] Multi-Modal Corruption Attack")
print("-"*40)
# Create stream with multiple types
multi_stream = [
Atom(0, 17 * 2, b"image_chunk_0"), # IMAGE [17] * 2 = 34
Atom(1, 17 * 3, b"image_chunk_1"), # IMAGE [17] * 3 = 51
Atom(2, 19 * 2, b"text_chunk_0"), # TEXT [19] * 2 = 38
Atom(3, 19 * 3, b"text_chunk_1"), # TEXT [19] * 3 = 57
Atom(4, 17 * 19, b"multimodal"), # IMAGE + TEXT = 323
]
print(f"Original: {[(a.id, a.heat) for a in multi_stream]}")
# Corrupt atoms 1 and 3
attacked_stream = harmonizer.inject_noise(multi_stream, indices=[1, 3], corruption_delta=1)
print(f"Attacked: {[(a.id, a.heat) for a in attacked_stream]}")
# Filter for IMAGE domain [17]
image_clean, image_rejected = harmonizer.filter_stream(attacked_stream, domain_prime=17)
print(f"\nIMAGE Domain [17]: {len(image_clean)} clean, {len(image_rejected)} rejected")
# Filter for TEXT domain [19]
text_clean, text_rejected = harmonizer.filter_stream(attacked_stream, domain_prime=19)
print(f"TEXT Domain [19]: {len(text_clean)} clean, {len(text_rejected)} rejected")
# ===== TEST 3: Cascading Attack =====
print("\n[TEST 3] Cascading Attack (50% Corruption)")
print("-"*40)
large_stream = [Atom(i, 7 * (i + 1), f"chunk_{i}".encode()) for i in range(10)]
print(f"Original: 10 atoms, all divisible by 7")
# Corrupt half
heavy_attack = harmonizer.inject_noise(large_stream, indices=[1, 3, 5, 7, 9], corruption_delta=1)
clean, rejected = harmonizer.filter_stream(heavy_attack, domain_prime=7, verbose=False)
integrity = harmonizer.calculate_stream_integrity(heavy_attack, clean)
print(f"Integrity after attack: {integrity*100:.0f}%")
print(f"Survivors: {len(clean)}, Rejected: {len(rejected)}")
if len(rejected) == 5:
print("[OK] TEST 3 PASSED: 50% corruption detected and filtered.")
# ===== FINAL SUMMARY =====
print("\n" + "="*60)
print(" HARMONIZATION SUMMARY")
print("="*60)
print(f"""
The LOGOS Immune System:
| Attack Type | Detection Method | Result |
|--------------------|----------------------|-----------|
| Single Corruption | heat % 19 != 0 | REJECTED |
| Multi-Modal Attack | heat % 17/19 != 0 | REJECTED |
| 50% Cascade | heat % 7 != 0 | REJECTED |
Principle: "Physics, not Policies"
- No virus database needed
- No signature matching
- Pure arithmetic geometry
""")
summary = harmonizer.get_rejection_summary()
print(f"Total Rejections: {summary['total_rejections']}")
print("\n" + "="*60)
print(" [OK] IMMUNE SYSTEM OPERATIONAL")
print("="*60)
|