Implement GlyphOS Cognitive Kernel
Add a system service layer on top of LAIN cognition and Supercharged Glyph Registry: Components: - glyphos/cognitive_kernel.py: CognitiveKernel class + functional API * CognitiveKernel: Main orchestrator with execute_gx(), execute_symbolic() * Result accessors: get_last_result(), get_last_trace(), get_last_fused_symbol() * get_kernel(): Singleton kernel instance * run_gx(): Convenience function for global kernel * kernel_status(): Status introspection - glyphos/__init__.py: Package initialization - tests/test_cognitive_kernel.py: Comprehensive test suite (8 tests, 100% pass) * Kernel initialization and warmup * GX execution and result validation * Result accessor methods * Singleton pattern * Functional API - COGNITIVE_KERNEL.md: Complete documentation Test Results: - 12 registry tests ✅ - 10 glyph bridge tests ✅ - 6 integration suites ✅ - 8 cognitive kernel tests ✅ - Total: 36 tests, 0 failures No breaking changes - all existing tests pass.
This commit is contained in:
@@ -0,0 +1,406 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Tests for GlyphOS Cognitive Kernel
|
||||
|
||||
Tests verify:
|
||||
- CognitiveKernel initialization and warmup
|
||||
- GX execution through LAIN pipeline
|
||||
- Result caching and accessors
|
||||
- Glyph registry integration
|
||||
- Functional API (singleton, run_gx, kernel_status)
|
||||
"""
|
||||
|
||||
import sys
|
||||
import tempfile
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path.cwd()))
|
||||
|
||||
from glyphos.cognitive_kernel import (
|
||||
CognitiveKernel,
|
||||
get_kernel,
|
||||
run_gx,
|
||||
kernel_status,
|
||||
)
|
||||
from gx_cli.main import main as gx_main
|
||||
from glyphs.super_registry import super_stats
|
||||
|
||||
|
||||
def _create_test_gx() -> Path:
|
||||
"""Create a test .gx file for kernel execution tests.
|
||||
|
||||
Returns:
|
||||
Path to compiled .gx file
|
||||
"""
|
||||
# Use sample_code.py as source
|
||||
source = Path("/home/dave/sample_code.py")
|
||||
if not source.exists():
|
||||
raise FileNotFoundError("Sample code not found")
|
||||
|
||||
# Compile to temporary .gx
|
||||
temp_gx = Path(tempfile.gettempdir()) / "test_kernel.gx"
|
||||
|
||||
# Clean up old file
|
||||
if temp_gx.exists():
|
||||
temp_gx.unlink()
|
||||
|
||||
# Compile
|
||||
exit_code = gx_main(["compile", str(source), "-o", str(temp_gx)])
|
||||
if exit_code != 0:
|
||||
raise RuntimeError(f"Compilation failed with exit code {exit_code}")
|
||||
|
||||
if not temp_gx.exists():
|
||||
raise RuntimeError("Compilation did not produce output file")
|
||||
|
||||
return temp_gx
|
||||
|
||||
|
||||
def test_kernel_initialization():
|
||||
"""Test CognitiveKernel initialization."""
|
||||
kernel = CognitiveKernel(auto_load_glyphs=True)
|
||||
|
||||
if kernel is None:
|
||||
print("FAIL: Could not create CognitiveKernel")
|
||||
return False
|
||||
|
||||
if kernel._warmed_up:
|
||||
print("FAIL: Kernel should not be warmed up on initialization")
|
||||
return False
|
||||
|
||||
if kernel._last_result is not None:
|
||||
print("FAIL: Last result should be None initially")
|
||||
return False
|
||||
|
||||
print("PASS: CognitiveKernel initializes correctly")
|
||||
return True
|
||||
|
||||
|
||||
def test_kernel_warmup():
|
||||
"""Test kernel warmup and glyph loading."""
|
||||
kernel = CognitiveKernel(auto_load_glyphs=True)
|
||||
|
||||
kernel.warmup()
|
||||
|
||||
if not kernel._warmed_up:
|
||||
print("FAIL: Kernel not marked as warmed up")
|
||||
return False
|
||||
|
||||
if kernel._startup_time is None:
|
||||
print("FAIL: Startup time not recorded")
|
||||
return False
|
||||
|
||||
if kernel._glyph_stats_cache is None:
|
||||
print("FAIL: Glyph stats not cached")
|
||||
return False
|
||||
|
||||
# Verify glyphs loaded
|
||||
stats = kernel._glyph_stats_cache
|
||||
if stats.get("total_glyphs") != 600:
|
||||
print(f"FAIL: Expected 600 glyphs, got {stats.get('total_glyphs')}")
|
||||
return False
|
||||
|
||||
if not stats.get("loaded"):
|
||||
print("FAIL: Glyph registry not marked as loaded")
|
||||
return False
|
||||
|
||||
print(f"PASS: Kernel warmed up with {stats['total_glyphs']} glyphs")
|
||||
return True
|
||||
|
||||
|
||||
def test_kernel_execute_gx():
|
||||
"""Test kernel GX execution."""
|
||||
kernel = CognitiveKernel(auto_load_glyphs=True)
|
||||
kernel.warmup()
|
||||
|
||||
# Create test .gx file
|
||||
try:
|
||||
gx_path = _create_test_gx()
|
||||
except Exception as e:
|
||||
print(f"FAIL: Could not create test .gx: {e}")
|
||||
return False
|
||||
|
||||
# Execute
|
||||
try:
|
||||
result = kernel.execute_gx(str(gx_path), mode="analyze")
|
||||
except Exception as e:
|
||||
print(f"FAIL: execute_gx raised exception: {e}")
|
||||
return False
|
||||
|
||||
# Verify result structure
|
||||
if result is None:
|
||||
print("FAIL: execute_gx returned None")
|
||||
return False
|
||||
|
||||
required_keys = ["fused_symbol", "diagnostics", "cognition_trace"]
|
||||
for key in required_keys:
|
||||
if key not in result:
|
||||
print(f"FAIL: Missing key in result: {key}")
|
||||
return False
|
||||
|
||||
# Verify fused_symbol
|
||||
fused = result.get("fused_symbol", {})
|
||||
if not fused:
|
||||
print("FAIL: fused_symbol is empty")
|
||||
return False
|
||||
|
||||
if "summary" not in fused:
|
||||
print("FAIL: fused_symbol missing 'summary'")
|
||||
return False
|
||||
|
||||
# Verify diagnostics
|
||||
diags = result.get("diagnostics", {})
|
||||
if not diags:
|
||||
print("FAIL: diagnostics is empty")
|
||||
return False
|
||||
|
||||
print("PASS: kernel.execute_gx() returns valid ExecutionResult")
|
||||
return True
|
||||
|
||||
|
||||
def test_kernel_result_accessors():
|
||||
"""Test result accessor methods."""
|
||||
kernel = CognitiveKernel(auto_load_glyphs=True)
|
||||
kernel.warmup()
|
||||
|
||||
# Initially no result
|
||||
if kernel.get_last_result() is not None:
|
||||
print("FAIL: get_last_result should be None initially")
|
||||
return False
|
||||
|
||||
if kernel.get_last_trace() is not None:
|
||||
print("FAIL: get_last_trace should be None initially")
|
||||
return False
|
||||
|
||||
if kernel.get_last_fused_symbol() is not None:
|
||||
print("FAIL: get_last_fused_symbol should be None initially")
|
||||
return False
|
||||
|
||||
if kernel.get_last_resonance() is not None:
|
||||
print("FAIL: get_last_resonance should be None initially")
|
||||
return False
|
||||
|
||||
# Execute and verify accessors work
|
||||
try:
|
||||
gx_path = _create_test_gx()
|
||||
except Exception as e:
|
||||
print(f"FAIL: Could not create test .gx: {e}")
|
||||
return False
|
||||
|
||||
kernel.execute_gx(str(gx_path))
|
||||
|
||||
# Now check accessors
|
||||
last_result = kernel.get_last_result()
|
||||
if last_result is None:
|
||||
print("FAIL: get_last_result should not be None after execution")
|
||||
return False
|
||||
|
||||
last_trace = kernel.get_last_trace()
|
||||
if last_trace is None:
|
||||
print("FAIL: get_last_trace should not be None after execution")
|
||||
return False
|
||||
|
||||
if not isinstance(last_trace, list):
|
||||
print("FAIL: get_last_trace should return a list")
|
||||
return False
|
||||
|
||||
last_symbol = kernel.get_last_fused_symbol()
|
||||
if last_symbol is None:
|
||||
print("FAIL: get_last_fused_symbol should not be None after execution")
|
||||
return False
|
||||
|
||||
if "summary" not in last_symbol:
|
||||
print("FAIL: fused_symbol should have 'summary'")
|
||||
return False
|
||||
|
||||
last_resonance = kernel.get_last_resonance()
|
||||
if last_resonance is None:
|
||||
print("FAIL: get_last_resonance should not be None after execution")
|
||||
return False
|
||||
|
||||
print("PASS: All result accessors work correctly")
|
||||
return True
|
||||
|
||||
|
||||
def test_kernel_glyph_stats():
|
||||
"""Test glyph statistics retrieval."""
|
||||
kernel = CognitiveKernel(auto_load_glyphs=True)
|
||||
kernel.warmup()
|
||||
|
||||
stats = kernel.get_glyph_stats()
|
||||
|
||||
if stats is None:
|
||||
print("FAIL: get_glyph_stats returned None")
|
||||
return False
|
||||
|
||||
required_keys = ["total_glyphs", "fields_present", "categories", "loaded"]
|
||||
for key in required_keys:
|
||||
if key not in stats:
|
||||
print(f"FAIL: Missing key in glyph_stats: {key}")
|
||||
return False
|
||||
|
||||
if stats["total_glyphs"] != 600:
|
||||
print(f"FAIL: Expected 600 glyphs, got {stats['total_glyphs']}")
|
||||
return False
|
||||
|
||||
if not isinstance(stats["categories"], list):
|
||||
print("FAIL: categories should be a list")
|
||||
return False
|
||||
|
||||
if stats["loaded"] != True:
|
||||
print("FAIL: Registry should be marked as loaded")
|
||||
return False
|
||||
|
||||
if "kernel_startup_time" not in stats:
|
||||
print("FAIL: kernel_startup_time not in stats")
|
||||
return False
|
||||
|
||||
print(f"PASS: get_glyph_stats returns {stats['total_glyphs']} glyphs in {len(stats['categories'])} categories")
|
||||
return True
|
||||
|
||||
|
||||
def test_get_kernel_singleton():
|
||||
"""Test get_kernel() singleton behavior."""
|
||||
kernel1 = get_kernel()
|
||||
kernel2 = get_kernel()
|
||||
|
||||
if kernel1 is None or kernel2 is None:
|
||||
print("FAIL: get_kernel returned None")
|
||||
return False
|
||||
|
||||
if kernel1 is not kernel2:
|
||||
print("FAIL: get_kernel should return same instance")
|
||||
return False
|
||||
|
||||
if not kernel1._warmed_up:
|
||||
print("FAIL: Kernel should be warmed up by get_kernel")
|
||||
return False
|
||||
|
||||
print("PASS: get_kernel returns warmed-up singleton")
|
||||
return True
|
||||
|
||||
|
||||
def test_run_gx_function():
|
||||
"""Test run_gx convenience function."""
|
||||
try:
|
||||
gx_path = _create_test_gx()
|
||||
except Exception as e:
|
||||
print(f"FAIL: Could not create test .gx: {e}")
|
||||
return False
|
||||
|
||||
try:
|
||||
result = run_gx(str(gx_path), mode="analyze")
|
||||
except Exception as e:
|
||||
print(f"FAIL: run_gx raised exception: {e}")
|
||||
return False
|
||||
|
||||
if result is None:
|
||||
print("FAIL: run_gx returned None")
|
||||
return False
|
||||
|
||||
if "fused_symbol" not in result:
|
||||
print("FAIL: Result missing fused_symbol")
|
||||
return False
|
||||
|
||||
kernel = get_kernel()
|
||||
last_result = kernel.get_last_result()
|
||||
if last_result is not result:
|
||||
print("FAIL: run_gx should update kernel's last_result")
|
||||
return False
|
||||
|
||||
print("PASS: run_gx convenience function works")
|
||||
return True
|
||||
|
||||
|
||||
def test_kernel_status_function():
|
||||
"""Test kernel_status() convenience function."""
|
||||
# Reset singleton to test initial state
|
||||
from glyphos import cognitive_kernel
|
||||
cognitive_kernel._GLOBAL_KERNEL = None
|
||||
|
||||
status = kernel_status()
|
||||
|
||||
if status is None:
|
||||
print("FAIL: kernel_status returned None")
|
||||
return False
|
||||
|
||||
required_keys = [
|
||||
"glyph_stats",
|
||||
"last_run_present",
|
||||
"last_mode",
|
||||
"startup_time",
|
||||
"is_warmed_up"
|
||||
]
|
||||
for key in required_keys:
|
||||
if key not in status:
|
||||
print(f"FAIL: Missing key in kernel_status: {key}")
|
||||
return False
|
||||
|
||||
if not status["is_warmed_up"]:
|
||||
print("FAIL: Kernel should be warmed up by kernel_status")
|
||||
return False
|
||||
|
||||
if status["last_run_present"]:
|
||||
print("FAIL: Should not have last_run_present on fresh kernel")
|
||||
return False
|
||||
|
||||
if status["glyph_stats"]["total_glyphs"] != 600:
|
||||
print("FAIL: glyph_stats should have 600 glyphs")
|
||||
return False
|
||||
|
||||
# Execute and verify status updates
|
||||
try:
|
||||
gx_path = _create_test_gx()
|
||||
run_gx(str(gx_path))
|
||||
except Exception as e:
|
||||
print(f"FAIL: Could not execute test: {e}")
|
||||
return False
|
||||
|
||||
status = kernel_status()
|
||||
if not status["last_run_present"]:
|
||||
print("FAIL: Should have last_run_present after execution")
|
||||
return False
|
||||
|
||||
if status["last_mode"] != "analyze":
|
||||
print("FAIL: last_mode should be 'analyze'")
|
||||
return False
|
||||
|
||||
print("PASS: kernel_status correctly reflects kernel state")
|
||||
return True
|
||||
|
||||
|
||||
def main_test():
|
||||
print("[TEST SUITE] test_cognitive_kernel.py")
|
||||
print()
|
||||
|
||||
tests = [
|
||||
("Kernel initialization", test_kernel_initialization),
|
||||
("Kernel warmup", test_kernel_warmup),
|
||||
("Execute GX", test_kernel_execute_gx),
|
||||
("Result accessors", test_kernel_result_accessors),
|
||||
("Glyph stats", test_kernel_glyph_stats),
|
||||
("get_kernel singleton", test_get_kernel_singleton),
|
||||
("run_gx function", test_run_gx_function),
|
||||
("kernel_status function", test_kernel_status_function),
|
||||
]
|
||||
|
||||
passed = 0
|
||||
failed = 0
|
||||
|
||||
for name, test_func in tests:
|
||||
print(f"Running: {name}...", end=" ")
|
||||
try:
|
||||
if test_func():
|
||||
passed += 1
|
||||
else:
|
||||
failed += 1
|
||||
except Exception as e:
|
||||
print(f"FAIL: {e}")
|
||||
failed += 1
|
||||
|
||||
print()
|
||||
print(f"Results: {passed} passed, {failed} failed")
|
||||
|
||||
return 0 if failed == 0 else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main_test())
|
||||
Reference in New Issue
Block a user