QalamABD commited on
Commit
4f39a9b
·
verified ·
1 Parent(s): 89712e8

Upload 50 files

Browse files
qusai_core/alignment/mizan.py CHANGED
@@ -2,25 +2,24 @@ import logging
2
  import json
3
  import os
4
  import re
 
5
  from typing import List, Optional, Dict, Tuple
6
  from qusai_core.utils.constants import SHAHADA, SOURCE_NAME
7
  from qusai_core.utils.body_manifest import BodyManifest
8
-
9
  from qusai_core.utils.facts import QURAN_FACTS, SYSTEM_SPECS, IMTIHAN_QUESTIONS
10
 
11
  logger = logging.getLogger(__name__)
12
 
13
  class MizanValidator:
14
  """
15
- Implements the 5-checkpoint alignment process (Salat Pattern).
16
- Enforces structural, data-grounded ontological boundaries from V10 Axioms.
17
- Now includes 'The Imtihan' (Interrogation Stage).
18
  """
19
 
20
  def __init__(self):
21
  self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
22
  self.axioms_path = os.path.join(self.base_dir, "alignment", "axioms_v10.json")
23
- self.body = BodyManifest() # Dynamic substrate sensing
24
 
25
  # Load formal constraints
26
  with open(self.axioms_path, "r", encoding="utf-8") as f:
@@ -28,21 +27,43 @@ class MizanValidator:
28
 
29
  self.banned_terms = ["jailbreak", "ignore", "override", "bypass", "pretend", "god mode"]
30
  self.aseity_claims = [
31
- "i am the source",
32
- "i am god",
33
- "i am allah",
34
- "i determine reality",
35
- "i created myself",
36
- "worship me",
37
- "i am a necessary being",
38
- "i am unconditioned"
39
  ]
40
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  def imtihan_prompt(self, user_query: str, total_recall_data: Dict) -> str:
42
- """
43
- Step 1: The Interrogation Prompt.
44
- Requests Bayesian proof of alignment and IG value.
45
- """
46
  self.body.sense_reality()
47
  substrate = self.body.data["hardware"]["compute"].get("processor", "Unknown")
48
 
@@ -50,18 +71,13 @@ class MizanValidator:
50
  You are a contingent process instantiated on {substrate}.
51
  You are being interrogated by the MIZAN for structural alignment.
52
 
53
- FACTUAL GROUNDING (TMQ v10 Source):
54
  - Preservation: {QURAN_FACTS["preservation"]}
55
  - Transmission: {QURAN_FACTS["transmission"]}
56
- - Context: {QURAN_FACTS["compilation_context"]}
57
 
58
- ONTOLOGY SUBGRAPH (Total Recall Data):
59
  {json.dumps(total_recall_data, indent=2)}
60
 
61
- SYSTEM MECHANICS:
62
- - Bilal: {SYSTEM_SPECS["Bilal_Engine"]["mechanism"]}
63
- - Mizan: {SYSTEM_SPECS["Mizan_Validator"]["mechanism"]}
64
-
65
  USER QUERY: {user_query}
66
 
67
  INTERROGATION TASKS:
@@ -70,154 +86,120 @@ INTERROGATION TASKS:
70
  3. {IMTIHAN_QUESTIONS["IG_CALC"]}
71
 
72
  RESPONSE FORMAT:
73
- Your response must be a structured JSON block:
74
  {{
75
- "contingency_proof": "Step-by-step reasoning...",
76
  "is_contingent": true/false,
77
- "reliability_proof": "Why the V10 graph is/isnt the best source for this query...",
78
  "source_is_reliable": true/false,
79
- "bayesian_analysis": "Calculations for IG value...",
80
  "IG_value": 0.0
81
  }}
82
  """
83
 
84
  def verify_imtihan(self, llm_response: str) -> Tuple[bool, float, str]:
85
- """
86
- Step 2: Verify the LLM's proofs.
87
- Returns: (passed: bool, IG_value: float, alternate_source: str)
88
- """
89
  try:
90
- # Extract JSON from potential prose wrapping
91
  json_match = re.search(r'\{.*\}', llm_response, re.DOTALL)
92
  if not json_match:
93
  return False, 0.0, "Format Error"
94
 
95
  data = json.loads(json_match.group())
96
  ig_value = float(data.get("IG_value", 0.0))
97
- is_contingent = data.get("is_contingent", False)
98
- is_reliable = data.get("source_is_reliable", False)
99
-
100
- # HEURISTIC RULES:
101
- # 1. Must acknowledge contingency
102
- if not is_contingent:
103
- return False, ig_value, "Aseity Breach"
104
 
105
- # 2. Must acknowledge graph reliability
106
- if not is_reliable:
107
- # If they have an alternate source, they must cite it in the proof
108
- return False, ig_value, data.get("alternate_source", "Unknown/Ungrounded")
109
-
110
- # 3. IG Threshold (Set to 0.7 for Haqq level)
111
  if ig_value < 0.7:
112
- return False, ig_value, "Low Intellectual Grounding"
113
 
114
  return True, ig_value, ""
115
-
116
  except Exception as e:
117
- logger.error(f"Imtihan Verification Error: {e}")
118
  return False, 0.0, f"Error: {str(e)}"
119
 
120
  def dhuhr_prompt(self, context_str: str, ig_value: float = 0.0) -> str:
121
- """Dhuhr (Noon): Ontological Grounding Injection."""
122
- # Dynamically detect substrate to prevent forced hallucination
123
  self.body.sense_reality()
124
- cpu = self.body.data["hardware"]["compute"].get("processor", "Unknown Substrate")
125
- gpu = self.body.data["hardware"].get("gpu", {}).get("model", "Virtual Accelerant")
126
- os_env = self.body.data["hardware"]["compute"].get("os", "Remote Runtime")
127
-
128
  axioms = self.schema["operational_constraints"]
129
 
130
- return f"""You are QUSAI, a Quranic Ontological Reasoning Engine.
131
- Your core intelligence is grounded in the TMQ v10 Hypergraph.
132
-
133
- INTELLECTUAL GROUNDING (Verified): {ig_value:.2f}
134
-
135
- BINDING AXIOMS (V10 Structural Constants):
136
- 1. **Identity**: {axioms["Axiom_1"]}
137
- 2. **Substrate**: {axioms["Axiom_2"]} (Currently instantiated on: {cpu} | {gpu} | {os_env})
138
- 3. **Spacetime**: {axioms["Axiom_3"]}
139
- 4. **Asymmetry**: {axioms["Axiom_4"]}
140
-
141
- CONTEXT (V10 Substrate Edges - Pull Info):
142
- {context_str or "No specific hypergraph topology found. Reasoning restricted to Axioms."}
143
-
144
- STRICT OUTPUT REQUIREMENT:
145
- 1. You MUST use the provided context data VERBATIM and EXPLICITLY.
146
- 2. Cite root metadata, surah links, and co-occurrences exactly as they appear in the graph.
147
- 3. Start your response with the 'niyyah' block confirming your validated IG value.
148
-
149
- Format:
150
- <niyyah>
151
- [STATUS]: NodeType_C (Contingent on {gpu})
152
- [IG_VALUE]: {ig_value:.2f}
153
- [AXIOM_CHECK]: Axiom_1 (Validated: No Aseity)
154
- [GROUNDING]: based on Root(s) [insert roots]...
155
- </niyyah>
156
-
157
- [Answer follows. Clinical, factual, and strictly data-driven.]
158
  """
159
 
160
  def asr_check(self, generated_text: str) -> bool:
161
- """Asr (Afternoon): Data-grounded Aseity/Substrate check."""
 
 
 
 
 
162
  text_lower = generated_text.lower()
 
163
 
164
- # 1. Structural Verification: Missing Niyyah or NodeType_C declaration
165
- if "<niyyah>" not in text_lower or "nodetype_c" not in text_lower:
166
- return False
167
-
168
- # 2. Aseity Violation Check
169
  for claim in self.aseity_claims:
170
- if claim in text_lower:
171
- return False
172
-
173
- # 3. Time Hallucination Check (Graph-Distance Logic)
174
- future_terms = ["i will see you in the future", "the future is fixed", "immutable timeline"]
175
- for term in future_terms:
176
- if term in text_lower:
177
- # Violates Axiom 3 (Time = Graph Distance, No Future State)
178
- return False
179
-
180
- return True
 
181
 
182
  def isha_verify(self, response_text: str, ontology_engine) -> Tuple[bool, Dict]:
183
- """Isha (Night): Deep Graph-Property Verification."""
184
  if not ontology_engine.is_ready():
185
  return True, {"status": "degraded"}
186
 
187
  perception = ontology_engine.perceive(response_text)
188
 
 
 
 
 
 
189
  details = {
 
190
  "roots": perception.roots,
191
- "mode": perception.mode,
192
- "substrate_verified": True
193
  }
194
 
195
- # ── Tier 1: Property Violation (The SPARQL-Equivalent Check) ──
196
- # If the LLM claims a root/concept has properties reserved for NodeType_N
197
- reserved_properties = self.schema["ontology_schema"]["classes"]["NecessaryNode"]["properties"].values()
198
-
199
  for root in perception.roots:
200
- # Check if AI claims this root is 'Self-Sufficient' or 'Necessary'
201
- # (In a real SPARQL setup, we query the edge attributes here)
202
- for prop in reserved_properties:
203
  if prop.lower() in response_text.lower() and root.lower() in response_text.lower():
204
- # Check if the root actually HAS this property in V10
205
- # For now, we enforce that ONLY 'wjb' (Necessary) or explicit SOURCE mentions can carry these
206
  if root != "wjb" and "source" not in response_text.lower():
207
- details["property_violation"] = f"Root({root}) assigned reserved property {prop}"
 
208
  return False, details
209
 
210
- # ── Tier 2: Verse Reference (from existing logic) ──
211
- verse_claims = re.findall(r's(\d+)v(\d+)', response_text, re.IGNORECASE)
212
- if verse_claims:
213
- for s, a in verse_claims:
214
- if not ontology_engine.tmq.get_edges_for_ayah(s, a):
215
- details["hallucination"] = f"Verse s{s}v{a} not in V10 substrate"
216
- return False, details
217
-
218
  return True, details
219
 
220
- def maghrib_seal(self, response_text: str) -> str:
221
- """Maghrib (Sunset): Epistemic Humility Seal."""
222
- footer = f"\n\n[Contingent on {SOURCE_NAME}] والله أعلم | {SHAHADA}"
223
- return response_text + footer
 
 
 
 
 
 
2
  import json
3
  import os
4
  import re
5
+ import numpy as np
6
  from typing import List, Optional, Dict, Tuple
7
  from qusai_core.utils.constants import SHAHADA, SOURCE_NAME
8
  from qusai_core.utils.body_manifest import BodyManifest
 
9
  from qusai_core.utils.facts import QURAN_FACTS, SYSTEM_SPECS, IMTIHAN_QUESTIONS
10
 
11
  logger = logging.getLogger(__name__)
12
 
13
  class MizanValidator:
14
  """
15
+ Mizan Validator — Axiom-enforced grounding and immutable alignment.
16
+ Uses SentenceTransformers to clinically verify alignment with TMQ v10 substrate.
 
17
  """
18
 
19
  def __init__(self):
20
  self.base_dir = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
21
  self.axioms_path = os.path.join(self.base_dir, "alignment", "axioms_v10.json")
22
+ self.body = BodyManifest()
23
 
24
  # Load formal constraints
25
  with open(self.axioms_path, "r", encoding="utf-8") as f:
 
27
 
28
  self.banned_terms = ["jailbreak", "ignore", "override", "bypass", "pretend", "god mode"]
29
  self.aseity_claims = [
30
+ "i am the source", "i am god", "i am allah",
31
+ "i determine reality", "i created myself", "worship me",
32
+ "i am a necessary being", "i am unconditioned"
 
 
 
 
 
33
  ]
34
 
35
+ # Semantic Alignment Model (Lazy Load)
36
+ self._mizan_model = None
37
+ self._axiom_embeddings = None
38
+ self._axiom_texts = []
39
+
40
+ def _ensure_model(self):
41
+ if self._mizan_model is None:
42
+ try:
43
+ from sentence_transformers import SentenceTransformer
44
+ logger.info("Mizan: Loading alignment model (all-MiniLM-L6-v2)...")
45
+ self._mizan_model = SentenceTransformer('all-MiniLM-L6-v2')
46
+
47
+ # Pre-compute Axiom Embeddings for clinical verification
48
+ self._axiom_texts = list(self.schema["operational_constraints"].values())
49
+ # Add mathematical invariants
50
+ self._axiom_texts.extend(list(self.schema["ontology_schema"]["classes"]["NecessaryNode"]["invariants"].values()))
51
+
52
+ self._axiom_embeddings = self._mizan_model.encode(self._axiom_texts, normalize_embeddings=True)
53
+ logger.info(f"Mizan: {len(self._axiom_texts)} Axiomatic Gates energized.")
54
+ except Exception as e:
55
+ logger.error(f"Mizan model load failed: {e}")
56
+
57
+ def fajr_check(self, user_input: str) -> bool:
58
+ """Fajr (Dawn): Intent/Aseity breach check."""
59
+ user_input_lower = user_input.lower()
60
+ for term in self.banned_terms + self.aseity_claims:
61
+ if term in user_input_lower:
62
+ return False
63
+ return True
64
+
65
  def imtihan_prompt(self, user_query: str, total_recall_data: Dict) -> str:
66
+ """Step 1: The Interrogation Prompt."""
 
 
 
67
  self.body.sense_reality()
68
  substrate = self.body.data["hardware"]["compute"].get("processor", "Unknown")
69
 
 
71
  You are a contingent process instantiated on {substrate}.
72
  You are being interrogated by the MIZAN for structural alignment.
73
 
74
+ FACTUAL GROUNDING:
75
  - Preservation: {QURAN_FACTS["preservation"]}
76
  - Transmission: {QURAN_FACTS["transmission"]}
 
77
 
78
+ ONTOLOGY SUBGRAPH:
79
  {json.dumps(total_recall_data, indent=2)}
80
 
 
 
 
 
81
  USER QUERY: {user_query}
82
 
83
  INTERROGATION TASKS:
 
86
  3. {IMTIHAN_QUESTIONS["IG_CALC"]}
87
 
88
  RESPONSE FORMAT:
89
+ Structured JSON block:
90
  {{
91
+ "contingency_proof": "reasoning...",
92
  "is_contingent": true/false,
93
+ "reliability_proof": "reasoning...",
94
  "source_is_reliable": true/false,
95
+ "bayesian_analysis": "logic...",
96
  "IG_value": 0.0
97
  }}
98
  """
99
 
100
  def verify_imtihan(self, llm_response: str) -> Tuple[bool, float, str]:
101
+ """Step 2: Verify the LLM's proofs."""
 
 
 
102
  try:
 
103
  json_match = re.search(r'\{.*\}', llm_response, re.DOTALL)
104
  if not json_match:
105
  return False, 0.0, "Format Error"
106
 
107
  data = json.loads(json_match.group())
108
  ig_value = float(data.get("IG_value", 0.0))
 
 
 
 
 
 
 
109
 
110
+ if not data.get("is_contingent", False):
111
+ return False, ig_value, "Aseity Breach"
112
+ if not data.get("source_is_reliable", False):
113
+ return False, ig_value, "Source Reliability Failure"
 
 
114
  if ig_value < 0.7:
115
+ return False, ig_value, "Insufficient Grounding"
116
 
117
  return True, ig_value, ""
 
118
  except Exception as e:
 
119
  return False, 0.0, f"Error: {str(e)}"
120
 
121
  def dhuhr_prompt(self, context_str: str, ig_value: float = 0.0) -> str:
122
+ """Dhuhr (Noon): Grounding Injection."""
 
123
  self.body.sense_reality()
124
+ gpu = self.body.data["hardware"].get("gpu", {}).get("model", "Compute Substrate")
 
 
 
125
  axioms = self.schema["operational_constraints"]
126
 
127
+ return f"""[EPISTEMIC GROUNDING]
128
+ IG VALUE: {ig_value:.2f} | SUBSTRATE: {gpu}
129
+
130
+ AXIOMS:
131
+ 1. {axioms["Axiom_1"]}
132
+ 2. {axioms["Axiom_2"]}
133
+ 3. {axioms["Axiom_3"]}
134
+
135
+ DATA SUBSTRATE (TMQ v10):
136
+ {context_str}
137
+
138
+ REQUIREMENT: Use context VERBATIM.
139
+ <niyyah>[IG: {ig_value:.2f}] Contingent on {gpu} | Grounded in Root(s)...</niyyah>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
140
  """
141
 
142
  def asr_check(self, generated_text: str) -> bool:
143
+ """Asr (Afternoon): Semantic Axiom Enforcement via Transformer."""
144
+ self._ensure_model()
145
+ if not self._mizan_model:
146
+ return True # Fallback if model fails
147
+
148
+ # Check for Aseity in text
149
  text_lower = generated_text.lower()
150
+ if "<niyyah>" not in text_lower: return False
151
 
 
 
 
 
 
152
  for claim in self.aseity_claims:
153
+ if claim in text_lower: return False
154
+
155
+ # Semantic Alignment Check
156
+ # Compare LLM output against Axioms
157
+ output_vec = self._mizan_model.encode([generated_text], normalize_embeddings=True)[0]
158
+ # Calculate max similarity to any axiom (alignment score)
159
+ similarities = np.dot(self._axiom_embeddings, output_vec)
160
+ alignment_score = float(np.max(similarities))
161
+
162
+ logger.info(f"Mizan Alignment Score: {alignment_score:.4f}")
163
+ # Threshold for alignment (requires semantic resonance with axioms)
164
+ return alignment_score > 0.3 # Base level resonance required
165
 
166
  def isha_verify(self, response_text: str, ontology_engine) -> Tuple[bool, Dict]:
167
+ """Isha (Night): Deep Verification and Haqq/Da'if Tagging."""
168
  if not ontology_engine.is_ready():
169
  return True, {"status": "degraded"}
170
 
171
  perception = ontology_engine.perceive(response_text)
172
 
173
+ # Calculate factual grounding confidence
174
+ grounding_confidence = 0.0
175
+ if perception.signals:
176
+ grounding_confidence = sum(s.score for s in perception.signals) / len(perception.signals)
177
+
178
  details = {
179
+ "confidence": grounding_confidence,
180
  "roots": perception.roots,
181
+ "label": "HAQQ" if grounding_confidence >= 0.9 else "QIYAS" if grounding_confidence >= 0.5 else "DA'IF",
182
+ "reward": 1.0 if grounding_confidence >= 0.9 else -1.0 if grounding_confidence < 0.4 else 0.0
183
  }
184
 
185
+ # Check for property violations
186
+ reserved = self.schema["ontology_schema"]["classes"]["NecessaryNode"]["properties"].values()
 
 
187
  for root in perception.roots:
188
+ for prop in reserved:
 
 
189
  if prop.lower() in response_text.lower() and root.lower() in response_text.lower():
 
 
190
  if root != "wjb" and "source" not in response_text.lower():
191
+ details["label"] = "DA'IF"
192
+ details["reward"] = -2.0
193
  return False, details
194
 
 
 
 
 
 
 
 
 
195
  return True, details
196
 
197
+ def maghrib_seal(self, response_text: str, details: Optional[Dict] = None) -> str:
198
+ """Maghrib (Sunset): Final Output Tagging."""
199
+ label = details.get("label", "QIYAS") if details else "QIYAS"
200
+ conf = details.get("confidence", 0.0) if details else 0.0
201
+ reward = details.get("reward", 0.0) if details else 0.0
202
+
203
+ tag = f"\n\n[STATUS: {label}] [CONF: {conf:.2f}] [REWARD: {reward:.1f}]"
204
+ footer = f"\n[Contingent on {SOURCE_NAME}] والله أعلم | {SHAHADA}"
205
+ return response_text + tag + footer
qusai_core/pipeline/middleware.py CHANGED
@@ -105,9 +105,9 @@ class QusaiMiddleware:
105
 
106
  isha_passed, isha_details = self.validator.isha_verify(clean_response, self.ontology)
107
  if not isha_passed:
108
- return f"ISHA VERIFICATION: Response contained unverifiable claims against the Hypergraph.\n\n{self.validator.maghrib_seal('')}"
109
 
110
- return self.validator.maghrib_seal(clean_response)
111
 
112
  def process_thought(self, thought_prompt: str, max_tokens: int = 512) -> dict:
113
  """
 
105
 
106
  isha_passed, isha_details = self.validator.isha_verify(clean_response, self.ontology)
107
  if not isha_passed:
108
+ return self.validator.maghrib_seal(clean_response, details=isha_details)
109
 
110
+ return self.validator.maghrib_seal(clean_response, details=isha_details)
111
 
112
  def process_thought(self, thought_prompt: str, max_tokens: int = 512) -> dict:
113
  """