Initial commit: 2125_GCE project

This commit is contained in:
GlyphRunner System
2026-07-09 12:54:44 -04:00
parent c3a826b65c
commit ae13f78c22
299 changed files with 124289 additions and 1031 deletions
Regular → Executable
-2
View File
@@ -10,7 +10,6 @@ from .cognitive_kernel import (
CognitiveKernel,
get_kernel,
run_gx,
run_symbolic_prompt,
kernel_status,
)
@@ -39,7 +38,6 @@ __all__ = [
"CognitiveKernel",
"get_kernel",
"run_gx",
"run_symbolic_prompt",
"kernel_status",
"SymbolicStep",
"SymbolicPipelineResult",
Binary file not shown.
Binary file not shown.
Binary file not shown.
Regular → Executable
+47 -28
View File
@@ -297,6 +297,13 @@ class CognitiveKernel:
result: Dict[str, Any]
) -> Dict[str, Any]:
"""Compute multi-glyph resonance metrics from execution result.
Uses actual glyph metadata from the registry to compute real resonance scores:
- weight: Based on glyph score and activation state
- lineage_score: From lineage.inheritanceWeight
- contributor_score: From originalMetrics connectivity
- frequency_score: From praw vector magnitude
- grammar_score: From originalMetrics stability
Args:
glyph_ids: List of glyph IDs to compute resonance for
@@ -309,21 +316,50 @@ class CognitiveKernel:
- global_resonance_score: Weighted average across glyphs
- guardrails_triggered: List of guardrail messages
"""
from glyphs import get_super
resonances = {}
scores = []
for glyph_id in glyph_ids:
# Compute 5-dimensional metrics for each glyph
# In real implementation, these would be computed from LAIN trace
# For now, use deterministic stubs based on glyph_id hash
base_score = (hash(glyph_id) % 100) / 100.0
glyph = get_super(glyph_id)
if not glyph:
continue
metrics = glyph.get('originalMetrics', {})
activation = glyph.get('activation', {})
lineage = glyph.get('lineage', {})
praw = glyph.get('praw', {})
# Compute weight from glyph score (max 335) and activation
score = glyph.get('score', 0)
activation_score = activation.get('score', 0)
weight = min(1.0, (score / 335) * 0.7 + (activation_score / 100) * 0.3)
# Compute lineage score from inheritance weight
inheritance_weight = lineage.get('inheritanceWeight', 0)
lineage_score = inheritance_weight
# Compute contributor score from connectivity metric
connectivity = metrics.get('connectivity', 50)
contributor_score = connectivity / 100
# Compute frequency score from praw vector magnitude
praw_values = [praw.get('P', 0), praw.get('R', 0), praw.get('A', 0), praw.get('W', 0)]
praw_magnitude = (sum(v * v for v in praw_values) ** 0.5) / 200
frequency_score = min(1.0, praw_magnitude)
# Compute grammar score from stability metric
stability = metrics.get('stability', 50)
grammar_score = stability / 100
metrics = {
"weight": min(1.0, 0.5 + (hash(f"{glyph_id}_w") % 50) / 100.0),
"lineage_score": min(1.0, 0.4 + (hash(f"{glyph_id}_l") % 60) / 100.0),
"contributor_score": min(1.0, 0.45 + (hash(f"{glyph_id}_c") % 55) / 100.0),
"frequency_score": min(1.0, 0.35 + (hash(f"{glyph_id}_f") % 65) / 100.0),
"grammar_score": min(1.0, 0.4 + (hash(f"{glyph_id}_g") % 60) / 100.0),
"weight": round(weight, 4),
"lineage_score": round(lineage_score, 4),
"contributor_score": round(contributor_score, 4),
"frequency_score": round(frequency_score, 4),
"grammar_score": round(grammar_score, 4),
}
resonances[glyph_id] = metrics
@@ -335,28 +371,11 @@ class CognitiveKernel:
return {
"glyph_ids": glyph_ids,
"resonances": resonances,
"global_resonance_score": min(1.0, global_resonance),
"global_resonance_score": round(min(1.0, global_resonance), 4),
"guardrails_triggered": [],
}
def run_symbolic_prompt(prompt: str, context: dict | None = None) -> str:
"""Thin wrapper around the symbolic pipeline for backward compatibility.
Routes through run_symbolic_pipeline() and returns output_text.
Args:
prompt: User or system prompt text
context: Optional symbolic/cognitive context dict
Returns:
String result from the 8-lane cognition pipeline
"""
from .symbolic_pipeline import run_symbolic_pipeline
result = run_symbolic_pipeline(prompt=prompt, context=context)
return result.output_text
# Global singleton kernel instance
_GLOBAL_KERNEL: Optional[CognitiveKernel] = None
View File
-78
View File
@@ -1,78 +0,0 @@
"""
Safe predicate evaluator for XIC v2 control flow.
Supports simple expressions referencing fused symbol fields and helper functions.
Allowed: comparisons, boolean ops, dominant_contains('glyph://id').
"""
import ast
from typing import Any, Dict
ALLOWED_NODE_TYPES = (
ast.Expression, ast.BoolOp, ast.BinOp, ast.UnaryOp, ast.Compare,
ast.Name, ast.Load, ast.Constant, ast.Call, ast.Attribute,
ast.And, ast.Or, ast.Not,
ast.Gt, ast.Lt, ast.GtE, ast.LtE, ast.Eq, ast.NotEq, ast.In, ast.NotIn
)
def _validate_node(node: ast.AST):
"""Recursively validate AST node is safe for eval."""
if not isinstance(node, ALLOWED_NODE_TYPES):
raise ValueError(f"Unsafe predicate node: {type(node).__name__}")
for child in ast.iter_child_nodes(node):
_validate_node(child)
class DotDict:
"""Helper class that allows dict access via dot notation."""
def __init__(self, data: Dict[str, Any]):
self.__dict__.update(data)
def _build_context(fused: Dict[str, Any], dominant: list):
"""Build safe evaluation context with helpers and fused symbol fields."""
def dominant_contains(glyph_id: str) -> bool:
"""Check if a glyph is in the dominant list."""
return any(g == glyph_id for g, _ in dominant)
safe = {
"dominant_contains": dominant_contains,
"fused": DotDict(fused or {}),
}
return safe
def eval_predicate(
expr: str,
fused: Dict[str, Any] | None = None,
dominant: list | None = None
) -> bool:
"""
Evaluate predicate expression safely.
Example predicates:
"fused.global_resonance_score > 0.7"
"dominant_contains('glyph://entropy') and fused.global_resonance_score > 0.5"
Args:
expr: Predicate expression string
fused: Fused symbol dict with fields like global_resonance_score, glyph_ids
dominant: List of (glyph_id, weight) tuples for dominant glyphs
Returns:
Boolean result of predicate evaluation
"""
if dominant is None:
dominant = []
# Parse and validate AST
try:
expr_ast = ast.parse(expr, mode="eval")
except SyntaxError as e:
raise ValueError(f"Invalid predicate syntax: {e}")
_validate_node(expr_ast)
# Compile and evaluate
compiled = compile(expr_ast, "<predicate>", "eval")
safe_ctx = _build_context(fused or {}, dominant)
try:
return bool(eval(compiled, {}, safe_ctx))
except Exception as e:
raise ValueError(f"Predicate evaluation error: {e}")
Regular → Executable
+5 -4
View File
@@ -6,8 +6,11 @@ Exposes glyph activation and resonance changes as first-class events.
"""
import time
import logging
from typing import Callable, Dict, List, Optional, TypedDict, Literal, Any
logger = logging.getLogger(__name__)
# Event type definitions
EventType = Literal[
"cognition.started",
@@ -61,7 +64,7 @@ class EventBus:
try:
self._subscribers[event_type].remove(handler)
except ValueError:
pass
logger.debug(f"Handler not found for {event_type} during unsubscribe")
def publish(self, event_type: EventType, payload: Dict[str, Any]) -> Event:
"""Create an Event, append to history, and invoke all handlers.
@@ -88,9 +91,7 @@ class EventBus:
try:
handler(event)
except Exception as e:
# Silently catch handler errors to prevent cascade failures
# In production, could log to a logger
pass
logger.warning(f"Event handler error for {event_type}: {e}")
return event
Regular → Executable
+24 -2
View File
@@ -5,9 +5,12 @@ Routes prompts through the LAIN 8-lane cognition kernel with explicit step track
and comprehensive glyph resonance metrics.
"""
import logging
from dataclasses import dataclass, field
from typing import Any, Dict, List, Optional
logger = logging.getLogger(__name__)
@dataclass
class GlyphResonanceMetrics:
@@ -306,6 +309,7 @@ def run_symbolic_pipeline(
# Build telemetry for FedMart integration
try:
from integrations.fedmart.xic_adapter import emit_telemetry
from integrations.fedmart.glyph_telemetry import emit_glyph_activation
import time
from datetime import datetime
@@ -319,6 +323,7 @@ def run_symbolic_pipeline(
]
avg_resonance = fused_symbol.resonance_map.get_average_resonance()
# Emit standard XIC telemetry
telemetry = {
"event_type": "symbolic_pipeline_run",
"timestamp": datetime.utcnow().isoformat() + "Z",
@@ -346,9 +351,26 @@ def run_symbolic_pipeline(
}
emit_telemetry(telemetry)
# Emit glyph activation telemetry for each engaged glyph
if fused_symbol and fused_symbol.glyph_ids:
from glyphs.super_registry import get_super
for glyph_id in fused_symbol.glyph_ids:
glyph = get_super(glyph_id)
if glyph:
superpower_ids = glyph.get("superpowers", [])
specialized_type = glyph.get("specialized_type", "")
metrics = glyph.get("originalMetrics", {})
emit_glyph_activation(
glyph_id=glyph_id,
superpower_ids=superpower_ids,
specialized_type=specialized_type,
metrics=metrics,
context={"run_id": telemetry.get("run_id")}
)
except ImportError:
# FedMart integration optional
pass
logger.debug("FedMart integration not available — telemetry emission skipped")
return SymbolicPipelineResult(
steps=steps,