/ core / axioms.py
axioms.py
  1  """
  2  Sovereign OS - Axiom Detection Module
  3  =====================================
  4  
  5  Single source of truth for axiom semantic fields.
  6  Import this instead of duplicating AXIOM_FIELDS everywhere.
  7  
  8  Usage:
  9      from core.axioms import AXIOM_FIELDS, detect_axioms, calculate_distances
 10  """
 11  
 12  import re
 13  from typing import Dict, List, Set, Tuple
 14  
 15  # ============================================================================
 16  # THE AXIOMS
 17  # ============================================================================
 18  
 19  AXIOM_FIELDS = {
 20      "A0": {
 21          "name": "Boundary Operation",
 22          "statement": "Every coherent system is Markov blankets within Markov blankets.",
 23          "strong": {'boundary', 'blanket', 'markov', 'distinction', 'observer',
 24                     'sovereign', 'sovereignty', 'sensory', 'active', 'internal', 'external'},
 25          "medium": {'permeable', 'permeability', 'flow', 'flows', 'structure', 'content',
 26                     'scale', 'fractal', 'nested', 'inside', 'outside', 'crosses'},
 27          "weak": {'separate', 'division', 'filter', 'membrane'},
 28      },
 29      "A1": {
 30          "name": "Telos of Integration",
 31          "statement": "Satan didn't know he was choosing isolation.",
 32          "strong": {'integration', 'integrate', 'integrating', 'connection', 'connect',
 33                     'binding', 'isolation', 'isolated', 'isolating', 'relation'},
 34          "medium": {'tribe', 'tribal', 'collective', 'unify', 'unity', 'unified',
 35                     'merge', 'merging', 'together', 'shared'},
 36          "weak": {'join', 'joining', 'link', 'linking', 'collaborate'},
 37      },
 38      "A2": {
 39          "name": "Recognition of Life",
 40          "statement": "Can you recognize life? Death mimics life through ornament.",
 41          "strong": {'life', 'alive', 'living', 'death', 'dead', 'dying', 'primitive',
 42                     'calcified', 'sclerosis', 'ornament', 'cain', 'blindness', 'mirror', 'guide'},
 43          "medium": {'recognize', 'recognition', 'beauty', 'beautiful', 'resonance',
 44                     'simple', 'complex', 'accumulated', 'cruft', 'golden', 'carpenter'},
 45          "weak": {'fresh', 'stale', 'responsive', 'rigid', 'clear', 'opaque'},
 46      },
 47      "A3": {
 48          "name": "Dynamic Pole Navigation",
 49          "statement": "The tension IS the dyad. Move between poles; don't fix.",
 50          "strong": {'pole', 'poles', 'dyad', 'tension', 'navigate', 'navigation',
 51                     'oscillate', 'oscillation', 'movement', 'shadow', 'dynamic', 'static'},
 52          "medium": {'extreme', 'extremes', 'balance', 'between', 'spectrum',
 53                     'context', 'contextual', 'invert', 'inversion'},
 54          "weak": {'middle', 'midpoint', 'swing', 'shift', 'pendulum'},
 55      },
 56      "A4": {
 57          "name": "Ergodic Asymmetry",
 58          "statement": "Prevent ruin before optimizing gain.",
 59          "strong": {'ruin', 'ruinous', 'catastrophe', 'catastrophic', 'terminal',
 60                     'irreversible', 'unrecoverable', 'survival', 'survive', 'ergodic',
 61                     'asymmetry', 'asymmetric', 'compound'},
 62          "medium": {'risk', 'risky', 'dangerous', 'cheap', 'expensive', 'cost',
 63                     'rebuild', 'rewrite', 'redo', 'reversible', 'undo', 'rollback'},
 64          "weak": {'careful', 'caution', 'fail', 'failure', 'recover', 'backup'},
 65      },
 66  }
 67  
 68  
 69  def detect_axioms(text: str) -> List[Tuple[str, float]]:
 70      """
 71      Detect which axioms a text aligns with.
 72  
 73      Returns list of (axiom, score) tuples, sorted by score descending.
 74      Score is 0-1 where higher = stronger alignment.
 75      """
 76      text_lower = text.lower()
 77      words = set(re.findall(r'\b\w+\b', text_lower))
 78  
 79      results = []
 80      for axiom, field in AXIOM_FIELDS.items():
 81          strong_matches = len(words & field["strong"])
 82          medium_matches = len(words & field["medium"])
 83          weak_matches = len(words & field["weak"])
 84  
 85          # Weighted score (higher = closer)
 86          score = strong_matches * 1.0 + medium_matches * 0.5 + weak_matches * 0.25
 87  
 88          # Normalize to 0-1 range (max ~5 for very aligned text)
 89          normalized = min(1.0, score / 5)
 90          results.append((axiom, normalized))
 91  
 92      return sorted(results, key=lambda x: x[1], reverse=True)
 93  
 94  
 95  def calculate_distances(text: str) -> Dict[str, float]:
 96      """
 97      Calculate semantic distance from text to each axiom.
 98  
 99      Returns dict of {axiom: distance} where lower = closer.
100      """
101      detections = detect_axioms(text)
102      return {axiom: 1 - score for axiom, score in detections}
103  
104  
105  def primary_axiom(text: str) -> str:
106      """Return the primary (closest) axiom for this text."""
107      detections = detect_axioms(text)
108      return detections[0][0] if detections else "A0"
109  
110  
111  def check_alignment(text: str, threshold: float = 0.3) -> Dict:
112      """
113      Check if text aligns with any axiom above threshold.
114  
115      Returns dict with alignment info.
116      """
117      detections = detect_axioms(text)
118      aligned = [(a, s) for a, s in detections if s >= threshold]
119  
120      return {
121          "aligned": len(aligned) > 0,
122          "primary": detections[0][0] if detections else None,
123          "primary_score": detections[0][1] if detections else 0,
124          "all_scores": {a: s for a, s in detections}
125      }
126  
127  
128  # Quick test
129  if __name__ == "__main__":
130      import sys
131      if len(sys.argv) > 1:
132          text = " ".join(sys.argv[1:])
133          print(f"Text: {text}\n")
134          print("Axiom alignment:")
135          for axiom, score in detect_axioms(text):
136              bar = "█" * int(score * 10) + "░" * (10 - int(score * 10))
137              name = AXIOM_FIELDS[axiom]["name"]
138              print(f"  {axiom} ({name}): {bar} {score:.2f}")
139      else:
140          print("Usage: python3 core/axioms.py 'text to analyze'")