150a036604
Complete end-to-end multi-glyph resonance enabling simultaneous analysis of multiple glyphs with cross-glyph resonance metrics, guardrails, and comprehensive telemetry. ## Phase 1: XIC Layer - Context Accumulation ### XICContext Enhancement - Added glyph_contexts: list field for accumulating glyph IDs ### New Operations - PUSH_GLYPH_CONTEXT: accumulate glyph with guardrail enforcement - CLEAR_GLYPH_CONTEXT: reset context for new analysis chains ### Enhanced Existing Operations - CALL_GLYPH: detects populated glyph_contexts, passes glyph_ids to pipeline - RUN_PROMPT: supports multi-glyph context via glyph_ids parameter - STREAM: supports multi-glyph context via glyph_ids parameter ### Guardrail Integration - max_resonance_glyphs (default 10, configurable) - enable_resonance_guardrails (default True) - Enforced at PUSH_GLYPH_CONTEXT to prevent exceeding limit ## Phase 2: Symbolic Pipeline - Multi-Glyph Support ### Extended Signature - run_symbolic_pipeline now accepts glyph_ids parameter - Multi-glyph mode detection and routing - glyph_ids takes precedence over glyph_id if both provided ### Multi-Glyph Processing - SymbolicStep(kind="multi_glyph_resonance") for glyph_ids - SymbolicStep(kind="guardrail") when truncation needed - Guardrail enforcement with pipeline-level truncation to max_resonance_glyphs ### Null-Safety Fixes - extract_glyph_resonances: handles None resonance_map - get_dominant_glyphs: handles None resonance_map - format_glyph_resonance_report: handles None resonance_map ## Phase 3: LAIN Cognitive Kernel - Resonance Computation ### New Method: compute_multi_glyph_resonance - Takes glyph_ids list and execution result - Computes 5-dimensional metrics per glyph: - weight: relative importance [0.0, 1.0] - lineage_score: symbolic ancestry [0.0, 1.0] - contributor_score: contribution to fusion [0.0, 1.0] - frequency_score: occurrence frequency [0.0, 1.0] - grammar_score: structural alignment [0.0, 1.0] - Returns global_resonance_score as weighted average ### Enhanced execute_symbolic - Detects context["glyph_ids"] for multi-glyph mode - Post-processes LAIN result via compute_multi_glyph_resonance - Merges multi-glyph metrics into fused_symbol - Maintains backward compatibility (single-glyph unaffected) ## Phase 4: Guardrails & Telemetry ### Guardrail Enforcement - PUSH_GLYPH_CONTEXT rejects pushes exceeding max_resonance_glyphs - run_symbolic_pipeline truncates glyph_ids if needed - Guardrail step recorded in pipeline with reason message ### Telemetry Collection - ctx._state["last_resonance_stats"] stores: - glyph_count: number of glyphs processed - global_resonance_score: weighted average [0.0, 1.0] - guardrails_triggered: list of guardrail messages - timestamp: execution time ## Phase 5: Validation Suite ### 12 Comprehensive Tests (all passing) 1. New operations in OP_TABLE 2. XICContext.glyph_contexts field 3. PUSH_GLYPH_CONTEXT accumulation 4. CLEAR_GLYPH_CONTEXT reset 5. Guardrail enforcement on PUSH 6. run_symbolic_pipeline signature 7. compute_multi_glyph_resonance method 8. Multi-glyph resonance structure 9. execute_symbolic multi-glyph processing 10. Single-glyph backward compatibility 11. Demo programs validity 12. Multi-glyph demo structure ### Test File: test_multi_glyph_resonance.py - Unit tests for all components - Integration tests for data flow - Backward compatibility validation - Mock-based testing for isolated units ## Phase 6: Documentation ### Updated XIC_SEMANTICS_v1_5.md - Added PUSH_GLYPH_CONTEXT instruction semantics - Added CLEAR_GLYPH_CONTEXT instruction semantics - Added comprehensive Multi-Glyph Resonance section with: - Context accumulation model diagram - Complete workflow documentation - Guardrail specifications - Telemetry format definition - Three-glyph analysis example with JSON/Python output ### Created demo_multi_glyph_resonance.gx.json - Two-chain demonstration program - Chain 1: 3-glyph analysis (compression, entropy, information) - Chain 2: 4-glyph analysis (cognition, language, symbol, meaning) - Shows complete resonance query pipeline - Demonstrates context clearing and reset ### Created XIC_MULTI_GLYPH_RESONANCE_REPORT.md - Comprehensive implementation documentation - All 6 phases detailed with code examples - Architecture overview and data flow diagrams - Design decisions with rationale - Backward compatibility guarantees - Usage examples (CLI, JSON, programmatic) - Future enhancement suggestions ## Key Features ✅ Explicit context accumulation (PUSH_GLYPH_CONTEXT) ✅ Automatic multi-glyph detection in CALL_GLYPH/RUN_PROMPT/STREAM ✅ Guardrails prevent exceeding max_resonance_glyphs ✅ Telemetry tracking for analytics ✅ Full backward compatibility maintained ✅ Single-glyph mode unaffected ✅ Comprehensive validation suite (12/12 tests passing) ✅ Complete formal specification updates ✅ Demo program showcase ## Backward Compatibility - All XIC v1 programs work unchanged - Single-glyph CALL_GLYPH still works identically - Empty glyph_contexts → single-glyph behavior - .gx binary format unchanged - No breaking changes to APIs Co-Authored-By: Claude Haiku 4.5 <noreply@anthropic.com>
311 lines
10 KiB
Python
311 lines
10 KiB
Python
"""Symbolic Pipeline Abstraction for XIC.
|
|
|
|
Provides a structured, glyph-aware pipeline for symbolic cognition execution.
|
|
Routes prompts through the LAIN 8-lane cognition kernel with explicit step tracking
|
|
and comprehensive glyph resonance metrics.
|
|
"""
|
|
|
|
from dataclasses import dataclass, field
|
|
from typing import Any, Dict, List, Optional
|
|
|
|
|
|
@dataclass
|
|
class GlyphResonanceMetrics:
|
|
"""Glyph resonance metrics from LAIN cognition layer."""
|
|
weight: float
|
|
lineage_score: float
|
|
contributor_score: float
|
|
frequency_score: float
|
|
grammar_score: float
|
|
|
|
|
|
@dataclass
|
|
class GlyphResonanceMap:
|
|
"""Maps glyph IDs to their resonance metrics."""
|
|
resonances: Dict[str, GlyphResonanceMetrics] = field(default_factory=dict)
|
|
global_resonance_score: float = 0.0
|
|
|
|
def get_glyph_resonance(self, glyph_id: str) -> Optional[GlyphResonanceMetrics]:
|
|
"""Get resonance metrics for a specific glyph."""
|
|
return self.resonances.get(glyph_id)
|
|
|
|
def get_top_glyphs(self, n: int = 5) -> List[tuple[str, GlyphResonanceMetrics]]:
|
|
"""Get top N glyphs by weight."""
|
|
sorted_glyphs = sorted(
|
|
self.resonances.items(),
|
|
key=lambda x: x[1].weight,
|
|
reverse=True
|
|
)
|
|
return sorted_glyphs[:n]
|
|
|
|
def get_average_resonance(self) -> float:
|
|
"""Get average resonance across all glyphs."""
|
|
if not self.resonances:
|
|
return 0.0
|
|
total = sum(m.weight for m in self.resonances.values())
|
|
return total / len(self.resonances)
|
|
|
|
|
|
@dataclass
|
|
class FusedSymbol:
|
|
"""Fused symbolic representation from LAIN cognition."""
|
|
summary: str
|
|
glyph_ids: List[str] = field(default_factory=list)
|
|
resonance_map: GlyphResonanceMap = field(default_factory=GlyphResonanceMap)
|
|
|
|
@classmethod
|
|
def from_lain_result(cls, lain_fused_symbol: Dict[str, Any]) -> "FusedSymbol":
|
|
"""Parse fused_symbol dict from LAIN result."""
|
|
summary = lain_fused_symbol.get("summary", "")
|
|
glyph_ids = lain_fused_symbol.get("glyph_ids", [])
|
|
|
|
resonance_map = GlyphResonanceMap(
|
|
global_resonance_score=lain_fused_symbol.get("global_resonance_score", 0.0)
|
|
)
|
|
|
|
raw_resonance = lain_fused_symbol.get("resonance_map", {})
|
|
for glyph_id, metrics_dict in raw_resonance.items():
|
|
if isinstance(metrics_dict, dict):
|
|
resonance_map.resonances[glyph_id] = GlyphResonanceMetrics(
|
|
weight=metrics_dict.get("weight", 0.0),
|
|
lineage_score=metrics_dict.get("lineage_score", 0.0),
|
|
contributor_score=metrics_dict.get("contributor_score", 0.0),
|
|
frequency_score=metrics_dict.get("frequency_score", 0.0),
|
|
grammar_score=metrics_dict.get("grammar_score", 0.0),
|
|
)
|
|
|
|
return cls(summary=summary, glyph_ids=glyph_ids, resonance_map=resonance_map)
|
|
|
|
|
|
@dataclass
|
|
class SymbolicStep:
|
|
"""A single step in the symbolic pipeline execution."""
|
|
name: str
|
|
kind: str # "prompt", "glyph_call", "fused_symbol"
|
|
payload: Any
|
|
context: Dict[str, Any] = field(default_factory=dict)
|
|
|
|
|
|
@dataclass
|
|
class SymbolicPipelineResult:
|
|
"""Result of a symbolic pipeline execution."""
|
|
steps: List[SymbolicStep]
|
|
output_text: str
|
|
fused_symbol: Optional[FusedSymbol] = None
|
|
|
|
|
|
def extract_glyph_resonances(
|
|
pipeline_result: "SymbolicPipelineResult",
|
|
) -> Dict[str, Dict[str, Any]]:
|
|
"""Extract glyph resonance metrics from a pipeline result.
|
|
|
|
Returns dict mapping glyph_id → resonance metrics dict.
|
|
"""
|
|
if not pipeline_result.fused_symbol:
|
|
return {}
|
|
|
|
if not pipeline_result.fused_symbol.resonance_map:
|
|
return {}
|
|
|
|
result = {}
|
|
for glyph_id, metrics in pipeline_result.fused_symbol.resonance_map.resonances.items():
|
|
result[glyph_id] = {
|
|
"weight": metrics.weight,
|
|
"lineage_score": metrics.lineage_score,
|
|
"contributor_score": metrics.contributor_score,
|
|
"frequency_score": metrics.frequency_score,
|
|
"grammar_score": metrics.grammar_score,
|
|
}
|
|
|
|
return result
|
|
|
|
|
|
def get_dominant_glyphs(
|
|
pipeline_result: "SymbolicPipelineResult",
|
|
n: int = 3,
|
|
) -> List[tuple[str, float]]:
|
|
"""Get top N glyphs by resonance weight from a pipeline result.
|
|
|
|
Returns list of (glyph_id, weight) tuples sorted by weight descending.
|
|
"""
|
|
if not pipeline_result.fused_symbol:
|
|
return []
|
|
|
|
if not pipeline_result.fused_symbol.resonance_map:
|
|
return []
|
|
|
|
return [
|
|
(glyph_id, metrics.weight)
|
|
for glyph_id, metrics in pipeline_result.fused_symbol.resonance_map.get_top_glyphs(n)
|
|
]
|
|
|
|
|
|
def format_glyph_resonance_report(
|
|
pipeline_result: "SymbolicPipelineResult",
|
|
) -> str:
|
|
"""Format a human-readable glyph resonance report."""
|
|
if not pipeline_result.fused_symbol:
|
|
return "No glyph resonance data."
|
|
|
|
if not pipeline_result.fused_symbol.resonance_map:
|
|
return "No resonance map available."
|
|
|
|
resonance = pipeline_result.fused_symbol.resonance_map
|
|
lines = [
|
|
f"Global Resonance Score: {resonance.global_resonance_score:.3f}",
|
|
f"Glyphs Engaged: {len(resonance.resonances)}",
|
|
"",
|
|
"Top Glyphs by Weight:",
|
|
]
|
|
|
|
for glyph_id, metrics in resonance.get_top_glyphs(5):
|
|
lines.append(
|
|
f" {glyph_id}: weight={metrics.weight:.3f}, "
|
|
f"lineage={metrics.lineage_score:.3f}, "
|
|
f"contributor={metrics.contributor_score:.3f}"
|
|
)
|
|
|
|
return "\n".join(lines)
|
|
|
|
|
|
def run_symbolic_pipeline(
|
|
prompt: str,
|
|
context: Optional[Dict[str, Any]] = None,
|
|
glyph_id: Optional[str] = None,
|
|
glyph_ids: Optional[List[str]] = None,
|
|
) -> SymbolicPipelineResult:
|
|
"""
|
|
High-level symbolic pipeline entrypoint for XIC.
|
|
|
|
Accepts a prompt and optional symbolic/glyph context, routes through
|
|
the LAIN 8-lane cognition kernel via CognitiveKernel.execute_symbolic(),
|
|
and returns a structured SymbolicPipelineResult with execution steps,
|
|
final output text, and fused symbolic representation.
|
|
|
|
Args:
|
|
prompt: User or system prompt text.
|
|
context: Optional dict of symbolic/cognitive context metadata.
|
|
glyph_id: Optional glyph identifier for single-glyph cognition.
|
|
glyph_ids: Optional list of glyph identifiers for multi-glyph resonance.
|
|
|
|
Returns:
|
|
SymbolicPipelineResult with:
|
|
- steps: List of SymbolicStep objects tracking execution flow.
|
|
- output_text: Final text result from cognition layer.
|
|
- fused_symbol: Fused symbolic representation (if produced by LAIN).
|
|
|
|
Notes:
|
|
If both glyph_id and glyph_ids are provided, glyph_ids takes precedence
|
|
for multi-glyph resonance computation.
|
|
"""
|
|
from gx_compiler.compressor import GXCompressor
|
|
from .cognitive_kernel import get_kernel
|
|
|
|
steps: List[SymbolicStep] = []
|
|
kernel = get_kernel()
|
|
prompt_bytes = prompt.encode("utf-8")
|
|
|
|
# Step 1: Initial prompt
|
|
steps.append(SymbolicStep(
|
|
name="initial_prompt",
|
|
kind="prompt",
|
|
payload=prompt,
|
|
context=dict(context or {})
|
|
))
|
|
|
|
# Step 2: Prepare context for glyph-aware processing
|
|
exec_context = dict(context or {})
|
|
guardrails_triggered = []
|
|
|
|
# Multi-glyph resonance takes precedence
|
|
if glyph_ids:
|
|
# Apply guardrails
|
|
max_glyphs = exec_context.get("max_resonance_glyphs", 10)
|
|
if len(glyph_ids) > max_glyphs:
|
|
glyph_ids = glyph_ids[:max_glyphs]
|
|
guardrails_triggered.append(f"Truncated glyph list to {max_glyphs}")
|
|
|
|
exec_context["glyph_ids"] = glyph_ids
|
|
steps.append(SymbolicStep(
|
|
name="multi_glyph_resonance",
|
|
kind="multi_glyph_resonance",
|
|
payload={"glyph_ids": glyph_ids, "count": len(glyph_ids)},
|
|
context=exec_context
|
|
))
|
|
|
|
# Record guardrail step if triggered
|
|
if guardrails_triggered:
|
|
steps.append(SymbolicStep(
|
|
name="guardrail_enforcement",
|
|
kind="guardrail",
|
|
payload={"guardrails": guardrails_triggered},
|
|
context={"max_resonance_glyphs": max_glyphs}
|
|
))
|
|
elif glyph_id:
|
|
exec_context["glyph_id"] = glyph_id
|
|
steps.append(SymbolicStep(
|
|
name=f"glyph:{glyph_id}",
|
|
kind="glyph_call",
|
|
payload=prompt,
|
|
context=exec_context
|
|
))
|
|
|
|
# Step 3: Compress prompt and build manifest
|
|
try:
|
|
payload = GXCompressor.compress(prompt)
|
|
except Exception as e:
|
|
return SymbolicPipelineResult(
|
|
steps=steps,
|
|
output_text=f"[Pipeline Error] Compression failed: {e}",
|
|
fused_symbol=None
|
|
)
|
|
|
|
manifest = {
|
|
"source_file": "<symbolic>",
|
|
"source_type": "symbolic",
|
|
"version": "1.0.0",
|
|
"contributor": "XIC-symbolic",
|
|
"segments": [{"id": "seg_0", "start": 0, "end": 1,
|
|
"start_byte": 0, "end_byte": len(prompt_bytes)}],
|
|
}
|
|
segments = [{"id": "seg_0", "start": 0, "end": 1,
|
|
"start_byte": 0, "end_byte": len(prompt_bytes)}]
|
|
|
|
# Step 4: Execute through LAIN cognition pipeline
|
|
result = kernel.execute_symbolic(
|
|
manifest=manifest,
|
|
segments=segments,
|
|
payload=payload,
|
|
mode="symbolic",
|
|
context=exec_context,
|
|
)
|
|
|
|
# Step 5: Extract and parse results
|
|
lain_fused_symbol = result.get("fused_symbol")
|
|
fused_symbol = None
|
|
|
|
if lain_fused_symbol:
|
|
fused_symbol = FusedSymbol.from_lain_result(lain_fused_symbol)
|
|
output_text = result.get("output_text") or fused_symbol.summary
|
|
else:
|
|
output_text = result.get("output_text") or prompt
|
|
|
|
# Step 6: Record fusion step if fused_symbol present
|
|
if fused_symbol:
|
|
steps.append(SymbolicStep(
|
|
name="fusion",
|
|
kind="fused_symbol",
|
|
payload={
|
|
"summary": fused_symbol.summary,
|
|
"glyph_ids": fused_symbol.glyph_ids,
|
|
"global_resonance_score": fused_symbol.resonance_map.global_resonance_score,
|
|
},
|
|
context={}
|
|
))
|
|
|
|
return SymbolicPipelineResult(
|
|
steps=steps,
|
|
output_text=output_text,
|
|
fused_symbol=fused_symbol
|
|
)
|