import json import re import sys import os if len(sys.argv) < 2: print("Usage: python3 defibrillator.py '/path/to/corrupted_chat.json'") sys.exit(1) file_path = sys.argv[1] if not os.path.exists(file_path): print(f"File not found: {file_path}") sys.exit(1) with open(file_path, 'r', encoding='utf-8') as f: data = json.load(f) chunks = data.get('chunkedPrompt', {}).get('chunks', []) counter = 1 is_inside_hotel = False is_inside_foundation = False for chunk in chunks: if 'parts' in chunk: new_parts = [] for p in chunk['parts']: if 'thoughtSignature' in p or ('text' in p and '[TX_ID:' in p['text']): new_parts.append(p) if new_parts: chunk['parts'] = new_parts else: del chunk['parts'] if 'text' in chunk: text = chunk['text'] # SAFE PURGE: Remove stacked tags ONLY from the very start of the text text = re.sub(r'^(?:\[TURN_\d{4}\]\s*)+', '', text) if text.startswith('[CODE_CUSTODIAN_HOTEL_BEGIN]'): is_inside_hotel = True if text.startswith('[CODE_CUSTODIAN_FOUNDATION_BEGIN]'): is_inside_foundation = True in_restricted_area = is_inside_hotel or is_inside_foundation is_system_chunk = text.startswith('[CODE_CUSTODIAN_') is_lost_image = '[IMAGE LOST DURING WORMHOLE SYNC' in text or '[UNTRACKED IMAGE STRIPPED BY WORMHOLE]' in text if not in_restricted_area and not is_system_chunk and not is_lost_image: tag = f"[TURN_{counter:04d}]" # Prepend the fresh tag chunk['text'] = f"{tag}\n{text}" if 'parts' not in chunk: chunk['parts'] = [] chunk['parts'].insert(0, {"text": tag}) counter += 1 else: chunk['text'] = text if text.startswith('[CODE_CUSTODIAN_HOTEL_END]'): is_inside_hotel = False if text.startswith('[CODE_CUSTODIAN_FOUNDATION_END]'): is_inside_foundation = False with open(file_path, 'w', encoding='utf-8') as f: json.dump(data, f, indent=2, separators=(',', ': '), ensure_ascii=False) print(f"✅ Defibrillator complete. Real conversation re-sequenced from 1 to {counter - 1}.")