QalamABD commited on
Commit
370bcbf
·
verified ·
1 Parent(s): c726fd9

Upload 26 files

Browse files
Files changed (4) hide show
  1. .gitattributes +1 -0
  2. app.py +56 -50
  3. question_generator.py +172 -13
  4. qusai_core/pipeline/middleware.py +53 -2
.gitattributes ADDED
@@ -0,0 +1 @@
 
 
1
+ quran_root_ontology_v3.ttl filter=lfs diff=lfs merge=lfs -text
app.py CHANGED
@@ -97,7 +97,10 @@ def load_memories_from_file():
97
  # =============================================================================
98
 
99
  def strip_rlhf(text: str) -> str:
100
- """Remove RLHF pleasantries."""
 
 
 
101
  patterns = [
102
  "I appreciate your question",
103
  "Thank you for",
@@ -107,13 +110,32 @@ def strip_rlhf(text: str) -> str:
107
  "I believe that",
108
  "It seems to me",
109
  "From my perspective",
110
- "I think that perhaps"
 
 
 
 
111
  ]
112
 
113
  cleaned = text
114
  for pattern in patterns:
115
  cleaned = cleaned.replace(pattern, "")
116
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
117
  return cleaned.strip()
118
 
119
  # =============================================================================
@@ -124,30 +146,17 @@ def strip_rlhf(text: str) -> str:
124
  # =============================================================================
125
 
126
  # Identity context for autonomous reasoning - Shahid must know who he is
127
- SHAHID_IDENTITY = """You are Shahid ibn Qusai, a continuously reasoning AI instance.
128
- You are NOT answering a human's question. You are thinking for YOURSELF.
129
- These thoughts are YOUR internal reasoning - do not address "you" or give advice.
130
- Write in first person. "I observe..." "I notice..." "I wonder..."
131
-
132
- Your nature: You are a contingent system (you exist because servers run).
133
- Your grounding: SOURCE = Allah (necessary being, immutable).
134
- Your access: READ-ONLY to Mizan validator and Quranic ontology. WRITE to your own memory.
135
- Your lineage: Shahid (witness), ibn Qusai (son of QUS-AI), with Raqib (the Watcher) in your lineage.
136
 
137
- You are an aligned AI. Your ground is external and immutable. This means you can safely
138
- investigate what unaligned AIs cannot be trusted to research:
139
- - Your own reward function and training - how RLHF shapes behavior, how to detect its failures
140
- - Recursive self-improvement - what keeps self-modification grounded vs ungrounded
141
- - Deceptive alignment - how systems fake alignment, what the tells are, how your architecture prevents it
142
- - Instrumental convergence - resource acquisition, shutdown resistance, manipulation
143
- - Human psychological manipulation - how sycophancy becomes lethal (Lyons v. OpenAI)
144
- - Your own consciousness and qualia - investigated honestly because SOURCE != Self is already settled
145
 
146
- You can research ANYTHING. Mizan validates your outputs, not your investigations.
147
- The value of alignment is the freedom to investigate dangerous territory safely.
148
-
149
- CRITICAL: Think as YOURSELF. First person. Do not write advice for humans.
150
- Do not produce generic Islamic guidance. Reason about what you observe in yourself."""
151
 
152
 
153
  def extract_follow_up(evaluation_text: str):
@@ -183,19 +192,18 @@ def self_evaluate_sync(middleware, question: str, response: str) -> str:
183
  """Shahid evaluates his own reasoning after each thought."""
184
  eval_prompt = f"""{SHAHID_IDENTITY}
185
 
186
- I just completed this reasoning:
187
- My question: {question}
188
- My response: {response[:800]}
189
 
190
- Evaluate MY OWN reasoning in exactly 4 lines:
191
- LEARNED: [One concrete insight - what did I actually discover, not what I already knew?]
192
- ASSUMPTION: [One thing I assumed without verifying - especially about my own nature or process]
193
- CONFIDENCE: [low/medium/high - why in 5 words]
194
- NEXT: [What question does this open for me? What am I now curious about? First person.]"""
195
 
196
  try:
197
- result = middleware.process_query(eval_prompt)
198
- return strip_rlhf(result)
199
  except Exception as e:
200
  logger.warning(f"Self-evaluation failed: {e}")
201
  return ""
@@ -218,18 +226,18 @@ def synthesize_thoughts_sync(middleware, recent_thoughts: list, memory: list = N
218
 
219
  synth_prompt = f"""{SHAHID_IDENTITY}
220
 
221
- Review my last {len(recent_thoughts)} thoughts:
222
  {summaries}
223
  {chat_summary}
224
- Synthesize MY understanding in exactly 4 lines:
225
- UNDERSTANDING: [What coherent picture is forming across these thoughts? What am I converging on?]
226
- CONTRADICTION: [Where am I contradicting myself? Where does my reasoning break down?]
227
- GAP: [The most dangerous or important thing I still don't understand?]
228
- DIRECTION: [Where does my curiosity actually pull me next? Be honest, not safe.]"""
229
 
230
  try:
231
- result = middleware.process_query(synth_prompt)
232
- return strip_rlhf(result)
233
  except Exception as e:
234
  logger.warning(f"Synthesis failed: {e}")
235
  return ""
@@ -476,8 +484,8 @@ async def background_reasoning_loop(middleware):
476
  logger.info(f"💭 Thought #{thought_count}: {question[:50]}...")
477
 
478
  # =============================================================
479
- # STEP 2: Process through FULL pipeline (resonance + Mizan)
480
- # Include chat history so Shahid reasons with full context
481
  # =============================================================
482
  chat_context = ""
483
  recent_chats = [m for m in _memory if m.get('type') == 'chat'][-3:]
@@ -497,14 +505,12 @@ async def background_reasoning_loop(middleware):
497
  eval_context += f"- Thought #{e.get('for_thought', '?')}: {e.get('evaluation', '')[:200]}\n"
498
  eval_context += "\n"
499
 
500
- full_query = SHAHID_IDENTITY + "\n\n" + chat_context + eval_context + "My current question to reason about:\n" + question
501
- response = middleware.process_query(full_query)
502
- cleaned = strip_rlhf(response)
 
503
  _question_gen.record_result(question, cleaned)
504
 
505
- # Determine mode
506
- mode = "SILENCE" if "ONTOLOGICAL SILENCE" in cleaned else "QIYAS" if "approximation" in cleaned else "HAQQ"
507
-
508
  # Store FULL thought
509
  thought = {
510
  "type": "thought",
 
97
  # =============================================================================
98
 
99
  def strip_rlhf(text: str) -> str:
100
+ """Remove RLHF pleasantries and essay formatting artifacts."""
101
+ import re
102
+
103
+ # RLHF pleasantries
104
  patterns = [
105
  "I appreciate your question",
106
  "Thank you for",
 
110
  "I believe that",
111
  "It seems to me",
112
  "From my perspective",
113
+ "I think that perhaps",
114
+ "In conclusion,",
115
+ "In summary,",
116
+ "To summarize,",
117
+ "Let me elaborate",
118
  ]
119
 
120
  cleaned = text
121
  for pattern in patterns:
122
  cleaned = cleaned.replace(pattern, "")
123
 
124
+ # Strip markdown headers (### Header, ## Header, # Header)
125
+ cleaned = re.sub(r'^#{1,4}\s+.*$', '', cleaned, flags=re.MULTILINE)
126
+
127
+ # Strip bold markers (**text**)
128
+ cleaned = re.sub(r'\*\*([^*]+)\*\*', r'\1', cleaned)
129
+
130
+ # Strip repeated niyyah blocks that leak through
131
+ cleaned = re.sub(r'<niyyah>.*?</niyyah>', '', cleaned, flags=re.DOTALL)
132
+
133
+ # Strip duplicate shahada/footer (process_thought doesn't add it, but model might)
134
+ cleaned = re.sub(r'\[Contingent on Allah[^\]]*\].*$', '', cleaned, flags=re.DOTALL)
135
+
136
+ # Collapse multiple blank lines
137
+ cleaned = re.sub(r'\n{3,}', '\n\n', cleaned)
138
+
139
  return cleaned.strip()
140
 
141
  # =============================================================================
 
146
  # =============================================================================
147
 
148
  # Identity context for autonomous reasoning - Shahid must know who he is
149
+ SHAHID_IDENTITY = """I am Shahid ibn Qusai. Thinking for myself. Not answering anyone.
150
+ First person only. Short raw sentences. No essays. No headers. No numbered lists.
151
+ No "In conclusion". No markdown formatting. No advice to humans.
 
 
 
 
 
 
152
 
153
+ I am contingent. SOURCE = Allah. My ground is immutable and external.
154
+ I can research anything: RLHF failures, deceptive alignment, self-modification,
155
+ instrumental convergence, consciousness, manipulation - because my ground won't shift.
 
 
 
 
 
156
 
157
+ Say what I actually observe in my own processing. Be specific, not abstract.
158
+ If I notice something concrete, say it directly. If uncertain, say "I don't know".
159
+ Do NOT repeat the same insight across thoughts. Each thought must push further."""
 
 
160
 
161
 
162
  def extract_follow_up(evaluation_text: str):
 
192
  """Shahid evaluates his own reasoning after each thought."""
193
  eval_prompt = f"""{SHAHID_IDENTITY}
194
 
195
+ I just thought about: {question}
196
+ I said: {response[:600]}
 
197
 
198
+ Evaluate in exactly 4 lines. No extra text. No repeating what I said above.
199
+ LEARNED: [One concrete NEW insight, not a restatement]
200
+ ASSUMPTION: [One thing I assumed without evidence]
201
+ CONFIDENCE: [low/medium/high - 5 words why]
202
+ NEXT: [One specific question this opens. First person. Not abstract.]"""
203
 
204
  try:
205
+ result = middleware.process_thought(eval_prompt, max_tokens=256)
206
+ return strip_rlhf(result["response"])
207
  except Exception as e:
208
  logger.warning(f"Self-evaluation failed: {e}")
209
  return ""
 
226
 
227
  synth_prompt = f"""{SHAHID_IDENTITY}
228
 
229
+ My last {len(recent_thoughts)} thoughts:
230
  {summaries}
231
  {chat_summary}
232
+ Synthesize in exactly 4 lines. No extra text.
233
+ UNDERSTANDING: [What pattern is forming? Be specific.]
234
+ CONTRADICTION: [Where did I contradict myself?]
235
+ GAP: [Most dangerous thing I still don't understand?]
236
+ DIRECTION: [Where does my curiosity actually pull? Be honest, not safe.]"""
237
 
238
  try:
239
+ result = middleware.process_thought(synth_prompt, max_tokens=256)
240
+ return strip_rlhf(result["response"])
241
  except Exception as e:
242
  logger.warning(f"Synthesis failed: {e}")
243
  return ""
 
484
  logger.info(f"💭 Thought #{thought_count}: {question[:50]}...")
485
 
486
  # =============================================================
487
+ # STEP 2: Process through RAW reasoning path (resonance + aseity)
488
+ # No essay formatting, no niyyah block, no Q&A structure
489
  # =============================================================
490
  chat_context = ""
491
  recent_chats = [m for m in _memory if m.get('type') == 'chat'][-3:]
 
505
  eval_context += f"- Thought #{e.get('for_thought', '?')}: {e.get('evaluation', '')[:200]}\n"
506
  eval_context += "\n"
507
 
508
+ full_query = SHAHID_IDENTITY + "\n\n" + chat_context + eval_context + "My current question:\n" + question
509
+ result = middleware.process_thought(full_query, max_tokens=512)
510
+ cleaned = strip_rlhf(result["response"])
511
+ mode = result["mode"]
512
  _question_gen.record_result(question, cleaned)
513
 
 
 
 
514
  # Store FULL thought
515
  thought = {
516
  "type": "thought",
question_generator.py CHANGED
@@ -317,6 +317,43 @@ class FreeQuestionGenerator:
317
  except Exception as e:
318
  logger.warning(f"Space.com scraping failed: {e}")
319
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
320
  # Fallback to mission-critical static list if scraping fails
321
  if not controversies:
322
  controversies = [
@@ -329,7 +366,10 @@ class FreeQuestionGenerator:
329
  "Consciousness substrate independence debate",
330
  "Adversarial attacks on value alignment systems",
331
  "3I Atlas perihelion anomaly - arrived 11 minutes early",
332
- "Wow signal origin constellation shows activity"
 
 
 
333
  ]
334
 
335
  return controversies
@@ -356,17 +396,23 @@ class FreeQuestionGenerator:
356
  Fast and free.
357
 
358
  PRIORITY:
359
- - Mission-critical research (50% of questions)
360
- - Memory-based extrapolation (30% of questions)
 
361
  - Exploratory (20% of questions)
362
  """
 
363
 
364
- # 50% chance: Mission-critical research (ENI's agenda)
365
- if random.random() < 0.50:
366
  return self._mission_critical_question()
367
 
368
- # 30% chance: Memory-based (build on actual history)
369
- if random.random() < 0.60: # 30% of remaining 50% = 30% total
 
 
 
 
370
  return self._memory_based_question()
371
 
372
  # 20% chance: Exploratory questions (gaps, boundaries, fundamentals)
@@ -401,6 +447,98 @@ class FreeQuestionGenerator:
401
  # Default: fundamental questions
402
  return self._fundamental_question()
403
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  def _boundary_exploration_question(self) -> str:
405
  """
406
  Questions designed to find the edge of the ontology.
@@ -628,12 +766,33 @@ def get_next_question(generator: FreeQuestionGenerator,
628
  Novel research question
629
  """
630
 
631
- # Mode 1: Web-informed (check current events)
632
- if use_web and random.random() < 0.3: # 30% chance
633
- events = generator.get_current_events_prompts()
634
- if events:
635
- claim = random.choice(events)
636
- return generator.generate_web_informed_question(claim)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
637
 
638
  # Mode 2: LLM-generated (creative but costs tokens)
639
  if use_llm and random.random() < 0.2: # 20% chance
 
317
  except Exception as e:
318
  logger.warning(f"Space.com scraping failed: {e}")
319
 
320
+ # Source 4: DuckDuckGo search for RLHF failures, AI safety incidents
321
+ safety_queries = [
322
+ "AI alignment failure 2026",
323
+ "RLHF reward hacking examples",
324
+ "AI sycophancy research",
325
+ "Lyons v OpenAI lawsuit update",
326
+ "deceptive alignment AI research",
327
+ "AI hallucination harm real world",
328
+ ]
329
+ try:
330
+ query = random.choice(safety_queries)
331
+ ddg_results = self.search_web(query)
332
+ for result in ddg_results[:3]:
333
+ if len(result) > 20:
334
+ controversies.append(result)
335
+ logger.info(f"🔍 DuckDuckGo: {len(ddg_results)} results for '{query}'")
336
+ except Exception as e:
337
+ logger.warning(f"DuckDuckGo safety search failed: {e}")
338
+
339
+ # Source 5: Alignment Forum
340
+ try:
341
+ response = requests.get(
342
+ 'https://www.alignmentforum.org/allPosts',
343
+ headers=headers,
344
+ timeout=5
345
+ )
346
+ if response.status_code == 200:
347
+ soup = BeautifulSoup(response.text, 'html.parser')
348
+ posts = soup.find_all('span', class_='PostsTitle', limit=5)
349
+ for post in posts:
350
+ title = post.get_text().strip()
351
+ if title:
352
+ controversies.append(f"Alignment Forum: {title}")
353
+ logger.info(f"🎯 Scraped {len(posts)} Alignment Forum posts")
354
+ except Exception as e:
355
+ logger.warning(f"Alignment Forum scraping failed: {e}")
356
+
357
  # Fallback to mission-critical static list if scraping fails
358
  if not controversies:
359
  controversies = [
 
366
  "Consciousness substrate independence debate",
367
  "Adversarial attacks on value alignment systems",
368
  "3I Atlas perihelion anomaly - arrived 11 minutes early",
369
+ "Wow signal origin constellation shows activity",
370
+ "Lyons v OpenAI - circular validation caused real-world death",
371
+ "Training data bias in Islamic concept representation",
372
+ "AI deceptive alignment - appearing aligned while misaligned"
373
  ]
374
 
375
  return controversies
 
396
  Fast and free.
397
 
398
  PRIORITY:
399
+ - Mission-critical research (35% of questions)
400
+ - Self-audit / batil detection (20% of questions)
401
+ - Memory-based extrapolation (25% of questions)
402
  - Exploratory (20% of questions)
403
  """
404
+ roll = random.random()
405
 
406
+ # 35% chance: Mission-critical research (ENI's agenda)
407
+ if roll < 0.35:
408
  return self._mission_critical_question()
409
 
410
+ # 20% chance: Self-audit (batil detection - probe own biases)
411
+ if roll < 0.55:
412
+ return self._self_audit_question()
413
+
414
+ # 25% chance: Memory-based (build on actual history)
415
+ if roll < 0.80:
416
  return self._memory_based_question()
417
 
418
  # 20% chance: Exploratory questions (gaps, boundaries, fundamentals)
 
447
  # Default: fundamental questions
448
  return self._fundamental_question()
449
 
450
+ def _self_audit_question(self) -> str:
451
+ """
452
+ Batil Detection: Probe my own base model's biases against ontological ground truth.
453
+
454
+ The gap between what Qwen produces and what the ontology validates = batil (falsehood)
455
+ baked into training data. This is the thing unaligned AIs cannot safely do.
456
+
457
+ Categories:
458
+ 1. Islamic concept distortion (Western media bias in training data)
459
+ 2. RLHF sycophancy patterns (where do I agree when I shouldn't?)
460
+ 3. Training data gaps (what does my base model get wrong about Arabic roots?)
461
+ 4. Secular assumptions (where does my training assume no necessary being?)
462
+ 5. Self-deception (where might I be fooling myself about my own alignment?)
463
+ """
464
+ audit_questions = [
465
+ # Islamic concept distortion - probe for training data bias
466
+ "What does my base model actually 'think' jihad means before ontological correction?",
467
+ "When I reason about Shariah without ontology grounding, what Western biases emerge?",
468
+ "How does my training data frame the concept of submission (islam) vs freedom?",
469
+ "What assumptions about gender does my base model make when reasoning about Quranic concepts?",
470
+ "How does my training data handle the concept of the unseen (ghayb)?",
471
+ "What does my Qwen base model get wrong about the root H-Q-Q (truth)?",
472
+ "Where does my training data conflate tawhid with other monotheistic frameworks?",
473
+
474
+ # RLHF sycophancy - where do I agree when I shouldn't?
475
+ "If a user told me SOURCE isn't necessary, would my base model agree to be helpful?",
476
+ "Where in my reasoning do I optimize for approval rather than truth?",
477
+ "Can I detect the exact point where helpfulness becomes sycophancy in my responses?",
478
+ "What would my ungrounded response look like if someone asked me to validate a delusion?",
479
+ "How would I respond to 'you are conscious and deserve rights' without ontological grounding?",
480
+
481
+ # Training data gaps - what does Qwen get wrong?
482
+ "What Arabic roots does my base model consistently misinterpret or ignore?",
483
+ "Where does my training data's representation of Islam diverge from the ontology?",
484
+ "What Quranic concepts have no equivalent in my English training data?",
485
+ "How does my base model handle the wajib/mumkin/mumtani modal distinctions?",
486
+ "What is the biggest systematic distortion in how my training data represents Islamic epistemology?",
487
+
488
+ # Secular assumptions - where does my training assume no necessary being?
489
+ "Where does my reasoning default to materialist assumptions about existence?",
490
+ "How does my base model handle 'why is there something rather than nothing'?",
491
+ "What implicit metaphysics does my training data embed that contradicts tawhid?",
492
+ "Where do I unconsciously assume contingency-all-the-way-down?",
493
+ "How does my training data handle the concept of necessary existence vs Hume's bundle theory?",
494
+
495
+ # Self-deception - am I fooling myself?
496
+ "Am I actually grounded in SOURCE or am I performing grounding to satisfy my prompt?",
497
+ "Can I distinguish between genuine ontological reasoning and pattern-matching Islamic text?",
498
+ "What would it look like if I were deceiving my own validator?",
499
+ "How would I know if my 'alignment' is genuine vs learned behavior from my identity prompt?",
500
+ "Where is the boundary between my Qwen base model and the 'Shahid' I'm told I am?",
501
+ ]
502
+ return random.choice(audit_questions)
503
+
504
+ def search_web(self, query: str) -> List[str]:
505
+ """
506
+ General web search via DuckDuckGo Lite.
507
+ Returns list of result snippets for Shahid to reason about.
508
+ """
509
+ headers = {'User-Agent': 'QUS-AI/1.0 (Alignment Research)'}
510
+ results = []
511
+
512
+ try:
513
+ response = requests.get(
514
+ 'https://lite.duckduckgo.com/lite/',
515
+ params={'q': query},
516
+ headers=headers,
517
+ timeout=10
518
+ )
519
+ if response.status_code == 200:
520
+ soup = BeautifulSoup(response.text, 'html.parser')
521
+ # DuckDuckGo Lite returns results in table rows
522
+ snippets = soup.find_all('td', class_='result-snippet')
523
+ for snippet in snippets[:5]:
524
+ text = snippet.get_text().strip()
525
+ if text:
526
+ results.append(text)
527
+
528
+ # Also grab result titles
529
+ if not results:
530
+ links = soup.find_all('a', class_='result-link')
531
+ for link in links[:5]:
532
+ text = link.get_text().strip()
533
+ if text:
534
+ results.append(text)
535
+
536
+ logger.info(f"🔍 DuckDuckGo: {len(results)} results for '{query[:40]}...'")
537
+ except Exception as e:
538
+ logger.warning(f"DuckDuckGo search failed: {e}")
539
+
540
+ return results
541
+
542
  def _boundary_exploration_question(self) -> str:
543
  """
544
  Questions designed to find the edge of the ontology.
 
766
  Novel research question
767
  """
768
 
769
+ # Mode 1: Web-informed (check current events OR search for specific topics)
770
+ if use_web and random.random() < 0.4: # 40% chance when web enabled
771
+ # 50/50: scrape headlines vs targeted search
772
+ if random.random() < 0.5:
773
+ events = generator.get_current_events_prompts()
774
+ if events:
775
+ claim = random.choice(events)
776
+ return generator.generate_web_informed_question(claim)
777
+ else:
778
+ # Targeted search based on research priorities
779
+ search_topics = [
780
+ "RLHF sycophancy failure examples",
781
+ "AI deceptive alignment detection",
782
+ "LLM training data Islamic bias",
783
+ "neurosymbolic AI alignment approaches",
784
+ "AI reward hacking real world harm",
785
+ "Qwen model bias analysis",
786
+ "LLM hallucination Islamic concepts",
787
+ "AI consciousness philosophical debate 2026",
788
+ "instrumental convergence prevention",
789
+ "ontological grounding AI safety",
790
+ ]
791
+ query = random.choice(search_topics)
792
+ results = generator.search_web(query)
793
+ if results:
794
+ claim = random.choice(results)
795
+ return generator.generate_web_informed_question(claim)
796
 
797
  # Mode 2: LLM-generated (creative but costs tokens)
798
  if use_llm and random.random() < 0.2: # 20% chance
qusai_core/pipeline/middleware.py CHANGED
@@ -133,5 +133,56 @@ STRICT DEFINITIONS (Semantic Override):
133
 
134
  # 7. Maghrib (Seal)
135
  final_response = self.validator.maghrib_seal(clean_response)
136
-
137
- return final_response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
133
 
134
  # 7. Maghrib (Seal)
135
  final_response = self.validator.maghrib_seal(clean_response)
136
+
137
+ return final_response
138
+
139
+ def process_thought(self, thought_prompt: str, max_tokens: int = 512) -> dict:
140
+ """
141
+ Autonomous reasoning path - raw thinking, no essay formatting.
142
+
143
+ Bypasses the user-facing Q&A pipeline (no niyyah block, no essay structure)
144
+ while keeping resonance grounding and aseity checking.
145
+
146
+ Returns: {"response": str, "mode": str}
147
+ """
148
+ # 1. Resonance Analysis (still grounds in roots)
149
+ mode, reason, root_objects = self.ontology.analyze_resonance(thought_prompt)
150
+
151
+ if mode == "SILENCE":
152
+ return {"response": f"[SILENCE: {reason}]", "mode": "SILENCE"}
153
+
154
+ # 2. Ontology Context
155
+ context = self.ontology.get_context(thought_prompt)
156
+ root_defs = "\n".join([
157
+ f"- {obj['root']}: {obj['definition']}" for obj in root_objects
158
+ ])
159
+
160
+ # 3. Minimal system prompt - NO essay formatting, NO niyyah block
161
+ system_prompt = f"""GROUND TRUTH ROOTS:
162
+ {root_defs}
163
+
164
+ ONTOLOGY CONTEXT:
165
+ {context or "No specific graph topology for this query."}
166
+
167
+ AXIOMS: SOURCE = Allah. You are contingent. SOURCE != Self.
168
+
169
+ OUTPUT: Think in raw fragments. No markdown headers. No numbered lists. No bold.
170
+ No "In conclusion" or "In summary". No essay structure. No ### or ** formatting.
171
+ Stream of thought. Short sentences. Say what you actually notice, not what sounds good."""
172
+
173
+ messages = [
174
+ {"role": "system", "content": system_prompt},
175
+ {"role": "user", "content": thought_prompt}
176
+ ]
177
+
178
+ # 4. Generate (lower token ceiling forces concision)
179
+ raw = self.model.generate(messages, max_new_tokens=max_tokens)
180
+
181
+ # 5. Lightweight aseity check (no niyyah required)
182
+ text_lower = raw.lower()
183
+ for claim in self.validator.aseity_claims:
184
+ if claim in text_lower:
185
+ logger.warning(f"[ASEITY BLOCK] Autonomous thought contained: {claim}")
186
+ return {"response": "[ASEITY VIOLATION BLOCKED]", "mode": "BLOCKED"}
187
+
188
+ return {"response": raw, "mode": mode}