#!/usr/bin/env python3 """ Enhanced Compressed Execution Program with Glyph System Integration Compresses Python source code and executes it through the XIC symbolic processor. Uses GSZ3 compression + XIC binary format + LAIN cognition engine + Glyph Superpowers. Features: - Glyph selection and activation - Superpower display and tracking - Power boost calculations - Dual-layer symbolic integration Usage: python3 compress_and_run.py [--mode analyze|debug] [--output output.gx] python3 compress_and_run.py --glyph G001 --activate python3 compress_and_run.py --glyph G001 --show-powers """ import sys import json import time from pathlib import Path from typing import Dict, Any, Optional, List import argparse # Add superdave to path sys.path.insert(0, str(Path(__file__).parent)) from gx_compiler.compressor import GXCompressor from gx_compiler.gx_packer import GXPacker from gx_compiler.segmenter import SourceSegmenter from gx_lain.runtime import execute_gx_path from xic_executor import run_xic from glyphs.super_registry import load_all_supercharged, get_super, list_super_ids from glyphs.superpower_registry import ( load_all_superpowers, calculate_boost, get_superpower_names, super_stats, ) from glyphs.superpower_assigner import assign_superpowers from glyphs.specialized_types import get_specialized_type def compress_source(source_code: str) -> bytes: """Compress source code using GSZ3.""" return GXCompressor.compress(source_code) def create_manifest(source_path: str, segments: list) -> dict: """Create GX manifest with codex_lineage.""" return { "magic": "GXIC1", "version": 1, "source_file": source_path, "source_type": "python", "version_str": "1.0.0", "contributor": "compress_and_run", "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()), "codex_lineage": { "segments": segments, "compression": "gsz3", "formula": "zlib_level9+sha256_trunc3", }, } def segment_source(source_code: str) -> list: """Segment source code and return segment metadata.""" segments = SourceSegmenter.segment(source_code) return [ { "id": seg.segment_id, "start": seg.start_line, "end": seg.end_line, "start_byte": seg.start_byte, "end_byte": seg.end_byte, } for seg in segments ] def build_gx_file(source_path: str, output_path: Optional[str] = None) -> bytes: """Build complete .gx file from Python source. Pipeline: 1. Read source code 2. Segment code 3. Compress with GSZ3 4. Pack with XIC format """ source_path = Path(source_path) if not source_path.exists(): raise FileNotFoundError(f"Source file not found: {source_path}") source_code = source_path.read_text() # Segment the source segments = segment_source(source_code) # Create manifest manifest = create_manifest(str(source_path), segments) # Compress the source code compressed_payload = compress_source(source_code) # Pack into GX format gx_data = GXPacker.pack(manifest, compressed_payload) # Write output if specified if output_path: output_path = Path(output_path) output_path.write_bytes(gx_data) print(f"Created .gx file: {output_path} ({len(gx_data)} bytes)") return gx_data def execute_gx_file(gx_path: str, mode: str = "analyze") -> dict: """Execute a .gx file through LAIN cognition.""" start = time.time() try: result = execute_gx_path(gx_path, context={"cognitive_mode": mode}) elapsed = time.time() - start result["execution_time"] = elapsed return result except Exception as e: elapsed = time.time() - start return { "error": str(e), "execution_time": elapsed, } def execute_compressed(source_path: str, mode: str = "analyze") -> dict: """Compress and execute source in one step.""" source_path = Path(source_path) print(f"Compressing: {source_path}") # Build compressed file (in memory) gx_data = build_gx_file(str(source_path)) # Save to temp file for execution temp_gx = Path("/tmp") / f"temp_{source_path.stem}.gx" temp_gx.write_bytes(gx_data) try: print(f"Executing through LAIN ({mode} mode)...") result = execute_gx_file(str(temp_gx), mode) return result finally: if temp_gx.exists(): temp_gx.unlink() def print_glyph_info(glyph_id: str): """Display glyph information with superpowers and power boost.""" if not glyph_id: return try: load_all_supercharged() load_all_superpowers() glyph = get_super(glyph_id) if not glyph: print(f"Glyph {glyph_id} not found") return metrics = glyph.get("originalMetrics", {}) category = glyph.get("category", "") specialized_type = get_specialized_type(glyph_id, metrics, category) superpower_ids = assign_superpowers(glyph_id, metrics, specialized_type, category) power_boost = calculate_boost(superpower_ids) print(f"\n{'=' * 70}") print(f"GLYPH: {glyph_id} - {glyph.get('name', 'Unknown')}") print(f"{'=' * 70}") print(f"Category: {category}") print(f"Band: {glyph.get('band', 'N/A')}") print(f"Score: {glyph.get('score', 'N/A')}") print(f"Specialized Type: {specialized_type}") print(f"Superpowers: {len(superpower_ids)}") print(f"Power Boost: {power_boost:.2f}x") # Show top superpowers names = get_superpower_names(superpower_ids[:10]) print(f"\nTop 10 Superpowers:") for i, (sp_id, sp_name) in enumerate(zip(superpower_ids[:10], names), 1): print(f" {i}. [{sp_id:3d}] {sp_name}") if len(superpower_ids) > 10: print(f" ... and {len(superpower_ids) - 10} more") except Exception as e: print(f"Error displaying glyph info: {e}") def print_result(result: dict, glyph_id: Optional[str] = None): """Print execution result in human-readable format.""" print("\n" + "=" * 70) print("EXECUTION RESULT") print("=" * 70) if glyph_id: print_glyph_info(glyph_id) if "error" in result: print(f"\n❌ Error: {result['error']}") print(f" Time: {result.get('execution_time', 0):.4f}s") return # Fused symbol fused = result.get("fused_symbol", {}) print(f"\nSummary:") print(f" {fused.get('summary', 'N/A')}") # Key points key_points = fused.get("key_points", []) if key_points: print(f"\nKey Points ({len(key_points)}):") for i, point in enumerate(key_points[:5], 1): print(f" {i}. {point}") # Constraints constraints = fused.get("constraints", []) if constraints: print(f"\nConstraints ({len(constraints)}):") for i, constraint in enumerate(constraints[:3], 1): print(f" {i}. {constraint}") # Open questions questions = fused.get("open_questions", []) if questions: print(f"\nOpen Questions ({len(questions)}):") for i, question in enumerate(questions[:3], 1): print(f" {i}. {question}") # Diagnostics diagnostics = result.get("diagnostics", {}) print(f"\nDiagnostics:") print(f" Time: {result.get('execution_time', 0):.4f}s") print(f" Interface: {diagnostics.get('interface_version', 'N/A')}") # Lane timings lane_timings = diagnostics.get("lane_timings", {}) if lane_timings: print(f"\nLane Timings:") for lane_id in sorted(lane_timings.keys()): print(f" Lane {lane_id}: {lane_timings[lane_id]:.4f}s") # Glyph resonance glyph_res = diagnostics.get("glyph_resonance", {}) if glyph_res.get("glyph_found"): print(f"\nGlyph Resonance:") print(f" Glyph ID: {glyph_res.get('glyph_id', 'N/A')}") print(f" Glyph Score: {glyph_res.get('glyph_score', 'N/A')}") # Output text output_text = result.get("output_text", "") if output_text and output_text.strip(): print(f"\nOutput:") print(output_text) def main(): """Main entry point.""" parser = argparse.ArgumentParser( description="Compress and execute Python code through XIC symbolic processor" ) parser.add_argument( "source", nargs="?", help="Python source file to compress and execute" ) parser.add_argument( "--mode", choices=["analyze", "debug"], default="analyze", help="Cognitive mode (default: analyze)" ) parser.add_argument( "--output", "-o", help="Output .gx file path (optional)" ) parser.add_argument( "--only-compress", action="store_true", help="Only compress, don't execute" ) parser.add_argument( "--glyph", help="Display glyph information (e.g., G001)" ) parser.add_argument( "--activate", action="store_true", help="Activate glyph with all superpowers" ) parser.add_argument( "--show-powers", action="store_true", help="Show all 152 superpowers" ) args = parser.parse_args() # Handle glyph display if args.glyph: load_all_supercharged() load_all_superpowers() glyph = get_super(args.glyph) if not glyph: print(f"Error: Glyph {args.glyph} not found") sys.exit(1) metrics = glyph.get("originalMetrics", {}) category = glyph.get("category", "") specialized_type = get_specialized_type(args.glyph, metrics, category) superpower_ids = assign_superpowers(args.glyph, metrics, specialized_type, category) power_boost = calculate_boost(superpower_ids) print(f"\n{'=' * 70}") print(f"GLYPH: {args.glyph} - {glyph.get('name', 'Unknown')}") print(f"{'=' * 70}") print(f"Category: {category}") print(f"Band: {glyph.get('band', 'N/A')}") print(f"Score: {glyph.get('score', 'N/A')}") print(f"Specialized Type: {specialized_type}") print(f"Superpowers: {len(superpower_ids)}") print(f"Power Boost: {power_boost:.2f}x") # Show superpowers if args.show_powers or len(superpower_ids) <= 20: names = get_superpower_names(superpower_ids) print(f"\nSuperpowers ({len(superpower_ids)}):") for i, (sp_id, sp_name) in enumerate(zip(superpower_ids, names), 1): print(f" {i:3d}. [{sp_id:3d}] {sp_name}") if args.activate: print(f"\n{'=' * 70}") print(f"ACTIVATING GLYPH {args.glyph}") print(f"{'=' * 70}") print(f"✅ Glyph {args.glyph} activated") print(f"✅ {len(superpower_ids)} superpowers loaded") print(f"✅ Power boost: {power_boost:.2f}x") print(f"✅ Specialized type: {specialized_type}") sys.exit(0) # Handle source file if not args.source: parser.print_help() sys.exit(1) source_path = Path(args.source) if not source_path.exists(): print(f"Error: Source file not found: {source_path}") sys.exit(1) try: # Build GX file gx_data = build_gx_file(str(source_path), args.output) if args.only_compress: print("Compression complete. Use --execute to run.") return # Execute result = execute_compressed(str(source_path), args.mode) print_result(result) except Exception as e: print(f"Error: {e}") sys.exit(1) if __name__ == "__main__": main()