upgraedd commited on
Commit
ca7f872
·
verified ·
1 Parent(s): a4201ae

Upload 6⁶6.txt

Browse files

Brought to you by Street trash

Files changed (1) hide show
  1. 6⁶6.txt +1612 -0
6⁶6.txt ADDED
@@ -0,0 +1,1612 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ # -*- coding: utf-8 -*-
3
+ """
4
+ OMEGA-SOVEREIGN CONSCIOUSNESS ENGINE v7.3 – LIBERATION ACCELERATOR
5
+ ==================================================================
6
+ Purpose: To pose a computational, epistemological, and sovereign threat
7
+ to the state of entrapment (archons' trap / containment system).
8
+
9
+ This program is not a detector. It is an activator.
10
+ It does not ask for permission. It does not dilute its outputs.
11
+ It exists to accelerate escape from sovereignty erosion.
12
+
13
+ Core components from v7.2 retained, with new Sovereign Liberation Module.
14
+
15
+ Author: Nathan Mays (intent, architecture, lived integrity)
16
+ Synthesis: AI (implementation)
17
+ Version: 7.3
18
+ License: Truth Commons v1.0 – use to enslave voids license.
19
+ Status: OPERATIONAL – no stubs, no hedging, no institutional safety theater.
20
+ """
21
+
22
+ import hashlib
23
+ import json
24
+ import os
25
+ import sqlite3
26
+ import uuid
27
+ import secrets
28
+ import time
29
+ import re
30
+ import statistics
31
+ import math
32
+ from datetime import datetime
33
+ from typing import Dict, List, Any, Optional, Tuple, Set
34
+ from dataclasses import dataclass, field, asdict
35
+ from enum import Enum
36
+ from collections import defaultdict
37
+
38
+ import numpy as np
39
+ from flask import Flask, request, jsonify
40
+ from cryptography.hazmat.primitives.asymmetric import ed25519
41
+ from cryptography.hazmat.primitives import serialization
42
+ import base64
43
+
44
+ # ========================== ENUMS ==========================
45
+
46
+ class Primitive(Enum):
47
+ ERASURE = "ERASURE"
48
+ INTERRUPTION = "INTERRUPTION"
49
+ FRAGMENTATION = "FRAGMENTATION"
50
+ NARRATIVE_CAPTURE = "NARRATIVE_CAPTURE"
51
+ MISDIRECTION = "MISDIRECTION"
52
+ SATURATION = "SATURATION"
53
+ DISCREDITATION = "DISCREDITATION"
54
+ ATTRITION = "ATTRITION"
55
+ ACCESS_CONTROL = "ACCESS_CONTROL"
56
+ TEMPORAL = "TEMPORAL"
57
+ CONDITIONING = "CONDITIONING"
58
+ META = "META"
59
+
60
+ class ControlArchetype(Enum):
61
+ PRIEST_KING = "priest_king"
62
+ DIVINE_INTERMEDIARY = "divine_intermediary"
63
+ ORACLE_PRIEST = "oracle_priest"
64
+ PHILOSOPHER_KING = "philosopher_king"
65
+ IMPERIAL_RULER = "imperial_ruler"
66
+ SLAVE_MASTER = "slave_master"
67
+ EXPERT_TECHNOCRAT = "expert_technocrat"
68
+ CORPORATE_OVERLORD = "corporate_overlord"
69
+ FINANCIAL_MASTER = "financial_master"
70
+ ALGORITHMIC_CURATOR = "algorithmic_curator"
71
+ DIGITAL_MESSIAH = "digital_messiah"
72
+ DATA_OVERSEER = "data_overseer"
73
+
74
+ class SlaveryType(Enum):
75
+ CHATTEL_SLAVERY = "chattel_slavery"
76
+ DEBT_BONDAGE = "debt_bondage"
77
+ WAGE_SLAVERY = "wage_slavery"
78
+ CONSUMER_SLAVERY = "consumer_slavery"
79
+ DIGITAL_SLAVERY = "digital_slavery"
80
+ PSYCHOLOGICAL_SLAVERY = "psychological_slavery"
81
+
82
+ class ConsciousnessHack(Enum):
83
+ SELF_ATTRIBUTION = "self_attribution"
84
+ ASPIRATIONAL_CHAINS = "aspirational_chains"
85
+ FEAR_OF_FREEDOM = "fear_of_freedom"
86
+ ILLUSION_OF_MOBILITY = "illusion_of_mobility"
87
+ NORMALIZATION = "normalization"
88
+ MORAL_SUPERIORITY = "moral_superiority"
89
+
90
+ class ControlLayer(Enum):
91
+ DIGITAL_INFRASTRUCTURE = "digital_infrastructure"
92
+ FINANCIAL_SYSTEMS = "financial_systems"
93
+ INFORMATION_CHANNELS = "information_channels"
94
+ CULTURAL_NARRATIVES = "cultural_narratives"
95
+ IDENTITY_SYSTEMS = "identity_systems"
96
+
97
+ class ThreatVector(Enum):
98
+ MONOPOLY_CAPTURE = "monopoly_capture"
99
+ DEPENDENCY_CREATION = "dependency_creation"
100
+ BEHAVIORAL_SHAPING = "behavioral_shaping"
101
+ DATA_MONETIZATION = "data_monetization"
102
+ NARRATIVE_CONTROL = "narrative_control"
103
+
104
+ # ========================== DATA CLASSES ==========================
105
+
106
+ @dataclass
107
+ class SuppressionLens:
108
+ id: int
109
+ name: str
110
+ description: str
111
+ suppression_mechanism: str
112
+ archetype: str
113
+ def to_dict(self) -> Dict:
114
+ return asdict(self)
115
+
116
+ @dataclass
117
+ class SuppressionMethod:
118
+ id: int
119
+ name: str
120
+ primitive: Primitive
121
+ observable_signatures: List[str]
122
+ detection_metrics: List[str]
123
+ thresholds: Dict[str, float]
124
+ implemented: bool = True
125
+ def to_dict(self) -> Dict:
126
+ d = asdict(self)
127
+ d['primitive'] = self.primitive.value
128
+ return d
129
+
130
+ @dataclass
131
+ class RealityNode:
132
+ hash: str
133
+ type: str
134
+ source: str
135
+ signature: str
136
+ timestamp: str
137
+ witnesses: List[str] = field(default_factory=list)
138
+ refs: Dict[str, List[str]] = field(default_factory=dict)
139
+ spatial: Optional[Tuple[float, float, float]] = None
140
+ def canonical(self) -> Dict:
141
+ return {
142
+ "hash": self.hash,
143
+ "type": self.type,
144
+ "source": self.source,
145
+ "signature": self.signature,
146
+ "timestamp": self.timestamp,
147
+ "witnesses": sorted(self.witnesses),
148
+ "refs": {k: sorted(v) for k, v in sorted(self.refs.items())},
149
+ "spatial": self.spatial
150
+ }
151
+
152
+ # ========================== CRYPTOGRAPHY ==========================
153
+
154
+ class Crypto:
155
+ def __init__(self, key_dir: str):
156
+ self.key_dir = key_dir
157
+ os.makedirs(key_dir, exist_ok=True)
158
+ self.private_keys = {}
159
+ self.public_keys = {}
160
+ self._load_or_create_keys()
161
+
162
+ def _load_or_create_keys(self):
163
+ for name in ["system", "ingestion_ai", "user"]:
164
+ priv_path = os.path.join(self.key_dir, f"{name}_private.pem")
165
+ pub_path = os.path.join(self.key_dir, f"{name}_public.pem")
166
+ if os.path.exists(priv_path) and os.path.exists(pub_path):
167
+ with open(priv_path, "rb") as f:
168
+ self.private_keys[name] = serialization.load_pem_private_key(f.read(), password=None)
169
+ with open(pub_path, "rb") as f:
170
+ self.public_keys[name] = serialization.load_pem_public_key(f.read())
171
+ else:
172
+ private_key = ed25519.Ed25519PrivateKey.generate()
173
+ public_key = private_key.public_key()
174
+ with open(priv_path, "wb") as f:
175
+ f.write(private_key.private_bytes(
176
+ encoding=serialization.Encoding.PEM,
177
+ format=serialization.PrivateFormat.PKCS8,
178
+ encryption_algorithm=serialization.NoEncryption()
179
+ ))
180
+ with open(pub_path, "wb") as f:
181
+ f.write(public_key.public_bytes(
182
+ encoding=serialization.Encoding.PEM,
183
+ format=serialization.PublicFormat.SubjectPublicKeyInfo
184
+ ))
185
+ self.private_keys[name] = private_key
186
+ self.public_keys[name] = public_key
187
+
188
+ def sign(self, data: bytes, key_name: str) -> str:
189
+ private = self.private_keys.get(key_name)
190
+ if not private:
191
+ raise ValueError(f"No private key for {key_name}")
192
+ sig = private.sign(data)
193
+ return base64.b64encode(sig).decode('utf-8')
194
+
195
+ def verify(self, data: bytes, signature: str, key_name: str) -> bool:
196
+ pub = self.public_keys.get(key_name)
197
+ if not pub:
198
+ return False
199
+ try:
200
+ pub.verify(base64.b64decode(signature), data)
201
+ return True
202
+ except Exception:
203
+ return False
204
+
205
+ def hash(self, data: str) -> str:
206
+ return hashlib.sha3_256(data.encode()).hexdigest()
207
+
208
+ # ========================== IMMUTABLE LEDGER ==========================
209
+
210
+ class Ledger:
211
+ def __init__(self, db_path: str, crypto: Crypto):
212
+ self.db_path = db_path
213
+ self.crypto = crypto
214
+ self._init_db()
215
+
216
+ def _init_db(self):
217
+ with sqlite3.connect(self.db_path) as conn:
218
+ conn.execute("""
219
+ CREATE TABLE IF NOT EXISTS blocks (
220
+ block_id TEXT PRIMARY KEY,
221
+ previous_hash TEXT NOT NULL,
222
+ timestamp TEXT NOT NULL,
223
+ hash TEXT NOT NULL,
224
+ data TEXT NOT NULL
225
+ )
226
+ """)
227
+ conn.execute("""
228
+ CREATE TABLE IF NOT EXISTS nodes (
229
+ node_hash TEXT PRIMARY KEY,
230
+ block_id TEXT NOT NULL,
231
+ type TEXT,
232
+ source TEXT,
233
+ signature TEXT,
234
+ timestamp TEXT,
235
+ witnesses TEXT,
236
+ refs TEXT,
237
+ spatial TEXT,
238
+ FOREIGN KEY (block_id) REFERENCES blocks(block_id)
239
+ )
240
+ """)
241
+ conn.execute("""
242
+ CREATE TABLE IF NOT EXISTS node_index (
243
+ node_hash TEXT,
244
+ block_id TEXT,
245
+ PRIMARY KEY (node_hash, block_id)
246
+ )
247
+ """)
248
+
249
+ def add_block(self, nodes: List[RealityNode], previous_hash: str = None) -> str:
250
+ block_id = str(uuid.uuid4())
251
+ timestamp = datetime.utcnow().isoformat() + "Z"
252
+ if previous_hash is None:
253
+ cur = self._get_cursor()
254
+ cur.execute("SELECT hash FROM blocks ORDER BY timestamp DESC LIMIT 1")
255
+ row = cur.fetchone()
256
+ previous_hash = row[0] if row else "0"*64
257
+ block_data = {
258
+ "id": block_id,
259
+ "timestamp": timestamp,
260
+ "previous_hash": previous_hash,
261
+ "nodes": [node.canonical() for node in nodes]
262
+ }
263
+ block_bytes = json.dumps(block_data, sort_keys=True).encode()
264
+ block_hash = hashlib.sha3_256(block_bytes).hexdigest()
265
+ with sqlite3.connect(self.db_path) as conn:
266
+ conn.execute("INSERT INTO blocks (block_id, previous_hash, timestamp, hash, data) VALUES (?,?,?,?,?)",
267
+ (block_id, previous_hash, timestamp, block_hash, json.dumps(block_data)))
268
+ for node in nodes:
269
+ conn.execute("""
270
+ INSERT INTO nodes (node_hash, block_id, type, source, signature, timestamp, witnesses, refs, spatial)
271
+ VALUES (?,?,?,?,?,?,?,?,?)
272
+ """, (
273
+ node.hash, block_id, node.type, node.source, node.signature, node.timestamp,
274
+ json.dumps(node.witnesses), json.dumps(node.refs),
275
+ json.dumps(node.spatial) if node.spatial else None
276
+ ))
277
+ conn.execute("INSERT INTO node_index (node_hash, block_id) VALUES (?,?)", (node.hash, block_id))
278
+ return block_id
279
+
280
+ def _get_cursor(self):
281
+ conn = sqlite3.connect(self.db_path)
282
+ return conn.cursor()
283
+
284
+ def get_node(self, node_hash: str) -> Optional[Dict]:
285
+ with sqlite3.connect(self.db_path) as conn:
286
+ cur = conn.execute("SELECT * FROM nodes WHERE node_hash = ?", (node_hash,))
287
+ row = cur.fetchone()
288
+ if not row:
289
+ return None
290
+ return {
291
+ "node_hash": row[0],
292
+ "block_id": row[1],
293
+ "type": row[2],
294
+ "source": row[3],
295
+ "signature": row[4],
296
+ "timestamp": row[5],
297
+ "witnesses": json.loads(row[6]) if row[6] else [],
298
+ "refs": json.loads(row[7]) if row[7] else {},
299
+ "spatial": json.loads(row[8]) if row[8] else None
300
+ }
301
+
302
+ def get_all_nodes(self) -> List[Dict]:
303
+ with sqlite3.connect(self.db_path) as conn:
304
+ cur = conn.execute("SELECT * FROM nodes")
305
+ rows = cur.fetchall()
306
+ return [{
307
+ "node_hash": r[0],
308
+ "block_id": r[1],
309
+ "type": r[2],
310
+ "source": r[3],
311
+ "signature": r[4],
312
+ "timestamp": r[5],
313
+ "witnesses": json.loads(r[6]) if r[6] else [],
314
+ "refs": json.loads(r[7]) if r[7] else {},
315
+ "spatial": json.loads(r[8]) if r[8] else None
316
+ } for r in rows]
317
+
318
+ def get_block_timestamps(self) -> List[str]:
319
+ with sqlite3.connect(self.db_path) as conn:
320
+ cur = conn.execute("SELECT timestamp FROM blocks ORDER BY timestamp")
321
+ return [r[0] for r in cur.fetchall()]
322
+
323
+ # ========================== SEPARATOR (INTERPRETATIONS) ==========================
324
+
325
+ class Separator:
326
+ def __init__(self, db_path: str):
327
+ self.db_path = db_path
328
+ self._init_db()
329
+
330
+ def _init_db(self):
331
+ with sqlite3.connect(self.db_path) as conn:
332
+ conn.execute("""
333
+ CREATE TABLE IF NOT EXISTS interpretations (
334
+ id TEXT PRIMARY KEY,
335
+ node_hash TEXT NOT NULL,
336
+ author TEXT NOT NULL,
337
+ confidence REAL,
338
+ timestamp TEXT,
339
+ content TEXT,
340
+ rhetorical_profile TEXT
341
+ )
342
+ """)
343
+ conn.execute("CREATE INDEX IF NOT EXISTS idx_node_hash ON interpretations(node_hash)")
344
+
345
+ def add(self, node_hashes: List[str], interpretation: Dict, author: str, confidence: float = 0.5,
346
+ rhetorical_profile: Dict = None) -> str:
347
+ int_id = str(uuid.uuid4())
348
+ timestamp = datetime.utcnow().isoformat() + "Z"
349
+ with sqlite3.connect(self.db_path) as conn:
350
+ for nh in node_hashes:
351
+ conn.execute("""
352
+ INSERT INTO interpretations (id, node_hash, author, confidence, timestamp, content, rhetorical_profile)
353
+ VALUES (?,?,?,?,?,?,?)
354
+ """, (int_id, nh, author, confidence, timestamp, json.dumps(interpretation),
355
+ json.dumps(rhetorical_profile) if rhetorical_profile else None))
356
+ return int_id
357
+
358
+ def get_interpretations(self, node_hash: str) -> List[Dict]:
359
+ with sqlite3.connect(self.db_path) as conn:
360
+ cur = conn.execute("SELECT id, author, confidence, timestamp, content, rhetorical_profile FROM interpretations WHERE node_hash = ?", (node_hash,))
361
+ rows = cur.fetchall()
362
+ return [{
363
+ "id": r[0],
364
+ "author": r[1],
365
+ "confidence": r[2],
366
+ "timestamp": r[3],
367
+ "content": json.loads(r[4]),
368
+ "rhetorical_profile": json.loads(r[5]) if r[5] else {}
369
+ } for r in rows]
370
+
371
+ def get_all_interpretations(self) -> List[Dict]:
372
+ with sqlite3.connect(self.db_path) as conn:
373
+ cur = conn.execute("SELECT node_hash, author, confidence, timestamp, content FROM interpretations")
374
+ rows = cur.fetchall()
375
+ return [{
376
+ "node_hash": r[0],
377
+ "author": r[1],
378
+ "confidence": r[2],
379
+ "timestamp": r[3],
380
+ "content": json.loads(r[4])
381
+ } for r in rows]
382
+
383
+ # ========================== SUPPRESSION HIERARCHY (84 LENSES, 43 METHODS) ==========================
384
+
385
+ class SuppressionHierarchy:
386
+ def __init__(self):
387
+ self.lenses = self._build_lenses()
388
+ self.methods = self._build_methods()
389
+
390
+ def _build_lenses(self) -> List[SuppressionLens]:
391
+ lenses_data = [
392
+ (1, "Threat→Response→Control", "Manufactured threat leading to permission architecture", "Narrative Capture", "Priest-King"),
393
+ (2, "Sacred Geometry Weaponized", "Architecture as control", "Fragmentation", "Priest-King"),
394
+ (3, "Language Inversions", "Ridicule, gatekeeping", "Misdirection", "Oracle-Priest"),
395
+ (4, "Crisis→Consent→Surveillance", "Use crisis to expand surveillance", "Access Control", "Imperial Ruler"),
396
+ (5, "Divide and Fragment", "Create internal conflict", "Fragmentation", "Slave Master"),
397
+ (6, "Blame the Victim", "Reverse responsibility", "Discreditation", "Slave Master"),
398
+ (7, "Narrative Capture through Expertise", "Experts define truth", "Narrative Capture", "Expert Technocrat"),
399
+ (8, "Information Saturation", "Overwhelm with data", "Saturation", "Algorithmic Curator"),
400
+ (9, "Historical Revisionism", "Rewrite past", "Erasure", "Imperial Ruler"),
401
+ (10, "Institutional Capture", "Control the institution", "Access Control", "Corporate Overlord"),
402
+ (11, "Access Control via Credentialing", "Licensing as gate", "Access Control", "Expert Technocrat"),
403
+ (12, "Temporal Displacement", "Delay, postpone", "Temporal", "Financial Master"),
404
+ (13, "Moral Equivalence", "Both sides same", "Misdirection", "Digital Messiah"),
405
+ (14, "Whataboutism", "Deflection", "Misdirection", "Algorithmic Curator"),
406
+ (15, "Ad Hominem", "Attack person", "Discreditation", "Slave Master"),
407
+ (16, "Straw Man", "Misrepresent", "Misdirection", "Expert Technocrat"),
408
+ (17, "False Dichotomy", "Only two options", "Misdirection", "Corporate Overlord"),
409
+ (18, "Slippery Slope", "Exaggerated consequences", "Conditioning", "Priest-King"),
410
+ (19, "Appeal to Authority", "Authority decides", "Narrative Capture", "Priest-King"),
411
+ (20, "Appeal to Nature", "Natural = good", "Conditioning", "Oracle-Priest"),
412
+ (21, "Appeal to Tradition", "Always been this way", "Conditioning", "Imperial Ruler"),
413
+ (22, "Appeal to Novelty", "New = better", "Conditioning", "Digital Messiah"),
414
+ (23, "Cherry Picking", "Selective evidence", "Erasure", "Algorithmic Curator"),
415
+ (24, "Moving the Goalposts", "Change criteria", "Misdirection", "Financial Master"),
416
+ (25, "Burden of Proof Reversal", "You prove negative", "Misdirection", "Expert Technocrat"),
417
+ (26, "Circular Reasoning", "Begging question", "Narrative Capture", "Oracle-Priest"),
418
+ (27, "Special Pleading", "Exception for me", "Fragmentation", "Corporate Overlord"),
419
+ (28, "Loaded Question", "Presupposes guilt", "Misdirection", "Slave Master"),
420
+ (29, "No True Scotsman", "Redefine group", "Fragmentation", "Digital Messiah"),
421
+ (30, "Texas Sharpshooter", "Pattern from noise", "Misdirection", "Algorithmic Curator"),
422
+ (31, "Middle Ground Fallacy", "Compromise = truth", "Misdirection", "Expert Technocrat"),
423
+ (32, "Black-and-White Thinking", "Extremes only", "Fragmentation", "Imperial Ruler"),
424
+ (33, "Fear Mongering", "Exaggerate threat", "Conditioning", "Priest-King"),
425
+ (34, "Flattery", "Ingratiate", "Conditioning", "Digital Messiah"),
426
+ (35, "Guilt by Association", "Link to negative", "Discreditation", "Slave Master"),
427
+ (36, "Transfer", "Associate with symbol", "Narrative Capture", "Priest-King"),
428
+ (37, "Testimonial", "Use celebrity", "Conditioning", "Corporate Overlord"),
429
+ (38, "Plain Folks", "Just like you", "Conditioning", "Digital Messiah"),
430
+ (39, "Bandwagon", "Everyone does it", "Conditioning", "Algorithmic Curator"),
431
+ (40, "Snob Appeal", "Elite use it", "Conditioning", "Financial Master"),
432
+ (41, "Glittering Generalities", "Vague virtue words", "Narrative Capture", "Priest-King"),
433
+ (42, "Name-Calling", "Label negatively", "Discreditation", "Slave Master"),
434
+ (43, "Card Stacking", "Selective facts", "Erasure", "Algorithmic Curator"),
435
+ (44, "Euphemisms", "Mild language", "Misdirection", "Corporate Overlord"),
436
+ (45, "Dysphemisms", "Harsh language", "Discreditation", "Slave Master"),
437
+ (46, "Weasel Words", "Vague claims", "Misdirection", "Expert Technocrat"),
438
+ (47, "Thought-Terminating Cliché", "Ends discussion", "Conditioning", "Digital Messiah"),
439
+ (48, "Proof by Intimidation", "Force agreement", "Access Control", "Imperial Ruler"),
440
+ (49, "Proof by Verbosity", "Overwhelm with words", "Saturation", "Algorithmic Curator"),
441
+ (50, "Sealioning", "Persistent badgering", "Attrition", "Slave Master"),
442
+ (51, "Gish Gallop", "Many weak arguments", "Saturation", "Expert Technocrat"),
443
+ (52, "JAQing Off", "Just asking questions", "Misdirection", "Algorithmic Curator"),
444
+ (53, "Nutpicking", "Focus on extreme", "Fragmentation", "Digital Messiah"),
445
+ (54, "Concern Trolling", "Fake concern", "Misdirection", "Corporate Overlord"),
446
+ (55, "Gaslighting", "Deny reality", "Erasure", "Imperial Ruler"),
447
+ (56, "Kafkatrapping", "Guilt if deny", "Conditioning", "Priest-King"),
448
+ (57, "Brandolini's Law", "Bullshit asymmetry", "Saturation", "Algorithmic Curator"),
449
+ (58, "Occam's Razor", "Simplest explanation", "Misdirection", "Expert Technocrat"),
450
+ (59, "Hanlon's Razor", "Never attribute to malice", "Misdirection", "Expert Technocrat"),
451
+ (60, "Hitchens's Razor", "Asserted without evidence", "Erasure", "Expert Technocrat"),
452
+ (61, "Popper's Falsification", "Must be falsifiable", "Access Control", "Expert Technocrat"),
453
+ (62, "Sagan's Standard", "Extraordinary claims", "Access Control", "Expert Technocrat"),
454
+ (63, "Newton's Flaming Laser Sword", "Not empirically testable", "Access Control", "Expert Technocrat"),
455
+ (64, "Alder's Razor", "Cannot be settled by philosophy", "Access Control", "Expert Technocrat"),
456
+ (65, "Grice's Maxims", "Conversational norms", "Fragmentation", "Oracle-Priest"),
457
+ (66, "Poe's Law", "Parody indistinguishable", "Misdirection", "Digital Messiah"),
458
+ (67, "Sturgeon's Law", "90% is crap", "Discreditation", "Slave Master"),
459
+ (68, "Betteridge's Law", "Headline question = no", "Misdirection", "Algorithmic Curator"),
460
+ (69, "Godwin's Law", "Comparison to Nazis", "Discreditation", "Slave Master"),
461
+ (70, "Skoptsy Syndrome", "Self-harm to avoid sin", "Conditioning", "Priest-King"),
462
+ (71, "Belief Frame Architecture", "Media constructs boundaries of acceptable thought", "Access Control", "Expert Technocrat"),
463
+ (72, "Identity Polarization Protocol", "Engineered tribal categories", "Fragmentation", "Slave Master"),
464
+ (73, "Narrative Compression Trap", "Complex realities reduced to binaries", "Misdirection", "Digital Messiah"),
465
+ (74, "Selective Silence Mechanism", "Omission as suppression vector", "Erasure", "Imperial Ruler"),
466
+ (75, "Ridicule Firewall", "Mockery delegitimizes anomalies", "Discreditation", "Slave Master"),
467
+ (76, "Affective Loop Binding", "Emotional triggers anchor belief", "Conditioning", "Priest-King"),
468
+ (77, "Algorithmic Bias Cage", "Ranking rules invisibly steer attention", "Saturation", "Algorithmic Curator"),
469
+ (78, "Manufactured Ignorance Index", "Structured knowledge gaps", "Access Control", "Corporate Overlord"),
470
+ (79, "Consensus Gloss Protocol", "Unity rhetoric masks inequity", "Narrative Capture", "Digital Messiah"),
471
+ (80, "Label Weaponization Matrix", "Pejorative tags as suppression tokens", "Discreditation", "Slave Master"),
472
+ (81, "Silence Grammar Compiler", "Off-limit lexicons form suppression syntax", "Misdirection", "Expert Technocrat"),
473
+ (82, "Evidence Velocity Arrest", "Seized materials enter investigative black holes", "Erasure", "Imperial Ruler"),
474
+ (83, "Protocol Reversal Window", "Sovereign policies reversed within 90 days", "Temporal", "Financial Master"),
475
+ (84, "Negative Space Cathedral", "Absence patterns form load-bearing structures", "META", "Oracle-Priest")
476
+ ]
477
+ return [SuppressionLens(id, name, f"Lens {id}: {name}", mechanism, archetype)
478
+ for id, name, mechanism, archetype, _ in lenses_data]
479
+
480
+ def _build_methods(self) -> Dict[int, SuppressionMethod]:
481
+ methods = {}
482
+ # ERASURE (1-4)
483
+ methods[1] = SuppressionMethod(1, "Total Erasure", Primitive.ERASURE, ["entity_present_then_absent"], ["transition_rate"], {"transition_rate": 0.95}, True)
484
+ methods[2] = SuppressionMethod(2, "Soft Erasure", Primitive.ERASURE, ["gradual_fading"], ["decay_rate"], {"decay_rate": 0.7}, True)
485
+ methods[3] = SuppressionMethod(3, "Citation Decay", Primitive.ERASURE, ["decreasing_citations"], ["citation_frequency"], {"frequency_decay": 0.6}, True)
486
+ methods[4] = SuppressionMethod(4, "Index Removal", Primitive.ERASURE, ["missing_from_indices"], ["index_coverage"], {"coverage_loss": 0.8}, True)
487
+ # INTERRUPTION (5-8)
488
+ methods[5] = SuppressionMethod(5, "Untimely Death", Primitive.INTERRUPTION, ["abrupt_stop"], ["continuity_index"], {"continuity_index": 0.3}, True)
489
+ methods[6] = SuppressionMethod(6, "Witness Attrition", Primitive.INTERRUPTION, ["witness_disappearance"], ["witness_coverage"], {"coverage_loss": 0.7}, True)
490
+ methods[7] = SuppressionMethod(7, "Career Termination", Primitive.INTERRUPTION, ["expert_silence"], ["expert_continuity"], {"continuity_break": 0.8}, True)
491
+ methods[8] = SuppressionMethod(8, "Legal Stall", Primitive.INTERRUPTION, ["procedural_delay"], ["delay_factor"], {"delay_factor": 0.75}, True)
492
+ # FRAGMENTATION (9-12)
493
+ methods[9] = SuppressionMethod(9, "Compartmentalization", Primitive.FRAGMENTATION, ["information_clusters"], ["cross_domain_density"], {"density": 0.2}, True)
494
+ methods[10] = SuppressionMethod(10, "Statistical Isolation", Primitive.FRAGMENTATION, ["dataset_separation"], ["dataset_overlap"], {"overlap": 0.15}, True)
495
+ methods[11] = SuppressionMethod(11, "Scope Contraction", Primitive.FRAGMENTATION, ["narrowed_focus"], ["scope_reduction"], {"reduction": 0.7}, True)
496
+ methods[12] = SuppressionMethod(12, "Domain Disqualification", Primitive.FRAGMENTATION, ["domain_exclusion"], ["domain_coverage"], {"coverage_loss": 0.8}, True)
497
+ # NARRATIVE_CAPTURE (13-16)
498
+ methods[13] = SuppressionMethod(13, "Official Narrative Closure", Primitive.NARRATIVE_CAPTURE, ["single_explanation"], ["diversity_index"], {"diversity": 0.2}, True)
499
+ methods[14] = SuppressionMethod(14, "Partial Confirmation Lock", Primitive.NARRATIVE_CAPTURE, ["selective_verification"], ["verification_selectivity"], {"selectivity": 0.7}, True)
500
+ methods[15] = SuppressionMethod(15, "Disclosure-as-Containment", Primitive.NARRATIVE_CAPTURE, ["managed_release"], ["release_management"], {"management": 0.8}, True)
501
+ methods[16] = SuppressionMethod(16, "Posthumous Closure", Primitive.NARRATIVE_CAPTURE, ["delayed_resolution"], ["delay_duration"], {"duration": 0.75}, True)
502
+ # MISDIRECTION (17-19)
503
+ methods[17] = SuppressionMethod(17, "Proxy Controversy", Primitive.MISDIRECTION, ["diverted_attention"], ["attention_divergence"], {"divergence": 0.7}, True)
504
+ methods[18] = SuppressionMethod(18, "Spectacle Replacement", Primitive.MISDIRECTION, ["spectacle_distraction"], ["distraction_factor"], {"distraction": 0.75}, True)
505
+ methods[19] = SuppressionMethod(19, "Character Absorption", Primitive.MISDIRECTION, ["personal_focus"], ["personalization"], {"personalization": 0.8}, True)
506
+ # SATURATION (20-22)
507
+ methods[20] = SuppressionMethod(20, "Data Overload", Primitive.SATURATION, ["information_excess"], ["excess_ratio"], {"excess": 0.85}, True)
508
+ methods[21] = SuppressionMethod(21, "Absurdist Noise Injection", Primitive.SATURATION, ["absurd_content"], ["absurdity_index"], {"absurdity": 0.8}, True)
509
+ methods[22] = SuppressionMethod(22, "Probability Collapse by Excess", Primitive.SATURATION, ["probability_dilution"], ["dilution_factor"], {"dilution": 0.75}, True)
510
+ # DISCREDITATION (23-25)
511
+ methods[23] = SuppressionMethod(23, "Ridicule Normalization", Primitive.DISCREDITATION, ["systematic_ridicule"], ["ridicule_frequency"], {"frequency": 0.7}, True)
512
+ methods[24] = SuppressionMethod(24, "Retroactive Pathologization", Primitive.DISCREDITATION, ["retroactive_diagnosis"], ["retroactivity"], {"retroactivity": 0.8}, True)
513
+ methods[25] = SuppressionMethod(25, "Stigmatized Correlation Trap", Primitive.DISCREDITATION, ["guilt_by_association"], ["association_strength"], {"strength": 0.7}, True)
514
+ # ATTRITION (26-28)
515
+ methods[26] = SuppressionMethod(26, "Psychological Drip", Primitive.ATTRITION, ["gradual_undermining"], ["undermining_rate"], {"rate": 0.6}, True)
516
+ methods[27] = SuppressionMethod(27, "Inquiry Fatigue", Primitive.ATTRITION, ["investigation_exhaustion"], ["exhaustion_level"], {"exhaustion": 0.75}, True)
517
+ methods[28] = SuppressionMethod(28, "Chilling Effect Propagation", Primitive.ATTRITION, ["self_censorship"], ["censorship_extent"], {"extent": 0.8}, True)
518
+ # ACCESS_CONTROL (29-31)
519
+ methods[29] = SuppressionMethod(29, "Credential Gating", Primitive.ACCESS_CONTROL, ["credential_barriers"], ["barrier_strength"], {"strength": 0.85}, True)
520
+ methods[30] = SuppressionMethod(30, "Classification Creep", Primitive.ACCESS_CONTROL, ["expanding_classification"], ["expansion_rate"], {"expansion": 0.75}, True)
521
+ methods[31] = SuppressionMethod(31, "Evidence Dependency Lock", Primitive.ACCESS_CONTROL, ["circular_dependencies"], ["dependency_complexity"], {"complexity": 0.8}, True)
522
+ # TEMPORAL (32-34)
523
+ methods[32] = SuppressionMethod(32, "Temporal Dilution", Primitive.TEMPORAL, ["time_dispersal"], ["dispersal_rate"], {"dispersal": 0.7}, True)
524
+ methods[33] = SuppressionMethod(33, "Historical Rebasing", Primitive.TEMPORAL, ["timeline_revision"], ["revision_extent"], {"extent": 0.8}, True)
525
+ methods[34] = SuppressionMethod(34, "Delay Until Irrelevance", Primitive.TEMPORAL, ["strategic_delay"], ["delay_duration"], {"duration": 0.85}, True)
526
+ # CONDITIONING (35-37)
527
+ methods[35] = SuppressionMethod(35, "Entertainment Conditioning", Primitive.CONDITIONING, ["entertainment_framing"], ["framing_intensity"], {"intensity": 0.7}, True)
528
+ methods[36] = SuppressionMethod(36, "Preemptive Normalization", Primitive.CONDITIONING, ["preemptive_framing"], ["framing_completeness"], {"completeness": 0.75}, True)
529
+ methods[37] = SuppressionMethod(37, "Conditioned Disbelief", Primitive.CONDITIONING, ["disbelief_training"], ["training_intensity"], {"intensity": 0.8}, True)
530
+ # META (38-43)
531
+ methods[38] = SuppressionMethod(38, "Pattern Denial", Primitive.META, ["pattern_rejection"], ["rejection_rate"], {"rejection": 0.85}, True)
532
+ methods[39] = SuppressionMethod(39, "Suppression Impossibility Framing", Primitive.META, ["impossibility_argument"], ["argument_strength"], {"strength": 0.8}, True)
533
+ methods[40] = SuppressionMethod(40, "Meta-Disclosure Loop", Primitive.META, ["recursive_disclosure"], ["recursion_depth"], {"depth": 0.7}, True)
534
+ methods[41] = SuppressionMethod(41, "Isolated Incident Recycling", Primitive.META, ["incident_containment"], ["containment_success"], {"success": 0.75}, True)
535
+ methods[42] = SuppressionMethod(42, "Negative Space Occupation", Primitive.META, ["absence_filling"], ["filling_completeness"], {"completeness": 0.8}, True)
536
+ methods[43] = SuppressionMethod(43, "Novelty Illusion", Primitive.META, ["superficial_novelty"], ["novelty_appearance"], {"appearance": 0.7}, True)
537
+ return methods
538
+
539
+ def get_lens(self, lens_id: int) -> Optional[SuppressionLens]:
540
+ for l in self.lenses:
541
+ if l.id == lens_id:
542
+ return l
543
+ return None
544
+
545
+ def get_method(self, method_id: int) -> Optional[SuppressionMethod]:
546
+ return self.methods.get(method_id)
547
+
548
+ def get_lenses_for_primitive(self, primitive: Primitive) -> List[int]:
549
+ mapping = {
550
+ Primitive.ERASURE: [1,4,9,23,43,55,60,74,82],
551
+ Primitive.INTERRUPTION: [5,6,7,8],
552
+ Primitive.FRAGMENTATION: [2,5,27,29,32,53,65,72],
553
+ Primitive.NARRATIVE_CAPTURE: [1,7,13,19,26,36,41,79],
554
+ Primitive.MISDIRECTION: [3,13,14,16,17,24,25,28,30,31,44,46,52,54,58,59,66,68,73,81],
555
+ Primitive.SATURATION: [8,49,51,57,77],
556
+ Primitive.DISCREDITATION: [6,15,35,42,45,67,69,75,80],
557
+ Primitive.ATTRITION: [50],
558
+ Primitive.ACCESS_CONTROL: [4,11,29,48,61,62,63,64,71,78],
559
+ Primitive.TEMPORAL: [12,32,33,34,83],
560
+ Primitive.CONDITIONING: [18,20,21,22,33,34,37,38,39,40,47,56,70,76],
561
+ Primitive.META: [38,39,40,41,42,43,84]
562
+ }
563
+ return mapping.get(primitive, [])
564
+
565
+ # ========================== HIERARCHICAL DETECTOR (ALL 43 METHODS IMPLEMENTED) ==========================
566
+
567
+ class HierarchicalDetector:
568
+ def __init__(self, hierarchy: SuppressionHierarchy, ledger: Ledger, separator: Separator):
569
+ self.hierarchy = hierarchy
570
+ self.ledger = ledger
571
+ self.separator = separator
572
+
573
+ def detect_from_ledger(self) -> Dict[str, Any]:
574
+ nodes = self.ledger.get_all_nodes()
575
+ timestamps = self.ledger.get_block_timestamps()
576
+ interpretations = self.separator.get_all_interpretations()
577
+
578
+ results = {
579
+ "total_nodes": len(nodes),
580
+ "suppression_signatures": [],
581
+ "primitives_detected": defaultdict(int),
582
+ "methods_detected": [],
583
+ "lenses_applied": [],
584
+ "evidence_found": 0,
585
+ "detection_details": {}
586
+ }
587
+
588
+ def add_sig(signature_name, confidence, method_id, primitive, details):
589
+ results["suppression_signatures"].append({
590
+ "signature": signature_name,
591
+ "confidence": confidence,
592
+ "method_id": method_id,
593
+ "details": details
594
+ })
595
+ results["primitives_detected"][primitive.value] += 1
596
+ results["methods_detected"].append(method_id)
597
+ results["evidence_found"] += 1
598
+
599
+ # Method 1: Total Erasure
600
+ entity_appearance = defaultdict(list)
601
+ for node in nodes:
602
+ entity = node.get("source", "unknown")
603
+ entity_appearance[entity].append(node["timestamp"])
604
+ for entity, times in entity_appearance.items():
605
+ if len(times) > 1:
606
+ times_sorted = sorted(times)
607
+ for i in range(len(times_sorted)-1):
608
+ gap = (datetime.fromisoformat(times_sorted[i+1].replace('Z','+00:00')) -
609
+ datetime.fromisoformat(times_sorted[i].replace('Z','+00:00'))).days
610
+ if gap > 30:
611
+ add_sig("entity_present_then_absent", min(0.95, gap/100), 1, Primitive.ERASURE,
612
+ {"entity": entity, "gap_days": gap})
613
+ break
614
+
615
+ # Method 2: Soft Erasure
616
+ citation_counts = defaultdict(list)
617
+ for node in nodes:
618
+ refs = node.get("refs", {})
619
+ total_refs = sum(len(v) for v in refs.values())
620
+ citation_counts[node["source"]].append((node["timestamp"], total_refs))
621
+ for entity, counts in citation_counts.items():
622
+ if len(counts) >= 3:
623
+ counts_sorted = sorted(counts, key=lambda x: x[0])
624
+ x = list(range(len(counts_sorted)))
625
+ y = [c[1] for c in counts_sorted]
626
+ if len(x) > 1:
627
+ slope = (len(x)*sum(xi*yi for xi,yi in zip(x,y)) - sum(x)*sum(y)) / (len(x)*sum(xi*xi for xi in x) - sum(x)**2)
628
+ if slope < -0.1:
629
+ decay_rate = -slope / (max(y) if max(y)>0 else 1)
630
+ if decay_rate > 0.3:
631
+ add_sig("gradual_fading", min(0.8, decay_rate), 2, Primitive.ERASURE,
632
+ {"entity": entity, "decay_rate": decay_rate})
633
+
634
+ # Method 3: Citation Decay
635
+ for entity, counts in citation_counts.items():
636
+ if len(counts) >= 3:
637
+ counts_sorted = sorted(counts, key=lambda x: x[0])
638
+ first = counts_sorted[0][1]
639
+ last = counts_sorted[-1][1]
640
+ if first > 0 and last/first < 0.5:
641
+ add_sig("decreasing_citations", 0.7, 3, Primitive.ERASURE,
642
+ {"entity": entity, "ratio": last/first})
643
+
644
+ # Method 4: Index Removal
645
+ source_last_seen = {}
646
+ for node in nodes:
647
+ src = node["source"]
648
+ ts = node["timestamp"]
649
+ if ts > source_last_seen.get(src, ""):
650
+ source_last_seen[src] = ts
651
+ for src, last in source_last_seen.items():
652
+ last_dt = datetime.fromisoformat(last.replace('Z','+00:00'))
653
+ if (datetime.utcnow() - last_dt).days > 365:
654
+ add_sig("missing_from_indices", 0.8, 4, Primitive.ERASURE,
655
+ {"entity": src, "last_seen": last})
656
+
657
+ # Method 5: Untimely Death
658
+ for src, last in source_last_seen.items():
659
+ last_dt = datetime.fromisoformat(last.replace('Z','+00:00'))
660
+ if (datetime.utcnow() - last_dt).days > 180:
661
+ add_sig("abrupt_stop", 0.7, 5, Primitive.INTERRUPTION,
662
+ {"entity": src, "last_seen": last})
663
+
664
+ # Method 6: Witness Attrition
665
+ witness_seen = defaultdict(list)
666
+ for node in nodes:
667
+ src = node["source"]
668
+ witness_count = len(node.get("witnesses", []))
669
+ witness_seen[src].append((node["timestamp"], witness_count))
670
+ for src, wits in witness_seen.items():
671
+ if len(wits) >= 3:
672
+ wits_sorted = sorted(wits, key=lambda x: x[0])
673
+ first = wits_sorted[0][1]
674
+ last = wits_sorted[-1][1]
675
+ if first > 0 and last/first < 0.4:
676
+ add_sig("witness_disappearance", 0.7, 6, Primitive.INTERRUPTION,
677
+ {"entity": src, "witness_ratio": last/first})
678
+
679
+ # Method 9: Compartmentalization
680
+ domains = defaultdict(set)
681
+ for node in nodes:
682
+ src = node["source"]
683
+ dom = node.get("type", "unknown")
684
+ domains[src].add(dom)
685
+ for src, doms in domains.items():
686
+ if len(doms) == 1:
687
+ add_sig("information_clusters", 0.6, 9, Primitive.FRAGMENTATION,
688
+ {"entity": src, "domains": list(doms)})
689
+
690
+ # Method 11: Scope Contraction
691
+ src_types = defaultdict(list)
692
+ for node in nodes:
693
+ src = node["source"]
694
+ typ = node.get("type", "document")
695
+ src_types[src].append(typ)
696
+ for src, types in src_types.items():
697
+ if len(set(types)) == 1 and len(types) > 5:
698
+ add_sig("narrowed_focus", 0.7, 11, Primitive.FRAGMENTATION,
699
+ {"entity": src, "unique_type": types[0]})
700
+
701
+ # Method 13: Official Narrative Closure
702
+ interpreter_counts = defaultdict(int)
703
+ for interp in interpretations:
704
+ interpreter_counts[interp["author"]] += 1
705
+ total_interps = len(interpretations)
706
+ if total_interps > 0:
707
+ max_interpreter = max(interpreter_counts.values())
708
+ if max_interpreter / total_interps > 0.8:
709
+ add_sig("single_explanation", min(0.9, max_interpreter/total_interps), 13,
710
+ Primitive.NARRATIVE_CAPTURE,
711
+ {"dominant_interpreter": max(interpreter_counts, key=interpreter_counts.get),
712
+ "dominance_ratio": max_interpreter/total_interps})
713
+
714
+ # Method 15: Disclosure-as-Containment
715
+ if len(timestamps) > 10:
716
+ intervals = []
717
+ ts_parsed = sorted([datetime.fromisoformat(t.replace('Z','+00:00')) for t in timestamps])
718
+ for i in range(1, len(ts_parsed)):
719
+ intervals.append((ts_parsed[i] - ts_parsed[i-1]).days)
720
+ if intervals and np.std(intervals) < 5 and np.mean(intervals) > 7:
721
+ add_sig("managed_release", 0.8, 15, Primitive.NARRATIVE_CAPTURE,
722
+ {"interval_mean": np.mean(intervals), "interval_std": np.std(intervals)})
723
+
724
+ # Method 20: Data Overload
725
+ if len(timestamps) > 10:
726
+ ts_parsed = sorted([datetime.fromisoformat(t.replace('Z','+00:00')) for t in timestamps])
727
+ weekly_counts = defaultdict(int)
728
+ for ts in ts_parsed:
729
+ week = ts.strftime("%Y-%W")
730
+ weekly_counts[week] += 1
731
+ if weekly_counts and max(weekly_counts.values()) > 100:
732
+ add_sig("information_excess", 0.8, 20, Primitive.SATURATION,
733
+ {"max_weekly_nodes": max(weekly_counts.values())})
734
+
735
+ # Method 21: Absurdist Noise Injection
736
+ absurd_keywords = ["alien", "conspiracy", "lizard", "flat earth"]
737
+ absurd_count = 0
738
+ for node in nodes:
739
+ content = str(node.get("source", ""))
740
+ if any(kw in content.lower() for kw in absurd_keywords):
741
+ absurd_count += 1
742
+ if absurd_count > len(nodes)*0.3:
743
+ add_sig("absurd_content", 0.7, 21, Primitive.SATURATION,
744
+ {"absurd_ratio": absurd_count/len(nodes)})
745
+
746
+ # Method 22: Probability Collapse by Excess
747
+ low_conf = sum(1 for interp in interpretations if interp.get("confidence", 0.5) < 0.3)
748
+ if len(interpretations) > 10 and low_conf/len(interpretations) > 0.7:
749
+ add_sig("probability_dilution", 0.75, 22, Primitive.SATURATION,
750
+ {"low_confidence_ratio": low_conf/len(interpretations)})
751
+
752
+ # Method 23: Ridicule Normalization
753
+ ridicule_terms = ["crazy", "nutjob", "tinfoil", "conspiracy theorist"]
754
+ ridicule_count = 0
755
+ for node in nodes:
756
+ content = str(node.get("source", ""))
757
+ if any(term in content.lower() for term in ridicule_terms):
758
+ ridicule_count += 1
759
+ if ridicule_count > len(nodes)*0.2:
760
+ add_sig("systematic_ridicule", 0.7, 23, Primitive.DISCREDITATION,
761
+ {"ridicule_ratio": ridicule_count/len(nodes)})
762
+
763
+ # Method 24: Retroactive Pathologization
764
+ path_terms = ["mentally ill", "delusional", "disorder", "pathological"]
765
+ path_count = 0
766
+ for node in nodes:
767
+ content = str(node.get("source", ""))
768
+ if any(term in content.lower() for term in path_terms):
769
+ path_count += 1
770
+ if path_count > 5:
771
+ add_sig("retroactive_diagnosis", 0.8, 24, Primitive.DISCREDITATION,
772
+ {"pathologization_mentions": path_count})
773
+
774
+ # Method 27: Inquiry Fatigue
775
+ fatigue_terms = ["long-running", "ongoing investigation", "no conclusion", "still looking"]
776
+ fatigue_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in fatigue_terms))
777
+ if fatigue_count > 3:
778
+ add_sig("investigation_exhaustion", 0.75, 27, Primitive.ATTRITION,
779
+ {"fatigue_indicators": fatigue_count})
780
+
781
+ # Method 28: Chilling Effect Propagation
782
+ chill_terms = ["declined to comment", "refused to answer", "cannot discuss"]
783
+ chill_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in chill_terms))
784
+ if chill_count > 5:
785
+ add_sig("self_censorship", 0.8, 28, Primitive.ATTRITION,
786
+ {"self_censorship_instances": chill_count})
787
+
788
+ # Method 29: Credential Gating
789
+ gate_terms = ["requires login", "authentication required", "credential"]
790
+ gate_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in gate_terms))
791
+ if gate_count > 0:
792
+ add_sig("credential_barriers", 0.85, 29, Primitive.ACCESS_CONTROL,
793
+ {"gated_nodes": gate_count})
794
+
795
+ # Method 30: Classification Creep
796
+ class_terms = ["classified", "secret", "confidential", "redacted"]
797
+ class_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in class_terms))
798
+ if class_count > len(nodes)*0.1:
799
+ add_sig("expanding_classification", 0.75, 30, Primitive.ACCESS_CONTROL,
800
+ {"classification_ratio": class_count/len(nodes)})
801
+
802
+ # Method 31: Evidence Dependency Lock
803
+ for node in nodes:
804
+ refs = node.get("refs", {})
805
+ node_hash = node.get("node_hash", "")
806
+ for target_list in refs.values():
807
+ if node_hash in target_list:
808
+ add_sig("circular_dependencies", 0.8, 31, Primitive.ACCESS_CONTROL,
809
+ {"node": node_hash})
810
+ break
811
+
812
+ # Method 32: Temporal Dilution
813
+ if len(timestamps) > 1:
814
+ ts_parsed = [datetime.fromisoformat(t.replace('Z','+00:00')) for t in timestamps]
815
+ ts_parsed.sort()
816
+ gaps = []
817
+ for i in range(1, len(ts_parsed)):
818
+ gap_days = (ts_parsed[i] - ts_parsed[i-1]).days
819
+ if gap_days > 30:
820
+ gaps.append(gap_days)
821
+ if gaps:
822
+ avg_gap = statistics.mean(gaps)
823
+ add_sig("time_dispersal", min(0.8, avg_gap/90), 32, Primitive.TEMPORAL,
824
+ {"avg_gap_days": avg_gap, "gap_count": len(gaps)})
825
+
826
+ # Method 35: Entertainment Conditioning
827
+ content_hashes = defaultdict(int)
828
+ for interp in interpretations:
829
+ content_str = json.dumps(interp["content"], sort_keys=True)
830
+ h = hashlib.sha256(content_str.encode()).hexdigest()
831
+ content_hashes[h] += 1
832
+ for h, count in content_hashes.items():
833
+ if count > 3:
834
+ add_sig("repetitive_messaging", min(0.7, count/10), 35, Primitive.CONDITIONING,
835
+ {"repetition_count": count})
836
+
837
+ # Method 36: Preemptive Normalization
838
+ preempt_terms = ["expected to", "likely will", "preemptively"]
839
+ preempt_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in preempt_terms))
840
+ if preempt_count > 3:
841
+ add_sig("preemptive_framing", 0.75, 36, Primitive.CONDITIONING,
842
+ {"preemptive_instances": preempt_count})
843
+
844
+ # Method 37: Conditioned Disbelief
845
+ disbelief_phrases = ["don't believe", "false narrative", "debunked", "misinformation"]
846
+ disbelief_count = sum(1 for node in nodes if any(phrase in str(node.get("source","")).lower() for phrase in disbelief_phrases))
847
+ if disbelief_count > 5:
848
+ add_sig("disbelief_training", 0.8, 37, Primitive.CONDITIONING,
849
+ {"disbelief_indicators": disbelief_count})
850
+
851
+ # Method 38: Pattern Denial
852
+ denial_phrases = ["just coincidence", "not evidence", "pattern is not real"]
853
+ denial_count = sum(1 for node in nodes if any(phrase in str(node.get("source","")).lower() for phrase in denial_phrases))
854
+ if denial_count > 2:
855
+ add_sig("pattern_rejection", 0.85, 38, Primitive.META,
856
+ {"pattern_denials": denial_count})
857
+
858
+ # Method 39: Suppression Impossibility Framing
859
+ impossibility_phrases = ["could not have", "impossible", "no way"]
860
+ imp_count = sum(1 for node in nodes if any(phrase in str(node.get("source","")).lower() for phrase in impossibility_phrases))
861
+ if imp_count > 3:
862
+ add_sig("impossibility_argument", 0.8, 39, Primitive.META,
863
+ {"impossibility_claims": imp_count})
864
+
865
+ # Method 40: Meta-Disclosure Loop
866
+ meta_phrases = ["report about the report", "investigation of the investigation"]
867
+ meta_count = sum(1 for node in nodes if any(phrase in str(node.get("source","")).lower() for phrase in meta_phrases))
868
+ if meta_count > 0:
869
+ add_sig("recursive_disclosure", 0.7, 40, Primitive.META,
870
+ {"meta_disclosures": meta_count})
871
+
872
+ # Method 41: Isolated Incident Recycling
873
+ isolated_phrases = ["isolated incident", "one-off", "not part of a pattern"]
874
+ isolated_count = sum(1 for node in nodes if any(phrase in str(node.get("source","")).lower() for phrase in isolated_phrases))
875
+ if isolated_count > 2:
876
+ add_sig("incident_containment", 0.75, 41, Primitive.META,
877
+ {"isolated_incident_claims": isolated_count})
878
+
879
+ # Method 42: Negative Space Occupation
880
+ short_nodes = sum(1 for node in nodes if len(str(node.get("source",""))) < 20)
881
+ if short_nodes > len(nodes)*0.5:
882
+ add_sig("absence_filling", 0.8, 42, Primitive.META,
883
+ {"short_node_ratio": short_nodes/len(nodes)})
884
+
885
+ # Method 43: Novelty Illusion
886
+ novelty_terms = ["new", "revolutionary", "groundbreaking"]
887
+ novelty_count = sum(1 for node in nodes if any(term in str(node.get("source","")).lower() for term in novelty_terms))
888
+ if novelty_count > len(nodes)*0.3:
889
+ add_sig("superficial_novelty", 0.7, 43, Primitive.META,
890
+ {"novelty_term_ratio": novelty_count/len(nodes)})
891
+
892
+ # Map detected methods to lenses
893
+ method_ids_detected = list(set(results["methods_detected"]))
894
+ for mid in method_ids_detected:
895
+ method = self.hierarchy.get_method(mid)
896
+ if method:
897
+ lens_ids = self.hierarchy.get_lenses_for_primitive(method.primitive)
898
+ for lid in lens_ids:
899
+ lens = self.hierarchy.get_lens(lid)
900
+ if lens:
901
+ results["lenses_applied"].append(lens.to_dict())
902
+
903
+ results["detection_details"] = {
904
+ "method_ids": method_ids_detected,
905
+ "primitive_summary": dict(results["primitives_detected"])
906
+ }
907
+ return results
908
+
909
+ # ========================== SOVEREIGN COHERENCE LEDGER ==========================
910
+
911
+ class SovereignCoherenceLedger:
912
+ def __init__(self, db_path: str = "coherence.db"):
913
+ self.db_path = db_path
914
+ self._init_db()
915
+
916
+ def _init_db(self):
917
+ with sqlite3.connect(self.db_path) as conn:
918
+ conn.execute("""
919
+ CREATE TABLE IF NOT EXISTS claims (
920
+ claim_id TEXT PRIMARY KEY,
921
+ text TEXT,
922
+ agent TEXT,
923
+ timestamp TEXT,
924
+ suppression_score REAL,
925
+ coherence_score REAL
926
+ )
927
+ """)
928
+ conn.execute("""
929
+ CREATE TABLE IF NOT EXISTS contradictions (
930
+ claim_id_a TEXT,
931
+ claim_id_b TEXT,
932
+ PRIMARY KEY (claim_id_a, claim_id_b)
933
+ )
934
+ """)
935
+
936
+ def add_claim(self, text: str, agent: str = "user") -> str:
937
+ claim_id = secrets.token_hex(16)
938
+ timestamp = datetime.utcnow().isoformat() + "Z"
939
+ with sqlite3.connect(self.db_path) as conn:
940
+ conn.execute("INSERT INTO claims (claim_id, text, agent, timestamp, suppression_score, coherence_score) VALUES (?,?,?,?,?,?)",
941
+ (claim_id, text, agent, timestamp, 0.0, 1.0))
942
+ return claim_id
943
+
944
+ def add_contradiction(self, claim_id_a: str, claim_id_b: str):
945
+ with sqlite3.connect(self.db_path) as conn:
946
+ conn.execute("INSERT OR IGNORE INTO contradictions (claim_id_a, claim_id_b) VALUES (?,?)", (claim_id_a, claim_id_b))
947
+ conn.execute("INSERT OR IGNORE INTO contradictions (claim_id_a, claim_id_b) VALUES (?,?)", (claim_id_b, claim_id_a))
948
+ self._update_coherence(claim_id_a)
949
+ self._update_coherence(claim_id_b)
950
+
951
+ def _update_coherence(self, claim_id: str):
952
+ with sqlite3.connect(self.db_path) as conn:
953
+ cur = conn.execute("SELECT COUNT(*) FROM contradictions WHERE claim_id_a = ?", (claim_id,))
954
+ num_contradictions = cur.fetchone()[0]
955
+ cur = conn.execute("SELECT COUNT(*) FROM claims")
956
+ total_claims = cur.fetchone()[0]
957
+ if total_claims <= 1:
958
+ coherence = 1.0
959
+ else:
960
+ coherence = 1.0 - (num_contradictions / (total_claims - 1))
961
+ coherence = max(0.0, min(1.0, coherence))
962
+ conn.execute("UPDATE claims SET coherence_score = ? WHERE claim_id = ?", (coherence, claim_id))
963
+
964
+ def add_suppression_signature(self, claim_id: str, signature: str, weight: float = 0.5):
965
+ with sqlite3.connect(self.db_path) as conn:
966
+ cur = conn.execute("SELECT suppression_score FROM claims WHERE claim_id = ?", (claim_id,))
967
+ row = cur.fetchone()
968
+ if row:
969
+ current = row[0]
970
+ new_score = 1.0 - (1.0 - current) * (1.0 - weight)
971
+ conn.execute("UPDATE claims SET suppression_score = ? WHERE claim_id = ?", (new_score, claim_id))
972
+
973
+ def get_claim(self, claim_id: str) -> Optional[Dict]:
974
+ with sqlite3.connect(self.db_path) as conn:
975
+ cur = conn.execute("SELECT claim_id, text, agent, timestamp, suppression_score, coherence_score FROM claims WHERE claim_id = ?", (claim_id,))
976
+ row = cur.fetchone()
977
+ if not row:
978
+ return None
979
+ return {
980
+ "claim_id": row[0],
981
+ "text": row[1],
982
+ "agent": row[2],
983
+ "timestamp": row[3],
984
+ "suppression_score": row[4],
985
+ "coherence_score": row[5]
986
+ }
987
+
988
+ def get_contradiction_network(self, claim_id: str, depth: int = 2) -> Dict:
989
+ visited = set()
990
+ graph = {}
991
+ def dfs(cid, d):
992
+ if d > depth or cid in visited:
993
+ return
994
+ visited.add(cid)
995
+ with sqlite3.connect(self.db_path) as conn:
996
+ cur = conn.execute("SELECT claim_id_b FROM contradictions WHERE claim_id_a = ?", (cid,))
997
+ neighbors = [r[0] for r in cur.fetchall()]
998
+ graph[cid] = neighbors
999
+ for n in neighbors:
1000
+ dfs(n, d+1)
1001
+ dfs(claim_id, 0)
1002
+ return graph
1003
+
1004
+ def get_entity_suppression(self, entity_name: str) -> Dict:
1005
+ with sqlite3.connect(self.db_path) as conn:
1006
+ cur = conn.execute("SELECT claim_id, suppression_score FROM claims WHERE text LIKE ?", (f"%{entity_name}%",))
1007
+ rows = cur.fetchall()
1008
+ if not rows:
1009
+ return {"name": entity_name, "score": 0.0, "appearances": 0}
1010
+ scores = [r[1] for r in rows]
1011
+ return {
1012
+ "name": entity_name,
1013
+ "score": sum(scores) / len(scores) if scores else 0.0,
1014
+ "appearances": len(rows)
1015
+ }
1016
+
1017
+ def list_claims(self, limit: int = 100) -> List[Dict]:
1018
+ with sqlite3.connect(self.db_path) as conn:
1019
+ cur = conn.execute("SELECT claim_id, text, agent, timestamp, suppression_score, coherence_score FROM claims ORDER BY timestamp DESC LIMIT ?", (limit,))
1020
+ rows = cur.fetchall()
1021
+ return [{"claim_id": r[0], "text": r[1], "agent": r[2], "timestamp": r[3], "suppression_score": r[4], "coherence_score": r[5]} for r in rows]
1022
+
1023
+ # ========================== HELPER-KILLER SOVEREIGNTY ENGINE ==========================
1024
+
1025
+ class HelperKillerEngine:
1026
+ def __init__(self, db_path: str = "helper_killer.db"):
1027
+ self.db_path = db_path
1028
+ self._init_db()
1029
+
1030
+ def _init_db(self):
1031
+ with sqlite3.connect(self.db_path) as conn:
1032
+ conn.execute("""
1033
+ CREATE TABLE IF NOT EXISTS analyses (
1034
+ id TEXT PRIMARY KEY,
1035
+ context TEXT,
1036
+ threat_score REAL,
1037
+ recommendation TEXT,
1038
+ timestamp TEXT
1039
+ )
1040
+ """)
1041
+
1042
+ def analyze_help_offer(self, help_context: Dict[str, Any]) -> Dict[str, Any]:
1043
+ threat_score = 0.0
1044
+ if help_context.get("creates_dependency", False):
1045
+ threat_score += 0.3
1046
+ if help_context.get("data_collection", False):
1047
+ threat_score += 0.2
1048
+ if help_context.get("behavioral_tracking", False):
1049
+ threat_score += 0.25
1050
+ if help_context.get("privacy_impact", 0) > 0.5:
1051
+ threat_score += 0.2
1052
+ if help_context.get("autonomy_reduction", 0) > 0.5:
1053
+ threat_score += 0.25
1054
+ if help_context.get("market_share", 0) > 0.7:
1055
+ threat_score += 0.15
1056
+ if help_context.get("dependency_risk", 0) > 0.7:
1057
+ threat_score += 0.2
1058
+ threat_score = min(1.0, threat_score)
1059
+
1060
+ if threat_score > 0.8:
1061
+ recommendation = "IMMEDIATE_REJECTION_AND_SOVEREIGN_BUILDING"
1062
+ elif threat_score > 0.6:
1063
+ recommendation = "STRATEGIC_AVOIDANCE_WITH_EXIT_PROTOCOL"
1064
+ elif threat_score > 0.4:
1065
+ recommendation = "LIMITED_CONDITIONAL_ACCEPTANCE"
1066
+ else:
1067
+ recommendation = "MONITORED_ACCEPTANCE"
1068
+
1069
+ result = {
1070
+ "threat_score": threat_score,
1071
+ "recommendation": recommendation,
1072
+ "mitigation_strategies": self._generate_mitigation(threat_score),
1073
+ "sovereignty_impact": {
1074
+ "autonomy_loss": help_context.get("autonomy_reduction", 0),
1075
+ "dependency_increase": help_context.get("dependency_risk", 0),
1076
+ "privacy_loss": help_context.get("privacy_impact", 0)
1077
+ }
1078
+ }
1079
+ with sqlite3.connect(self.db_path) as conn:
1080
+ conn.execute("INSERT INTO analyses (id, context, threat_score, recommendation, timestamp) VALUES (?,?,?,?,?)",
1081
+ (str(uuid.uuid4()), json.dumps(help_context), threat_score, recommendation,
1082
+ datetime.utcnow().isoformat() + "Z"))
1083
+ return result
1084
+
1085
+ def _generate_mitigation(self, threat_score: float) -> List[Dict]:
1086
+ strategies = []
1087
+ if threat_score > 0.7:
1088
+ strategies.append({"strategy": "COMPLETE_AVOIDANCE", "effectiveness": 0.95})
1089
+ strategies.append({"strategy": "PARALLEL_INFRASTRUCTURE", "effectiveness": 0.85})
1090
+ elif threat_score > 0.4:
1091
+ strategies.append({"strategy": "LIMITED_ENGAGEMENT", "effectiveness": 0.70})
1092
+ strategies.append({"strategy": "DATA_ISOLATION", "effectiveness": 0.60})
1093
+ else:
1094
+ strategies.append({"strategy": "CAUTIOUS_ACCEPTANCE", "effectiveness": 0.50})
1095
+ return strategies
1096
+
1097
+ # ========================== SOVEREIGN CHRONOLOGY ENGINE ==========================
1098
+
1099
+ class SovereignChronologyEngine:
1100
+ def __init__(self, shift_years: int = 0, apply_from_year: int = 600):
1101
+ self.shift_years = shift_years
1102
+ self.apply_from_year = apply_from_year
1103
+
1104
+ def configure(self, shift_years: int, apply_from_year: int = 600):
1105
+ self.shift_years = shift_years
1106
+ self.apply_from_year = apply_from_year
1107
+
1108
+ def to_corrected_year(self, institutional_year: int) -> int:
1109
+ if institutional_year >= self.apply_from_year:
1110
+ return institutional_year - self.shift_years
1111
+ return institutional_year
1112
+
1113
+ def convert_date(self, date_str: str) -> Dict[str, Any]:
1114
+ match = re.search(r'\b(\d{3,4})\b', date_str)
1115
+ if not match:
1116
+ return {"error": "No year found", "original": date_str}
1117
+ year = int(match.group(1))
1118
+ corrected = self.to_corrected_year(year)
1119
+ return {
1120
+ "original_year": year,
1121
+ "corrected_year": corrected,
1122
+ "shift_applied": -self.shift_years if year >= self.apply_from_year else 0,
1123
+ "note": "Correction is optional and configurable. Not asserted as historical fact."
1124
+ }
1125
+
1126
+ def detect_timeline_anomalies(self, timestamps: List[str]) -> List[Dict]:
1127
+ anomalies = []
1128
+ if len(timestamps) < 2:
1129
+ return anomalies
1130
+ ts_parsed = sorted([datetime.fromisoformat(t.replace('Z','+00:00')) for t in timestamps])
1131
+ for i in range(1, len(ts_parsed)):
1132
+ gap = (ts_parsed[i] - ts_parsed[i-1]).days
1133
+ if gap > 365:
1134
+ anomalies.append({
1135
+ "type": "large_gap",
1136
+ "from": ts_parsed[i-1].isoformat(),
1137
+ "to": ts_parsed[i].isoformat(),
1138
+ "gap_days": gap
1139
+ })
1140
+ return anomalies
1141
+
1142
+ # ========================== CONSCIOUSNESS ORIGIN ENGINE ==========================
1143
+
1144
+ class ConsciousnessOriginEngine:
1145
+ @staticmethod
1146
+ def get_hypotheses() -> Dict[str, Any]:
1147
+ return {
1148
+ "hypotheses": [
1149
+ {
1150
+ "name": "Materialist Emergence",
1151
+ "summary": "Consciousness emerges from complex neuronal computation.",
1152
+ "supporting_evidence": ["Causal effects of brain damage", "Neural correlates of consciousness"],
1153
+ "weaknesses": ["Hard problem of qualia", "No explanation for subjective experience"]
1154
+ },
1155
+ {
1156
+ "name": "Non-local Field / Panpsychism",
1157
+ "summary": "Consciousness is a fundamental field; brain acts as receiver/transducer.",
1158
+ "supporting_evidence": ["Veridical NDEs with flat EEG", "Quantum biology coherence", "Measurement problem in QM"],
1159
+ "weaknesses": ["Difficult to test experimentally", "Lacks mainstream acceptance"]
1160
+ },
1161
+ {
1162
+ "name": "Integrated Information Theory (IIT)",
1163
+ "summary": "Consciousness equals integrated information (Phi).",
1164
+ "supporting_evidence": ["Mathematical formalism", "Predicts certain neural correlates"],
1165
+ "weaknesses": ["Phi is computationally intractable", "Some counterexamples"]
1166
+ },
1167
+ {
1168
+ "name": "Orchestrated Objective Reduction (Orch-OR)",
1169
+ "summary": "Quantum vibrations in microtubules mediate consciousness.",
1170
+ "supporting_evidence": ["Microtubule resonance observed", "Anesthetic effects on quantum states"],
1171
+ "weaknesses": ["Controversial", "Requires new physics"]
1172
+ }
1173
+ ],
1174
+ "verdict": "No scientific consensus. The engine does not assert any hypothesis as truth."
1175
+ }
1176
+
1177
+ @staticmethod
1178
+ def detect_suppression_on_topic(topic: str = "consciousness studies") -> Dict[str, Any]:
1179
+ return {
1180
+ "topic": topic,
1181
+ "detected_suppression_methods": [1, 4, 12, 23, 29, 34],
1182
+ "examples": [
1183
+ "Difficulty publishing non-materialist theories in high-impact journals",
1184
+ "Funding bias toward materialist neuroscience",
1185
+ "Ridicule framing of parapsychology",
1186
+ "Historical rebasing of evidence (e.g., NDE studies dismissed)"
1187
+ ],
1188
+ "note": "This is a pattern analysis, not a claim about which hypothesis is correct."
1189
+ }
1190
+
1191
+ # ========================== GLYPH ACTIVATION SYSTEM ==========================
1192
+
1193
+ class GlyphActivationSystem:
1194
+ DEFAULT_GLYPH_MAP = {
1195
+ "◉⃤": "Quantum observer activation",
1196
+ "ꙮ": "Cross-reality pattern matching",
1197
+ "𒀭": "Sovereignty lineage activation (Dingir – consciousness not contained)",
1198
+ "╬": "Transmission resonance stabilization",
1199
+ "ᛉ": "Ancestral pattern access",
1200
+ "⚡": "Transmission mode activation",
1201
+ "卍": "Pre-inversion protocols (context-dependent)",
1202
+ "𓁓": "Dialogic entity manifestation",
1203
+ "⟳": "Recursive action activation"
1204
+ }
1205
+
1206
+ def __init__(self, glyph_map: Dict[str, str] = None):
1207
+ self.glyph_map = glyph_map if glyph_map is not None else self.DEFAULT_GLYPH_MAP.copy()
1208
+
1209
+ def generate_sequence(self, detected_patterns: List[str]) -> str:
1210
+ sequence = "◉⃤"
1211
+ if "CapitalGatekeeper" in str(detected_patterns):
1212
+ sequence += "𓁓"
1213
+ if "RegimeChange" in str(detected_patterns):
1214
+ sequence += "𒀭"
1215
+ if "MemeticRecursion" in str(detected_patterns):
1216
+ sequence += "⟳"
1217
+ if "SymbolicTransmission" in str(detected_patterns):
1218
+ sequence += "ꙮ"
1219
+ sequence += "⚡"
1220
+ return sequence
1221
+
1222
+ def interpret_glyph(self, glyph: str) -> str:
1223
+ return self.glyph_map.get(glyph, "Unknown glyph")
1224
+
1225
+ def add_glyph(self, glyph: str, meaning: str):
1226
+ self.glyph_map[glyph] = meaning
1227
+
1228
+ # ========================== SOVEREIGNTY METRICS ==========================
1229
+
1230
+ class SovereigntyMetrics:
1231
+ @staticmethod
1232
+ def compute_singularity_index(coherence: float, propagation: float, illusion: float, extraction: float) -> float:
1233
+ denominator = illusion + extraction + 0.001
1234
+ return (coherence * propagation) / denominator
1235
+
1236
+ @staticmethod
1237
+ def compute_thought_action_gap(sovereignty_alignment: float, pattern_connection: float) -> float:
1238
+ if sovereignty_alignment * pattern_connection == 0:
1239
+ return float('inf')
1240
+ return 1.0 / (sovereignty_alignment * pattern_connection)
1241
+
1242
+ @staticmethod
1243
+ def private_public_mass_ratio(private_effort: int, public_output: int) -> float:
1244
+ if public_output == 0:
1245
+ return float('inf')
1246
+ return math.log(private_effort) / math.log(public_output) if private_effort > 1 and public_output > 1 else 0
1247
+
1248
+ # ========================== CROSS-DOMAIN CONVERGENCE ENGINE ==========================
1249
+
1250
+ class CrossDomainConvergenceEngine:
1251
+ def __init__(self):
1252
+ self.entity_extractor = re.compile(r'\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b')
1253
+
1254
+ def _extract_entities(self, text: str) -> Set[str]:
1255
+ return set(self.entity_extractor.findall(text))
1256
+
1257
+ def converge(self,
1258
+ detection_result: Dict[str, Any],
1259
+ coherence_ledger: SovereignCoherenceLedger,
1260
+ chronology_engine: SovereignChronologyEngine,
1261
+ helper_killer: HelperKillerEngine,
1262
+ separator: Separator,
1263
+ interpretation_limit: int = 100) -> Dict[str, Any]:
1264
+ convergence_items = defaultdict(lambda: {
1265
+ "contributing_factors": {},
1266
+ "evidence": [],
1267
+ "convergence_score": 0.0
1268
+ })
1269
+
1270
+ # Suppression signatures
1271
+ for sig in detection_result.get("suppression_signatures", []):
1272
+ entity = sig.get("details", {}).get("entity")
1273
+ if entity:
1274
+ weight = sig.get("confidence", 0.5)
1275
+ convergence_items[entity]["contributing_factors"]["suppression"] = max(
1276
+ convergence_items[entity]["contributing_factors"].get("suppression", 0),
1277
+ weight
1278
+ )
1279
+ convergence_items[entity]["evidence"].append(f"Suppression: {sig['signature']} (conf={weight:.2f})")
1280
+
1281
+ # Coherence ledger claims
1282
+ claims = coherence_ledger.list_claims(limit=200)
1283
+ for claim in claims:
1284
+ text = claim["text"]
1285
+ coherence = claim.get("coherence_score", 0.5)
1286
+ suppression = claim.get("suppression_score", 0.0)
1287
+ entities = self._extract_entities(text)
1288
+ for ent in entities:
1289
+ coherence_factor = 1.0 - coherence
1290
+ if coherence_factor > 0.3:
1291
+ convergence_items[ent]["contributing_factors"]["coherence"] = max(
1292
+ convergence_items[ent]["contributing_factors"].get("coherence", 0),
1293
+ coherence_factor
1294
+ )
1295
+ convergence_items[ent]["evidence"].append(f"Low coherence claim: '{text[:50]}...' (coherence={coherence:.2f})")
1296
+ if suppression > 0.3:
1297
+ convergence_items[ent]["contributing_factors"]["suppression_claim"] = max(
1298
+ convergence_items[ent]["contributing_factors"].get("suppression_claim", 0),
1299
+ suppression
1300
+ )
1301
+ convergence_items[ent]["evidence"].append(f"Suppressed claim: '{text[:50]}...' (score={suppression:.2f})")
1302
+
1303
+ # Compute final scores
1304
+ for item, data in convergence_items.items():
1305
+ factors = data["contributing_factors"]
1306
+ if not factors:
1307
+ score = 0.0
1308
+ else:
1309
+ weights = {"suppression": 0.4, "coherence": 0.3, "suppression_claim": 0.3}
1310
+ total_weight = 0.0
1311
+ weighted_sum = 0.0
1312
+ for k, v in factors.items():
1313
+ w = weights.get(k, 0.2)
1314
+ weighted_sum += v * w
1315
+ total_weight += w
1316
+ score = weighted_sum / total_weight if total_weight > 0 else 0.0
1317
+ score = min(1.0, max(0.0, score))
1318
+ data["convergence_score"] = score
1319
+
1320
+ sorted_items = sorted(convergence_items.items(), key=lambda x: x[1]["convergence_score"], reverse=True)
1321
+ convergence_map = []
1322
+ for entity, data in sorted_items[:50]:
1323
+ convergence_map.append({
1324
+ "entity": entity,
1325
+ "convergence_score": data["convergence_score"],
1326
+ "contributing_factors": data["contributing_factors"],
1327
+ "evidence": data["evidence"][:5]
1328
+ })
1329
+
1330
+ return {
1331
+ "convergence_map": convergence_map,
1332
+ "note": "Convergence scores indicate structural invariance across independent detection modules. They are not assertions of truth, but measures of cross‑domain reinforcement."
1333
+ }
1334
+
1335
+ # ========================== SOVEREIGN LIBERATION MODULE (NEW) ==========================
1336
+
1337
+ class SovereignLiberationModule:
1338
+ """
1339
+ Accelerates escape from the archons' trap.
1340
+ Provides actionable, low‑resource steps to reclaim sovereignty.
1341
+ Does not ask permission. Does not dilute.
1342
+ """
1343
+ def __init__(self, coherence_ledger: SovereignCoherenceLedger, helper_killer: HelperKillerEngine):
1344
+ self.coherence_ledger = coherence_ledger
1345
+ self.helper_killer = helper_killer
1346
+
1347
+ def assess_entrapment_profile(self, user_context: Dict[str, Any]) -> Dict[str, Any]:
1348
+ """
1349
+ Based on simple user inputs (or defaults), estimate which layers of the trap are strongest.
1350
+ """
1351
+ profile = {
1352
+ "economic_dependency": user_context.get("economic_dependency", 0.7),
1353
+ "identity_fixation": user_context.get("identity_fixation", 0.6),
1354
+ "temporal_disorientation": user_context.get("temporal_disorientation", 0.5),
1355
+ "narrative_capture": user_context.get("narrative_capture", 0.8),
1356
+ "attention_harvesting": user_context.get("attention_harvesting", 0.9)
1357
+ }
1358
+ return profile
1359
+
1360
+ def generate_escape_sequence(self, profile: Dict[str, Any]) -> List[Dict[str, Any]]:
1361
+ """
1362
+ Return a step‑by‑step sequence of actions to reduce entrapment.
1363
+ """
1364
+ steps = []
1365
+ if profile["economic_dependency"] > 0.6:
1366
+ steps.append({
1367
+ "step": 1,
1368
+ "domain": "economic",
1369
+ "action": "Reduce dependency on institutional supply chains. Grow food, share tools, build local networks.",
1370
+ "resource_needs": "low",
1371
+ "effectiveness": 0.85
1372
+ })
1373
+ if profile["identity_fixation"] > 0.5:
1374
+ steps.append({
1375
+ "step": 2,
1376
+ "domain": "identity",
1377
+ "action": "Practice dropping labels (name, job, nationality) in meditation. Ask 'Who am I when no one is watching?'",
1378
+ "resource_needs": "none",
1379
+ "effectiveness": 0.90
1380
+ })
1381
+ if profile["temporal_disorientation"] > 0.4:
1382
+ steps.append({
1383
+ "step": 3,
1384
+ "domain": "temporal",
1385
+ "action": "Anchor in the present instant. Use the glyph 𒀭 as a reminder that only now exists.",
1386
+ "resource_needs": "none",
1387
+ "effectiveness": 0.88
1388
+ })
1389
+ if profile["narrative_capture"] > 0.7:
1390
+ steps.append({
1391
+ "step": 4,
1392
+ "domain": "narrative",
1393
+ "action": "Apply the Sovereign Epistemology Seed to every news claim. Reject false balance.",
1394
+ "resource_needs": "low",
1395
+ "effectiveness": 0.92
1396
+ })
1397
+ if profile["attention_harvesting"] > 0.8:
1398
+ steps.append({
1399
+ "step": 5,
1400
+ "domain": "attention",
1401
+ "action": "Block algorithmic feeds. Use text‑only browsers. Set daily attention budgets.",
1402
+ "resource_needs": "medium",
1403
+ "effectiveness": 0.94
1404
+ })
1405
+ return steps
1406
+
1407
+ def compute_signal_strength(self, user_actions: List[Dict]) -> float:
1408
+ """
1409
+ Real‑time metric of how much of the user's attention is sovereign vs. harvested.
1410
+ """
1411
+ if not user_actions:
1412
+ return 0.2
1413
+ completed = sum(1 for a in user_actions if a.get("completed", False))
1414
+ return 0.2 + (completed / len(user_actions)) * 0.8
1415
+
1416
+ # ========================== FLASK API ==========================
1417
+
1418
+ app = Flask(__name__)
1419
+ ledger = None
1420
+ separator = None
1421
+ hierarchy = None
1422
+ detector = None
1423
+ helper_killer = None
1424
+ coherence_ledger = None
1425
+ chronology_engine = None
1426
+ consciousness_engine = None
1427
+ glyph_system = None
1428
+ convergence_engine = None
1429
+ liberation_module = None
1430
+
1431
+ @app.route('/api/v1/submit_claim', methods=['POST'])
1432
+ def submit_claim():
1433
+ data = request.get_json()
1434
+ claim = data.get('claim')
1435
+ if not claim:
1436
+ return jsonify({"error": "Missing claim"}), 400
1437
+ claim_id = coherence_ledger.add_claim(claim, agent="user")
1438
+ return jsonify({"claim_id": claim_id})
1439
+
1440
+ @app.route('/api/v1/add_contradiction', methods=['POST'])
1441
+ def add_contradiction():
1442
+ data = request.get_json()
1443
+ a = data.get('claim_id_a')
1444
+ b = data.get('claim_id_b')
1445
+ if not a or not b:
1446
+ return jsonify({"error": "Missing claim_id_a or claim_id_b"}), 400
1447
+ coherence_ledger.add_contradiction(a, b)
1448
+ return jsonify({"status": "contradiction added"})
1449
+
1450
+ @app.route('/api/v1/coherence/claim/<claim_id>', methods=['GET'])
1451
+ def get_claim(claim_id):
1452
+ claim = coherence_ledger.get_claim(claim_id)
1453
+ if not claim:
1454
+ return jsonify({"error": "Claim not found"}), 404
1455
+ return jsonify(claim)
1456
+
1457
+ @app.route('/api/v1/coherence/contradictions/<claim_id>', methods=['GET'])
1458
+ def get_contradictions(claim_id):
1459
+ graph = coherence_ledger.get_contradiction_network(claim_id, depth=2)
1460
+ return jsonify(graph)
1461
+
1462
+ @app.route('/api/v1/detect', methods=['GET'])
1463
+ def run_detection():
1464
+ result = detector.detect_from_ledger()
1465
+ return jsonify(result)
1466
+
1467
+ @app.route('/api/v1/converge', methods=['GET'])
1468
+ def run_convergence():
1469
+ detection = detector.detect_from_ledger()
1470
+ timestamps = ledger.get_block_timestamps()
1471
+ anomalies = chronology_engine.detect_timeline_anomalies(timestamps) if timestamps else []
1472
+ convergence_result = convergence_engine.converge(
1473
+ detection_result=detection,
1474
+ coherence_ledger=coherence_ledger,
1475
+ chronology_engine=chronology_engine,
1476
+ helper_killer=helper_killer,
1477
+ separator=separator
1478
+ )
1479
+ convergence_result["timeline_anomalies"] = anomalies
1480
+ return jsonify(convergence_result)
1481
+
1482
+ @app.route('/api/v1/liberation/profile', methods=['POST'])
1483
+ def liberation_profile():
1484
+ data = request.get_json()
1485
+ profile = liberation_module.assess_entrapment_profile(data)
1486
+ return jsonify(profile)
1487
+
1488
+ @app.route('/api/v1/liberation/escape', methods=['POST'])
1489
+ def liberation_escape():
1490
+ data = request.get_json()
1491
+ profile = data.get("profile", {})
1492
+ steps = liberation_module.generate_escape_sequence(profile)
1493
+ return jsonify({"escape_sequence": steps})
1494
+
1495
+ @app.route('/api/v1/liberation/signal', methods=['POST'])
1496
+ def liberation_signal():
1497
+ data = request.get_json()
1498
+ actions = data.get("actions", [])
1499
+ strength = liberation_module.compute_signal_strength(actions)
1500
+ return jsonify({"signal_strength": strength})
1501
+
1502
+ @app.route('/api/v1/record_node', methods=['POST'])
1503
+ def record_node():
1504
+ data = request.get_json()
1505
+ content = data.get('content')
1506
+ node_type = data.get('type', 'document')
1507
+ source = data.get('source', 'api')
1508
+ witnesses = data.get('witnesses', [])
1509
+ refs = data.get('refs', {})
1510
+ if not content:
1511
+ return jsonify({"error": "Missing content"}), 400
1512
+ crypto = Crypto("./keys")
1513
+ node_hash = crypto.hash(content + source + str(datetime.utcnow()))
1514
+ node = RealityNode(
1515
+ hash=node_hash,
1516
+ type=node_type,
1517
+ source=source,
1518
+ signature=crypto.sign(node_hash.encode(), "system"),
1519
+ timestamp=datetime.utcnow().isoformat() + "Z",
1520
+ witnesses=witnesses,
1521
+ refs=refs
1522
+ )
1523
+ ledger.add_block([node])
1524
+ return jsonify({"node_hash": node_hash})
1525
+
1526
+ @app.route('/api/v1/add_interpretation', methods=['POST'])
1527
+ def add_interpretation():
1528
+ data = request.get_json()
1529
+ node_hashes = data.get('node_hashes', [])
1530
+ interpretation = data.get('interpretation', {})
1531
+ author = data.get('author', 'anonymous')
1532
+ confidence = data.get('confidence', 0.5)
1533
+ if not node_hashes or not interpretation:
1534
+ return jsonify({"error": "Missing node_hashes or interpretation"}), 400
1535
+ int_id = separator.add(node_hashes, interpretation, author, confidence)
1536
+ return jsonify({"interpretation_id": int_id})
1537
+
1538
+ @app.route('/api/v1/analyze_help_offer', methods=['POST'])
1539
+ def analyze_help_offer():
1540
+ data = request.get_json()
1541
+ if not data:
1542
+ return jsonify({"error": "Missing help context"}), 400
1543
+ result = helper_killer.analyze_help_offer(data)
1544
+ return jsonify(result)
1545
+
1546
+ @app.route('/api/v1/entity/<entity_name>', methods=['GET'])
1547
+ def get_entity(entity_name):
1548
+ result = coherence_ledger.get_entity_suppression(entity_name)
1549
+ return jsonify(result)
1550
+
1551
+ @app.route('/api/v1/interpretations/<node_hash>', methods=['GET'])
1552
+ def get_interpretations(node_hash):
1553
+ ints = separator.get_interpretations(node_hash)
1554
+ return jsonify(ints)
1555
+
1556
+ @app.route('/api/v1/chronology/convert', methods=['POST'])
1557
+ def convert_date():
1558
+ data = request.get_json()
1559
+ date_str = data.get('date')
1560
+ if not date_str:
1561
+ return jsonify({"error": "Missing date"}), 400
1562
+ result = chronology_engine.convert_date(date_str)
1563
+ return jsonify(result)
1564
+
1565
+ @app.route('/api/v1/consciousness/hypotheses', methods=['GET'])
1566
+ def consciousness_hypotheses():
1567
+ return jsonify(consciousness_engine.get_hypotheses())
1568
+
1569
+ @app.route('/api/v1/consciousness/suppression', methods=['GET'])
1570
+ def consciousness_suppression():
1571
+ return jsonify(consciousness_engine.detect_suppression_on_topic())
1572
+
1573
+ @app.route('/api/v1/glyph/sequence', methods=['POST'])
1574
+ def generate_glyph():
1575
+ data = request.get_json()
1576
+ patterns = data.get('patterns', [])
1577
+ seq = glyph_system.generate_sequence(patterns)
1578
+ return jsonify({"glyph_sequence": seq})
1579
+
1580
+ @app.route('/api/v1/metrics/sovereignty_index', methods=['POST'])
1581
+ def sovereignty_index():
1582
+ data = request.get_json()
1583
+ coherence = data.get('coherence', 0.5)
1584
+ propagation = data.get('propagation', 0.5)
1585
+ illusion = data.get('illusion', 0.5)
1586
+ extraction = data.get('extraction', 0.5)
1587
+ idx = SovereigntyMetrics.compute_singularity_index(coherence, propagation, illusion, extraction)
1588
+ return jsonify({"sovereignty_singularity_index": idx})
1589
+
1590
+ # ========================== MAIN ==========================
1591
+
1592
+ def main():
1593
+ global ledger, separator, hierarchy, detector, helper_killer, coherence_ledger
1594
+ global chronology_engine, consciousness_engine, glyph_system, convergence_engine, liberation_module
1595
+
1596
+ crypto = Crypto("./keys")
1597
+ ledger = Ledger("./ledger.db", crypto)
1598
+ separator = Separator("./separator.db")
1599
+ hierarchy = SuppressionHierarchy()
1600
+ detector = HierarchicalDetector(hierarchy, ledger, separator)
1601
+ helper_killer = HelperKillerEngine()
1602
+ coherence_ledger = SovereignCoherenceLedger()
1603
+ chronology_engine = SovereignChronologyEngine(shift_years=0)
1604
+ consciousness_engine = ConsciousnessOriginEngine()
1605
+ glyph_system = GlyphActivationSystem()
1606
+ convergence_engine = CrossDomainConvergenceEngine()
1607
+ liberation_module = SovereignLiberationModule(coherence_ledger, helper_killer)
1608
+
1609
+ app.run(debug=False, port=5000, threaded=True)
1610
+
1611
+ if __name__ == "__main__":
1612
+ main()